update to 1.3.19

Spanish localization by Borja Campina
Applied pull request by Yuri Orlov
(https://github.com/DrKLO/Telegram/pull/27)
This commit is contained in:
DrKLO 2014-02-04 22:36:55 +04:00
parent 1a4d0786ec
commit 9814a6e927
110 changed files with 6238 additions and 3457 deletions

View file

@ -3,7 +3,7 @@ buildscript {
mavenCentral() mavenCentral()
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:0.7.+' classpath 'com.android.tools.build:gradle:0.8.+'
} }
} }
apply plugin: 'android' apply plugin: 'android'
@ -31,7 +31,7 @@ tasks.withType(JavaCompile) {
} }
dependencies { dependencies {
compile 'com.google.android.gms:play-services:4.0.+' compile 'com.google.android.gms:play-services:4.1.+'
compile 'net.hockeyapp.android:HockeySDK:3.0.1' compile 'net.hockeyapp.android:HockeySDK:3.0.1'
compile 'com.android.support:support-v4:19.0.+' compile 'com.android.support:support-v4:19.0.+'
compile 'com.android.support:appcompat-v7:19.0.+' compile 'com.android.support:appcompat-v7:19.0.+'
@ -40,7 +40,7 @@ dependencies {
android { android {
compileSdkVersion 19 compileSdkVersion 19
buildToolsVersion '19.0.0' buildToolsVersion '19.0.1'
signingConfigs { signingConfigs {
debug { debug {

View file

@ -1,15 +1,15 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.telegram.messenger" package="org.telegram.messenger"
android:versionCode="131" android:versionCode="148"
android:versionName="1.3.7"> android:versionName="1.3.19">
<supports-screens android:anyDensity="true" <supports-screens android:anyDensity="true"
android:smallScreens="true" android:smallScreens="true"
android:normalScreens="true" android:normalScreens="true"
android:largeScreens="true" android:largeScreens="true"
android:resizeable="true" android:resizeable="true"
android:xlargeScreens="true"/> android:xlargeScreens="true"/>
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" /> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" />
@ -63,11 +63,12 @@
android:largeHeap="true"> android:largeHeap="true">
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="your-google-maps-api-key-here" /> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="your-google-maps-api-key-here" />
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
<activity <activity
android:name="org.telegram.ui.LaunchActivity" android:name="org.telegram.ui.LaunchActivity"
android:windowSoftInputMode="adjustResize" android:windowSoftInputMode="adjustResize"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"> android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
@ -135,8 +136,8 @@
</receiver> </receiver>
<receiver <receiver
android:name="org.telegram.messenger.GcmBroadcastReceiver" android:name="org.telegram.messenger.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" > android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter> <intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" /> <action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" /> <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
@ -150,7 +151,7 @@
<action android:name="android.accounts.AccountAuthenticator"/> <action android:name="android.accounts.AccountAuthenticator"/>
</intent-filter> </intent-filter>
<meta-data android:name="android.accounts.AccountAuthenticator" <meta-data android:name="android.accounts.AccountAuthenticator"
android:resource="@xml/auth"/> android:resource="@xml/auth"/>
</service> </service>
<service android:name="org.telegram.messenger.ContactsSyncAdapterService" <service android:name="org.telegram.messenger.ContactsSyncAdapterService"
@ -159,13 +160,12 @@
<action android:name="android.content.SyncAdapter" /> <action android:name="android.content.SyncAdapter" />
</intent-filter> </intent-filter>
<meta-data android:name="android.content.SyncAdapter" <meta-data android:name="android.content.SyncAdapter"
android:resource="@xml/sync_contacts" /> android:resource="@xml/sync_contacts" />
<meta-data android:name="android.provider.CONTACTS_STRUCTURE" <meta-data android:name="android.provider.CONTACTS_STRUCTURE"
android:resource="@xml/contacts" /> android:resource="@xml/contacts" />
</service> </service>
<uses-library android:name="com.google.android.maps" android:required="false"/> <uses-library android:name="com.google.android.maps" android:required="false"/>
</application> </application>
</manifest> </manifest>

View file

@ -32,7 +32,7 @@ public class TLObject {
} }
public int layer () { public int layer () {
return 8; return 11;
} }
public void parseVector(TLRPC.Vector vector, SerializedData data) { public void parseVector(TLRPC.Vector vector, SerializedData data) {

View file

@ -15,6 +15,7 @@ import android.net.ConnectivityManager;
import android.net.NetworkInfo; import android.net.NetworkInfo;
import android.os.Build; import android.os.Build;
import android.util.Base64; import android.util.Base64;
import android.util.Log;
import org.telegram.TL.TLClassStore; import org.telegram.TL.TLClassStore;
import org.telegram.TL.TLObject; import org.telegram.TL.TLObject;
@ -33,7 +34,7 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.TcpConnectionDelegate { public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.TcpConnectionDelegate {
public static boolean DEBUG_VERSION = false; public static boolean DEBUG_VERSION = true;
public static int APP_ID = 2458; public static int APP_ID = 2458;
public static String APP_HASH = "5bce48dc7d331e62c955669eb7233217"; public static String APP_HASH = "5bce48dc7d331e62c955669eb7233217";
public static String HOCKEY_APP_HASH = "your-hockeyapp-api-key-here"; public static String HOCKEY_APP_HASH = "your-hockeyapp-api-key-here";
@ -100,35 +101,55 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
public void run() { public void run() {
long currentTime = System.currentTimeMillis(); long currentTime = System.currentTimeMillis();
if (ApplicationLoader.lastPauseTime != 0 && ApplicationLoader.lastPauseTime < currentTime - nextSleepTimeout) { if (ApplicationLoader.lastPauseTime != 0 && ApplicationLoader.lastPauseTime < currentTime - nextSleepTimeout) {
if (!paused) { boolean dontSleep = false;
FileLog.e("tmessages", "pausing network and timers by sleep time = " + nextSleepTimeout); for (RPCRequest request : runningRequests) {
for (Datacenter datacenter : datacenters.values()) { if (request.retryCount < 10 && (request.runningStartTime + 60 > (int)(currentTime / 1000)) && ((request.flags & RPCRequest.RPCRequestClassDownloadMedia) != 0 || (request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0)) {
if (datacenter.connection != null) { dontSleep = true;
datacenter.connection.suspendConnection(true); break;
} }
if (datacenter.uploadConnection != null) { }
datacenter.uploadConnection.suspendConnection(true); if (!dontSleep) {
} for (RPCRequest request : requestQueue) {
if (datacenter.downloadConnection != null) { if ((request.flags & RPCRequest.RPCRequestClassDownloadMedia) != 0 || (request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0) {
datacenter.downloadConnection.suspendConnection(true); dontSleep = true;
break;
} }
} }
} }
try { if (!dontSleep) {
paused = true; if (!paused) {
if (ApplicationLoader.lastPauseTime < currentTime - nextSleepTimeout - nextWakeUpTimeout) { FileLog.e("tmessages", "pausing network and timers by sleep time = " + nextSleepTimeout);
ApplicationLoader.lastPauseTime = currentTime; for (Datacenter datacenter : datacenters.values()) {
nextSleepTimeout = 30000; if (datacenter.connection != null) {
FileLog.e("tmessages", "wakeup network in background by wakeup time = " + nextWakeUpTimeout); datacenter.connection.suspendConnection(true);
if (nextWakeUpTimeout < 30 * 60 * 1000) { }
nextWakeUpTimeout *= 2; if (datacenter.uploadConnection != null) {
datacenter.uploadConnection.suspendConnection(true);
}
if (datacenter.downloadConnection != null) {
datacenter.downloadConnection.suspendConnection(true);
}
} }
} else {
Thread.sleep(500);
return;
} }
} catch (Exception e) { try {
FileLog.e("tmessages", e); paused = true;
if (ApplicationLoader.lastPauseTime < currentTime - nextSleepTimeout - nextWakeUpTimeout) {
ApplicationLoader.lastPauseTime = currentTime;
nextSleepTimeout = 30000;
FileLog.e("tmessages", "wakeup network in background by wakeup time = " + nextWakeUpTimeout);
if (nextWakeUpTimeout < 30 * 60 * 1000) {
nextWakeUpTimeout *= 2;
}
} else {
Thread.sleep(500);
return;
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
} else {
ApplicationLoader.lastPauseTime += 30 * 1000;
FileLog.e("tmessages", "don't sleep 30 seconds because of upload or download request");
} }
} }
if (paused) { if (paused) {
@ -240,8 +261,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
if (datacenterSetId == useDifferentBackend) { if (datacenterSetId == useDifferentBackend) {
currentDatacenterId = preferences.getInt("currentDatacenterId", 0); currentDatacenterId = preferences.getInt("currentDatacenterId", 0);
timeDifference = preferences.getInt("timeDifference", 0); timeDifference = preferences.getInt("timeDifference", 0);
lastDcUpdateTime = preferences.getInt("lastDcUpdateTime", 0); //TODO uncomment lastDcUpdateTime = preferences.getInt("lastDcUpdateTime", 0);
//lastDcUpdateTime = 0;
try { try {
sessionsToDestroy.clear(); sessionsToDestroy.clear();
String sessionsString = preferences.getString("sessionsToDestroy", null); String sessionsString = preferences.getString("sessionsToDestroy", null);
@ -635,7 +655,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
TLObject wrapInLayer(TLObject object, int datacenterId, RPCRequest request) { TLObject wrapInLayer(TLObject object, int datacenterId, RPCRequest request) {
if (object.layer() > 0) { if (object.layer() > 0) {
Datacenter datacenter = datacenterWithId(datacenterId); Datacenter datacenter = datacenterWithId(datacenterId);
if (datacenter.lastInitVersion != currentAppVersion) { if (datacenter == null || datacenter.lastInitVersion != currentAppVersion) {
request.initRequest = true; request.initRequest = true;
TLRPC.initConnection invoke = new TLRPC.initConnection(); TLRPC.initConnection invoke = new TLRPC.initConnection();
invoke.query = object; invoke.query = object;
@ -704,6 +724,12 @@ 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)) {
ApplicationLoader.lastPauseTime = System.currentTimeMillis();
nextSleepTimeout = 30000;
FileLog.e("tmessages", "wakeup by download or upload request");
}
processRequestQueue(0, 0); processRequestQueue(0, 0);
} }
}); });
@ -941,6 +967,12 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
Integer tokenIt = activeTransportTokens.get(requestDatacenter.datacenterId); Integer tokenIt = activeTransportTokens.get(requestDatacenter.datacenterId);
int datacenterTransportToken = tokenIt != null ? tokenIt : 0; 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; double maxTimeout = 8.0;
if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0) { if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0) {
@ -952,12 +984,18 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
FileLog.d("tmessages", "Don't have any network connection, skipping download request"); FileLog.d("tmessages", "Don't have any network connection, skipping download request");
continue; continue;
} }
if (datacenterDownloadTransportToken == 0) {
continue;
}
maxTimeout = 40.0; maxTimeout = 40.0;
} else if ((request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0) { } else if ((request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0) {
if (!haveNetwork) { if (!haveNetwork) {
FileLog.d("tmessages", "Don't have any network connection, skipping upload request"); FileLog.d("tmessages", "Don't have any network connection, skipping upload request");
continue; continue;
} }
if (datacenterUploadTransportToken == 0) {
continue;
}
maxTimeout = 30.0; maxTimeout = 30.0;
} }
@ -988,20 +1026,19 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
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 ((request.flags & RPCRequest.RPCRequestClassDownloadMedia) != 0) {
int downloadToken = requestDatacenter.downloadConnection.channelToken; if (datacenterDownloadTransportToken != 0 && request.transportChannelToken == datacenterDownloadTransportToken) {
if (downloadToken != 0 && request.transportChannelToken == downloadToken) {
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) { } else if ((request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0) {
int uploadToken = requestDatacenter.uploadConnection.channelToken; if (datacenterUploadTransportToken != 0 && request.transportChannelToken == datacenterUploadTransportToken) {
if (uploadToken != 0 && request.transportChannelToken == uploadToken) {
FileLog.d("tmessages", "Request upload token is valid, not retrying " + request.rawRequest); FileLog.d("tmessages", "Request upload token is valid, not retrying " + request.rawRequest);
continue; continue;
} }
} }
} }
request.retryCount++;
NetworkMessage networkMessage = new NetworkMessage(); NetworkMessage networkMessage = new NetworkMessage();
networkMessage.protoMessage = new TLRPC.TL_protoMessage(); networkMessage.protoMessage = new TLRPC.TL_protoMessage();
@ -1022,10 +1059,12 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
request.transportChannelToken = datacenterTransportToken; request.transportChannelToken = datacenterTransportToken;
addMessageToDatacenter(genericMessagesToDatacenters, requestDatacenter.datacenterId, networkMessage); addMessageToDatacenter(genericMessagesToDatacenters, requestDatacenter.datacenterId, networkMessage);
} else if ((request.flags & RPCRequest.RPCRequestClassDownloadMedia) != 0) { } else if ((request.flags & RPCRequest.RPCRequestClassDownloadMedia) != 0) {
request.transportChannelToken = datacenterDownloadTransportToken;
ArrayList<NetworkMessage> arr = new ArrayList<NetworkMessage>(); ArrayList<NetworkMessage> arr = new ArrayList<NetworkMessage>();
arr.add(networkMessage); arr.add(networkMessage);
proceedToSendingMessages(arr, sessionId, requestDatacenter.downloadConnection, false, false); proceedToSendingMessages(arr, sessionId, requestDatacenter.downloadConnection, false, false);
} else if ((request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0) { } else if ((request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0) {
request.transportChannelToken = datacenterUploadTransportToken;
ArrayList<NetworkMessage> arr = new ArrayList<NetworkMessage>(); ArrayList<NetworkMessage> arr = new ArrayList<NetworkMessage>();
arr.add(networkMessage); arr.add(networkMessage);
proceedToSendingMessages(arr, sessionId, requestDatacenter.uploadConnection, false, false); proceedToSendingMessages(arr, sessionId, requestDatacenter.uploadConnection, false, false);
@ -1147,6 +1186,9 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
continue; 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) {
@ -1158,6 +1200,9 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
continue; continue;
} }
Integer downloadTokenIt = activeDownloadTransportTokens.get(requestDatacenter.datacenterId);
request.transportChannelToken = downloadTokenIt != null ? downloadTokenIt : 0;
downloadRunningRequestCount++; downloadRunningRequestCount++;
} }
} }
@ -1166,8 +1211,9 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
SerializedData os = new SerializedData(); SerializedData os = new SerializedData();
request.rpcRequest.serializeToStream(os); request.rpcRequest.serializeToStream(os);
int requestLength = os.length();
if (os.length() != 0) { if (requestLength != 0) {
long sessionId = 0; long sessionId = 0;
if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0) { if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0) {
sessionId = requestDatacenter.authSessionId; sessionId = requestDatacenter.authSessionId;
@ -1177,18 +1223,31 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
sessionId = requestDatacenter.authUploadSessionId; sessionId = requestDatacenter.authUploadSessionId;
} }
if ((request.flags & RPCRequest.RPCRequestClassCanCompress) != 0) {
try {
byte[] data = Utilities.compress(os.toByteArray());
if (data.length < requestLength) {
TLRPC.TL_gzip_packed packed = new TLRPC.TL_gzip_packed();
packed.packed_data = data;
request.rpcRequest = packed;
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
NetworkMessage networkMessage = new NetworkMessage(); NetworkMessage networkMessage = new NetworkMessage();
networkMessage.protoMessage = new TLRPC.TL_protoMessage(); networkMessage.protoMessage = new TLRPC.TL_protoMessage();
networkMessage.protoMessage.msg_id = messageId; networkMessage.protoMessage.msg_id = messageId;
networkMessage.protoMessage.seqno = generateMessageSeqNo(sessionId, true); networkMessage.protoMessage.seqno = generateMessageSeqNo(sessionId, true);
networkMessage.protoMessage.bytes = os.length(); networkMessage.protoMessage.bytes = requestLength;
networkMessage.protoMessage.body = request.rpcRequest; networkMessage.protoMessage.body = request.rpcRequest;
networkMessage.rawRequest = request.rawRequest; networkMessage.rawRequest = request.rawRequest;
networkMessage.requestId = request.token; networkMessage.requestId = request.token;
request.runningMessageId = messageId; request.runningMessageId = messageId;
request.runningMessageSeqNo = networkMessage.protoMessage.seqno; request.runningMessageSeqNo = networkMessage.protoMessage.seqno;
request.serializedLength = os.length(); request.serializedLength = requestLength;
request.runningStartTime = (int)(System.currentTimeMillis() / 1000); request.runningStartTime = (int)(System.currentTimeMillis() / 1000);
if (request.requiresCompletion) { if (request.requiresCompletion) {
runningRequests.add(request); runningRequests.add(request);
@ -1454,8 +1513,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
byte[] transportData = createConnectionData(currentMessages, sessionId, quickAckId, connection); byte[] transportData = createConnectionData(currentMessages, sessionId, quickAckId, connection);
if (transportData != null) { if (transportData != null) {
if (reportAck && quickAckId.size() != 0) if (reportAck && quickAckId.size() != 0) {
{
ArrayList<Long> requestIds = new ArrayList<Long>(); ArrayList<Long> requestIds = new ArrayList<Long>();
for (NetworkMessage message : messagesToSend) { for (NetworkMessage message : messagesToSend) {
@ -1933,13 +1991,15 @@ 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) {
Utilities.RunOnUIThread(new Runnable() { if (UserConfig.clientActivated) {
@Override UserConfig.clearConfig();
public void run() { Utilities.RunOnUIThread(new Runnable() {
NotificationCenter.Instance.postNotificationName(1234); @Override
UserConfig.clearConfig(); public void run() {
} NotificationCenter.Instance.postNotificationName(1234);
}); }
});
}
} }
} else { } else {
datacenter.authorized = false; datacenter.authorized = false;
@ -2078,7 +2138,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
TLObject result = Utilities.decompress(packet.packed_data, getRequestWithMessageId(messageId)); TLObject result = Utilities.decompress(packet.packed_data, getRequestWithMessageId(messageId));
processMessage(result, messageId, messageSeqNo, messageSalt, connection, sessionId, innerMsgId, containerMessageId); processMessage(result, messageId, messageSeqNo, messageSalt, connection, sessionId, innerMsgId, containerMessageId);
} else if (message instanceof TLRPC.Updates) { } else if (message instanceof TLRPC.Updates) {
MessagesController.Instance.processUpdates((TLRPC.Updates)message); MessagesController.Instance.processUpdates((TLRPC.Updates)message, false);
} else { } else {
FileLog.e("tmessages", "***** Error: unknown message class " + message); FileLog.e("tmessages", "***** Error: unknown message class " + message);
} }
@ -2275,6 +2335,20 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
} else { } else {
connectionState = 1; connectionState = 1;
} }
if (DEBUG_VERSION) {
try {
ConnectivityManager cm = (ConnectivityManager)ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] networkInfos = cm.getAllNetworkInfo();
for (NetworkInfo info : networkInfos) {
FileLog.e("tmessages", "Network: " + info.getTypeName() + " status: " + info.getState() + " info: " + info.getExtraInfo() + " object: " + info.getDetailedState() + " other: " + info);
}
if (networkInfos.length == 0) {
FileLog.e("tmessages", "no network available");
}
} catch (Exception e) {
FileLog.e("tmessages", "NETWORK STATE GET ERROR");
}
}
final int stateCopy = connectionState; final int stateCopy = connectionState;
Utilities.RunOnUIThread(new Runnable() { Utilities.RunOnUIThread(new Runnable() {
@Override @Override
@ -2477,7 +2551,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
public void run() { public void run() {
moveToDatacenter(datacenterId); moveToDatacenter(datacenterId);
} }
}, 1000); }, 1000, false);
} }
} }
}, null, true, RPCRequest.RPCRequestClassGeneric, currentDatacenterId); }, null, true, RPCRequest.RPCRequestClassGeneric, currentDatacenterId);

File diff suppressed because it is too large Load diff

View file

@ -42,10 +42,14 @@ public class DispatchQueue extends Thread {
} }
public void postRunnable(Runnable runnable) { public void postRunnable(Runnable runnable) {
postRunnable(runnable, 0); postRunnable(runnable, 0, false);
} }
public void postRunnable(Runnable runnable, int delay) { public void postRunnable(Runnable runnable, boolean inFront) {
postRunnable(runnable, 0, true);
}
public void postRunnable(Runnable runnable, int delay, boolean inFront) {
if (handler == null) { if (handler == null) {
try { try {
synchronized (handlerSyncObject) { synchronized (handlerSyncObject) {
@ -58,7 +62,11 @@ public class DispatchQueue extends Thread {
if (handler != null) { if (handler != null) {
if (delay <= 0) { if (delay <= 0) {
handler.post(runnable); if (inFront) {
handler.postAtFrontOfQueue(runnable);
} else {
handler.post(runnable);
}
} else { } else {
handler.postDelayed(runnable, delay); handler.postDelayed(runnable, delay);
} }

View file

@ -53,7 +53,7 @@ public class ExportAuthorizationAction extends Action {
public void run() { public void run() {
beginExport(); beginExport();
} }
}, retryCount * 1500); }, retryCount * 1500, false);
} }
} }
} }
@ -84,7 +84,7 @@ public class ExportAuthorizationAction extends Action {
public void run() { public void run() {
beginExport(); beginExport();
} }
}, retryCount * 1500); }, retryCount * 1500, false);
} }
} }
} }

View file

@ -420,7 +420,12 @@ public class FileLoadOperation {
if (renamed) { if (renamed) {
image = BitmapFactory.decodeStream(new FileInputStream(cacheFileFinal), null, opts); image = BitmapFactory.decodeStream(new FileInputStream(cacheFileFinal), null, opts);
} else { } else {
image = BitmapFactory.decodeStream(new FileInputStream(cacheFileTemp), null, opts); try {
image = BitmapFactory.decodeStream(new FileInputStream(cacheFileTemp), null, opts);
} catch (Exception e) {
FileLog.e("tmessages", e);
image = BitmapFactory.decodeStream(new FileInputStream(cacheFileFinal), null, opts);
}
} }
if (filter != null && image != null) { if (filter != null && image != null) {
float bitmapW = image.getWidth(); float bitmapW = image.getWidth();
@ -440,10 +445,11 @@ public class FileLoadOperation {
if (FileLoader.Instance.runtimeHack != null) { if (FileLoader.Instance.runtimeHack != null) {
FileLoader.Instance.runtimeHack.trackFree(image.getRowBytes() * image.getHeight()); FileLoader.Instance.runtimeHack.trackFree(image.getRowBytes() * image.getHeight());
} }
delegate.didFinishLoadingFile(FileLoadOperation.this);
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
delegate.didFailedLoadingFile(FileLoadOperation.this);
} }
delegate.didFinishLoadingFile(FileLoadOperation.this);
} }
}); });
} else { } else {

View file

@ -15,13 +15,12 @@ import android.graphics.BitmapFactory;
import android.graphics.Matrix; import android.graphics.Matrix;
import android.media.ExifInterface; import android.media.ExifInterface;
import android.os.Build; import android.os.Build;
import android.view.View;
import android.widget.ImageView;
import org.telegram.TL.TLRPC; import org.telegram.TL.TLRPC;
import org.telegram.objects.MessageObject; import org.telegram.objects.MessageObject;
import org.telegram.ui.ApplicationLoader; import org.telegram.ui.ApplicationLoader;
import org.telegram.ui.Views.BackupImageView; import org.telegram.ui.Views.BackupImageView;
import org.telegram.ui.Views.ImageReceiver;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
@ -134,29 +133,28 @@ public class FileLoader {
private class CacheImage { private class CacheImage {
public String key; public String key;
public ArrayList<View> imageViewArray; final public ArrayList<Object> imageViewArray = new ArrayList<Object>();
public FileLoadOperation loadOperation; public FileLoadOperation loadOperation;
public void addImageView(View imageView) { public void addImageView(Object imageView) {
if (imageViewArray == null) { synchronized (imageViewArray) {
imageViewArray = new ArrayList<View>(); boolean exist = false;
} for (Object v : imageViewArray) {
boolean exist = false; if (v == imageView) {
for (View v : imageViewArray) { exist = true;
if (v == imageView) { break;
exist = true; }
break; }
if (!exist) {
imageViewArray.add(imageView);
} }
}
if (!exist) {
imageViewArray.add(imageView);
} }
} }
public void removeImageView(View imageView) { public void removeImageView(Object imageView) {
if (imageViewArray != null) { synchronized (imageViewArray) {
for (int a = 0; a < imageViewArray.size(); a++) { for (int a = 0; a < imageViewArray.size(); a++) {
View obj = imageViewArray.get(a); Object obj = imageViewArray.get(a);
if (obj == null || obj == imageView) { if (obj == null || obj == imageView) {
imageViewArray.remove(a); imageViewArray.remove(a);
a--; a--;
@ -166,19 +164,23 @@ public class FileLoader {
} }
public void callAndClear(Bitmap image) { public void callAndClear(Bitmap image) {
if (image != null) { synchronized (imageViewArray) {
for (View imgView : imageViewArray) { if (image != null) {
if (imgView instanceof BackupImageView) { for (Object imgView : imageViewArray) {
((BackupImageView)imgView).setImageBitmap(image, key); if (imgView instanceof BackupImageView) {
} else if (imgView instanceof ImageView) { ((BackupImageView)imgView).setImageBitmap(image, key);
((ImageView)imgView).setImageBitmap(image); } else if (imgView instanceof ImageReceiver) {
((ImageReceiver)imgView).setImageBitmap(image, key);
}
} }
} }
} }
Utilities.imageLoadQueue.postRunnable(new Runnable() { Utilities.imageLoadQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
imageViewArray.clear(); synchronized (imageViewArray) {
imageViewArray.clear();
}
loadOperation = null; loadOperation = null;
} }
}); });
@ -189,7 +191,9 @@ public class FileLoader {
loadOperation.cancel(); loadOperation.cancel();
loadOperation = null; loadOperation = null;
} }
imageViewArray.clear(); synchronized (imageViewArray) {
imageViewArray.clear();
}
} }
} }
@ -548,25 +552,42 @@ public class FileLoader {
memCache.evictAll(); memCache.evictAll();
} }
public void cancelLoadingForImageView(final View imageView) { private Integer getTag(Object obj) {
if (obj instanceof BackupImageView) {
return (Integer)((BackupImageView)obj).getTag(R.string.CacheTag);
} else if (obj instanceof ImageReceiver) {
return ((ImageReceiver)obj).TAG;
}
return 0;
}
private void setTag(Object obj, Integer tag) {
if (obj instanceof BackupImageView) {
((BackupImageView)obj).setTag(R.string.CacheTag, tag);
} else if (obj instanceof ImageReceiver) {
((ImageReceiver)obj).TAG = tag;
}
}
public void cancelLoadingForImageView(final Object imageView) {
if (imageView == null) { if (imageView == null) {
return; return;
} }
Utilities.imageLoadQueue.postRunnable(new Runnable() { Utilities.imageLoadQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
Integer num = (Integer)imageView.getTag(R.string.CacheTag); Integer TAG = getTag(imageView);
if (num == null) { if (TAG == null) {
num = lastImageNum; TAG = lastImageNum;
imageView.setTag(R.string.CacheTag, num); setTag(imageView, TAG);
lastImageNum++; lastImageNum++;
if (lastImageNum == Integer.MAX_VALUE) { if (lastImageNum == Integer.MAX_VALUE) {
lastImageNum = 0; lastImageNum = 0;
} }
} }
CacheImage ei = imageLoadingByKeys.get(num); CacheImage ei = imageLoadingByKeys.get(TAG);
if (ei != null) { if (ei != null) {
imageLoadingByKeys.remove(num); imageLoadingByKeys.remove(TAG);
ei.removeImageView(imageView); ei.removeImageView(imageView);
if (ei.imageViewArray.size() == 0) { if (ei.imageViewArray.size() == 0) {
checkOperationsAndClear(ei.loadOperation); checkOperationsAndClear(ei.loadOperation);
@ -578,17 +599,18 @@ public class FileLoader {
}); });
} }
public Bitmap getImageFromMemory(TLRPC.FileLocation url, View imageView, String filter, boolean cancel) { public Bitmap getImageFromMemory(TLRPC.FileLocation url, Object imageView, String filter, boolean cancel) {
return getImageFromMemory(url, null, imageView, filter, cancel); return getImageFromMemory(url, null, imageView, filter, cancel);
} }
public Bitmap getImageFromMemory(String url, View imageView, String filter, boolean cancel) { public Bitmap getImageFromMemory(String url, Object imageView, String filter, boolean cancel) {
return getImageFromMemory(null, url, imageView, filter, cancel); return getImageFromMemory(null, url, imageView, filter, cancel);
} }
public Bitmap getImageFromMemory(TLRPC.FileLocation url, String httpUrl, View imageView, String filter, boolean cancel) { public Bitmap getImageFromMemory(TLRPC.FileLocation url, String httpUrl, Object imageView, String filter, boolean cancel) {
if ((url == null && httpUrl == null) || imageView == null) if (url == null && httpUrl == null) {
return null; return null;
}
String key; String key;
if (httpUrl != null) { if (httpUrl != null) {
key = Utilities.MD5(httpUrl); key = Utilities.MD5(httpUrl);
@ -600,7 +622,7 @@ public class FileLoader {
} }
Bitmap img = imageFromKey(key); Bitmap img = imageFromKey(key);
if (img != null && cancel) { if (imageView != null && img != null && cancel) {
cancelLoadingForImageView(imageView); cancelLoadingForImageView(imageView);
} }
return img; return img;
@ -637,19 +659,19 @@ public class FileLoader {
}); });
} }
public void loadImage(final String url, final View imageView, final String filter, final boolean cancel) { public void loadImage(final String url, final Object imageView, final String filter, final boolean cancel) {
loadImage(null, url, imageView, filter, cancel, 0); loadImage(null, url, imageView, filter, cancel, 0);
} }
public void loadImage(final TLRPC.FileLocation url, final View imageView, final String filter, final boolean cancel) { public void loadImage(final TLRPC.FileLocation url, final Object imageView, final String filter, final boolean cancel) {
loadImage(url, null, imageView, filter, cancel, 0); loadImage(url, null, imageView, filter, cancel, 0);
} }
public void loadImage(final TLRPC.FileLocation url, final View imageView, final String filter, final boolean cancel, final int size) { public void loadImage(final TLRPC.FileLocation url, final Object imageView, final String filter, final boolean cancel, final int size) {
loadImage(url, null, imageView, filter, cancel, size); loadImage(url, null, imageView, filter, cancel, size);
} }
public void loadImage(final TLRPC.FileLocation url, final String httpUrl, final View imageView, final String filter, final boolean cancel, final int size) { public void loadImage(final TLRPC.FileLocation url, final String httpUrl, final Object imageView, final String filter, final boolean cancel, final int size) {
if ((url == null && httpUrl == null) || imageView == null || (url != null && !(url instanceof TLRPC.TL_fileLocation) && !(url instanceof TLRPC.TL_fileEncryptedLocation))) { if ((url == null && httpUrl == null) || imageView == null || (url != null && !(url instanceof TLRPC.TL_fileLocation) && !(url instanceof TLRPC.TL_fileEncryptedLocation))) {
return; return;
} }
@ -666,10 +688,10 @@ public class FileLoader {
key += "@" + filter; key += "@" + filter;
} }
Integer num = (Integer)imageView.getTag(R.string.CacheTag); Integer TAG = getTag(imageView);
if (num == null) { if (TAG == null) {
num = lastImageNum; TAG = lastImageNum;
imageView.setTag(R.string.CacheTag, num); setTag(imageView, TAG);
lastImageNum++; lastImageNum++;
if (lastImageNum == Integer.MAX_VALUE) if (lastImageNum == Integer.MAX_VALUE)
lastImageNum = 0; lastImageNum = 0;
@ -679,7 +701,7 @@ public class FileLoader {
boolean addToByKeys = true; boolean addToByKeys = true;
CacheImage alreadyLoadingImage = imageLoading.get(key); CacheImage alreadyLoadingImage = imageLoading.get(key);
if (cancel) { if (cancel) {
CacheImage ei = imageLoadingByKeys.get(num); CacheImage ei = imageLoadingByKeys.get(TAG);
if (ei != null) { if (ei != null) {
if (ei != alreadyLoadingImage) { if (ei != alreadyLoadingImage) {
ei.removeImageView(imageView); ei.removeImageView(imageView);
@ -697,7 +719,7 @@ public class FileLoader {
if (alreadyLoadingImage != null && addToByKeys) { if (alreadyLoadingImage != null && addToByKeys) {
alreadyLoadingImage.addImageView(imageView); alreadyLoadingImage.addImageView(imageView);
imageLoadingByKeys.put(num, alreadyLoadingImage); imageLoadingByKeys.put(TAG, alreadyLoadingImage);
added = true; added = true;
} }
@ -705,7 +727,7 @@ public class FileLoader {
final CacheImage img = new CacheImage(); final CacheImage img = new CacheImage();
img.key = key; img.key = key;
img.addImageView(imageView); img.addImageView(imageView);
imageLoadingByKeys.put(num, img); imageLoadingByKeys.put(TAG, img);
imageLoading.put(key, img); imageLoading.put(key, img);
final String arg2 = key; final String arg2 = key;
@ -744,9 +766,8 @@ public class FileLoader {
Utilities.imageLoadQueue.postRunnable(new Runnable() { Utilities.imageLoadQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
for (View view : img.imageViewArray) { for (Object view : img.imageViewArray) {
Integer num = (Integer)view.getTag(R.string.CacheTag); imageLoadingByKeys.remove(getTag(view));
imageLoadingByKeys.remove(num);
imageLoading.remove(arg2); imageLoading.remove(arg2);
checkOperationsAndClear(operation); checkOperationsAndClear(operation);
} }
@ -814,15 +835,16 @@ public class FileLoader {
} }
} }
public void processImage(Bitmap image, View imageView, String filter, boolean cancel) { public void processImage(Bitmap image, Object imageView, String filter, boolean cancel) {
if (filter == null || imageView == null) { if (filter == null || imageView == null) {
return; return;
} }
Integer num = (Integer)imageView.getTag(R.string.CacheTag);
if (num == null) { Integer TAG = getTag(imageView);
num = lastImageNum; if (TAG == null) {
imageView.setTag(R.string.CacheTag, num); TAG = lastImageNum;
setTag(image, TAG);
lastImageNum++; lastImageNum++;
if (lastImageNum == Integer.MAX_VALUE) if (lastImageNum == Integer.MAX_VALUE)
lastImageNum = 0; lastImageNum = 0;
@ -832,7 +854,7 @@ public class FileLoader {
boolean addToByKeys = true; boolean addToByKeys = true;
CacheImage alreadyLoadingImage = imageLoading.get(filter); CacheImage alreadyLoadingImage = imageLoading.get(filter);
if (cancel) { if (cancel) {
CacheImage ei = imageLoadingByKeys.get(num); CacheImage ei = imageLoadingByKeys.get(TAG);
if (ei != null) { if (ei != null) {
if (ei != alreadyLoadingImage) { if (ei != alreadyLoadingImage) {
ei.removeImageView(imageView); ei.removeImageView(imageView);
@ -850,7 +872,7 @@ public class FileLoader {
if (alreadyLoadingImage != null && addToByKeys) { if (alreadyLoadingImage != null && addToByKeys) {
alreadyLoadingImage.addImageView(imageView); alreadyLoadingImage.addImageView(imageView);
imageLoadingByKeys.put(num, alreadyLoadingImage); imageLoadingByKeys.put(TAG, alreadyLoadingImage);
added = true; added = true;
} }
@ -858,7 +880,7 @@ public class FileLoader {
CacheImage img = new CacheImage(); CacheImage img = new CacheImage();
img.key = filter; img.key = filter;
img.addImageView(imageView); img.addImageView(imageView);
imageLoadingByKeys.put(num, img); imageLoadingByKeys.put(TAG, img);
imageLoading.put(filter, img); imageLoading.put(filter, img);
enqueueImageProcessingOperationWithImage(image, filter, filter, img); enqueueImageProcessingOperationWithImage(image, filter, filter, img);
@ -873,9 +895,8 @@ public class FileLoader {
Utilities.imageLoadQueue.postRunnable(new Runnable() { Utilities.imageLoadQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
for (View v : img.imageViewArray) { for (Object v : img.imageViewArray) {
Integer num = (Integer)v.getTag(R.string.CacheTag); imageLoadingByKeys.remove(getTag(v));
imageLoadingByKeys.remove(num);
} }
checkOperationsAndClear(img.loadOperation); checkOperationsAndClear(img.loadOperation);
imageLoading.remove(key); imageLoading.remove(key);

View file

@ -118,6 +118,8 @@ public class FileLog {
} }
} }
}); });
} else {
e.printStackTrace();
} }
} }

View file

@ -109,7 +109,16 @@ public class FileUploadOperation {
isBigFile = true; isBigFile = true;
} }
uploadChunkSize = (int)Math.max(32, Math.ceil(totalFileSize / (1024.0f * 3000))) * 1024; uploadChunkSize = (int)Math.max(32, Math.ceil(totalFileSize / (1024.0f * 3000)));
if (1024 % uploadChunkSize != 0) {
int chunkSize = 64;
while (uploadChunkSize > chunkSize) {
chunkSize *= 2;
}
uploadChunkSize = chunkSize;
}
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];
} }

View file

@ -14,6 +14,7 @@ import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.os.Bundle; import android.os.Bundle;
import android.os.PowerManager;
import com.google.android.gms.gcm.GoogleCloudMessaging; import com.google.android.gms.gcm.GoogleCloudMessaging;
@ -27,6 +28,10 @@ public class GcmBroadcastReceiver extends BroadcastReceiver {
setResultCode(Activity.RESULT_OK); setResultCode(Activity.RESULT_OK);
if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) { if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
final PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "lock");
wl.acquire();
SharedPreferences preferences = context.getSharedPreferences("Notifications", Context.MODE_PRIVATE); SharedPreferences preferences = context.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
boolean globalEnabled = preferences.getBoolean("EnableAll", true); boolean globalEnabled = preferences.getBoolean("EnableAll", true);
if (!globalEnabled) { if (!globalEnabled) {
@ -38,12 +43,13 @@ public class GcmBroadcastReceiver extends BroadcastReceiver {
public void run() { public void run() {
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
String messageType = gcm.getMessageType(intent); String messageType = gcm.getMessageType(intent);
sendNotification(context, intent.getExtras()); ConnectionsManager.Instance.resumeNetworkMaybe();
wl.release();
} }
}); });
thread.setPriority(Thread.MAX_PRIORITY); thread.setPriority(Thread.MAX_PRIORITY);
thread.start(); thread.start();
} else if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) { } else if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")) {
String registration = intent.getStringExtra("registration_id"); String registration = intent.getStringExtra("registration_id");
if (intent.getStringExtra("error") != null) { if (intent.getStringExtra("error") != null) {
FileLog.e("tmessages", "Registration failed, should try again later."); FileLog.e("tmessages", "Registration failed, should try again later.");
@ -54,157 +60,4 @@ public class GcmBroadcastReceiver extends BroadcastReceiver {
} }
} }
} }
private void sendNotification(Context context, Bundle extras) {
ConnectionsManager.Instance.resumeNetworkMaybe();
/*if (!UserConfig.clientActivated || context == null || extras == null) {
return;
}
SharedPreferences preferences = context.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
boolean groupEnabled = preferences.getBoolean("EnableGroup", true);
boolean globalVibrate = preferences.getBoolean("EnableVibrateAll", true);
boolean groupVibrate = preferences.getBoolean("EnableVibrateGroup", true);
if (ApplicationLoader.Instance != null && (ApplicationLoader.lastPauseTime == 0 || ApplicationLoader.lastPauseTime > System.currentTimeMillis() - 200)) {
return;
}
String defaultPath = null;
Uri defaultUri = Settings.System.DEFAULT_NOTIFICATION_URI;
if (defaultUri != null) {
defaultPath = defaultUri.getPath();
}
String globalSound = preferences.getString("GlobalSoundPath", defaultPath);
String chatSound = preferences.getString("GroupSoundPath", defaultPath);
String userSoundPath = null;
String chatSoundPath = null;
NotificationManager mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(context, LaunchActivity.class);
String msg = extras.getString("message");
try {
String to_id = extras.getString("user_id");
int to = Integer.parseInt(to_id);
if (to != UserConfig.clientUserId) {
return;
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
int chat_id = 0;
int user_id = 0;
String custom = extras.getString("custom");
try {
if (custom != null) {
JSONObject obj = new JSONObject(custom);
if (obj.has("chat_id")) {
Object object = obj.get("chat_id");
if (object instanceof Integer) {
chat_id = (Integer)object;
} else if (object instanceof String) {
chat_id = Integer.parseInt((String)object);
}
if (chat_id != 0) {
intent.putExtra("chatId", chat_id);
}
} else if (obj.has("from_id")) {
Object object = obj.get("from_id");
if (object instanceof Integer) {
user_id = (Integer)object;
} else if (object instanceof String) {
user_id = Integer.parseInt((String)object);
}
if (user_id != 0) {
intent.putExtra("userId", user_id);
}
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
if (user_id != 0) {
String key = "notify_" + user_id;
boolean value = preferences.getBoolean(key, true);
if (!value) {
return;
}
userSoundPath = preferences.getString("sound_path_" + user_id, null);
}
if (chat_id != 0) {
if (!groupEnabled) {
return;
}
String key = "notify_" + (-chat_id);
boolean value = preferences.getBoolean(key, true);
if (!value) {
return;
}
chatSoundPath = preferences.getString("sound_chat_path_" + chat_id, null);
}
boolean needVibrate;
String choosenSoundPath = null;
if (chat_id != 0) {
needVibrate = groupVibrate;
} else {
needVibrate = globalVibrate;
}
if (user_id != 0) {
if (userSoundPath != null) {
choosenSoundPath = userSoundPath;
} else if (globalSound != null) {
choosenSoundPath = globalSound;
}
} else if (chat_id != 0) {
if (chatSoundPath != null) {
choosenSoundPath = chatSoundPath;
} else if (chatSound != null) {
choosenSoundPath = chatSound;
}
} else {
choosenSoundPath = globalSound;
}
intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setContentTitle(ApplicationLoader.applicationContext.getString(R.string.AppName))
.setSmallIcon(R.drawable.notification)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg)
.setAutoCancel(true)
.setTicker(msg);
if (needVibrate) {
mBuilder.setVibrate(new long[]{0, 100, 0, 100});
}
if (choosenSoundPath != null && !choosenSoundPath.equals("NoSound")) {
if (choosenSoundPath.equals(defaultPath)) {
mBuilder.setSound(defaultUri);
} else {
mBuilder.setSound(Uri.parse(choosenSoundPath));
}
}
mBuilder.setContentIntent(contentIntent);
mNotificationManager.cancel(NOTIFICATION_ID);
Notification notification = mBuilder.build();
notification.ledARGB = 0xff00ff00;
notification.ledOnMS = 1000;
notification.ledOffMS = 1000;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
mNotificationManager.notify(NOTIFICATION_ID, notification);*/
}
} }

View file

@ -9,7 +9,6 @@
package org.telegram.messenger; package org.telegram.messenger;
import android.text.Html; import android.text.Html;
import android.util.Log;
import android.util.SparseArray; import android.util.SparseArray;
import org.telegram.SQLite.SQLiteCursor; import org.telegram.SQLite.SQLiteCursor;
@ -74,6 +73,11 @@ public class MessagesStorage {
database.executeFast("INSERT INTO params VALUES(1, 0, 0, 0, 0, 0, 0, NULL)").stepThis().dispose(); database.executeFast("INSERT INTO params VALUES(1, 0, 0, 0, 0, 0, 0, NULL)").stepThis().dispose();
database.executeFast("CREATE TABLE user_photos(uid INTEGER, id INTEGER, data BLOB, PRIMARY KEY (uid, id))").stepThis().dispose(); database.executeFast("CREATE TABLE user_photos(uid INTEGER, id INTEGER, data BLOB, PRIMARY KEY (uid, id))").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 INDEX IF NOT EXISTS sphone_deleted_idx_user_phones ON user_phones_v6(sphone, deleted);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS date_idx_dialogs ON dialogs(date);").stepThis().dispose(); database.executeFast("CREATE INDEX IF NOT EXISTS date_idx_dialogs ON dialogs(date);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS date_idx_enc_tasks ON enc_tasks(date);").stepThis().dispose(); database.executeFast("CREATE INDEX IF NOT EXISTS date_idx_enc_tasks ON enc_tasks(date);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS last_mid_idx_dialogs ON dialogs(last_mid);").stepThis().dispose(); database.executeFast("CREATE INDEX IF NOT EXISTS last_mid_idx_dialogs ON dialogs(last_mid);").stepThis().dispose();
@ -133,6 +137,10 @@ public class MessagesStorage {
database.executeFast("CREATE INDEX IF NOT EXISTS mid_out_idx_messages ON messages(mid, out);").stepThis().dispose(); database.executeFast("CREATE INDEX IF NOT EXISTS mid_out_idx_messages ON messages(mid, out);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS task_idx_messages ON messages(uid, out, read_state, ttl, date, send_state);").stepThis().dispose(); database.executeFast("CREATE INDEX IF NOT EXISTS task_idx_messages ON messages(uid, out, read_state, ttl, date, send_state);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS uid_date_mid_idx_messages ON messages(uid, date, mid);").stepThis().dispose(); database.executeFast("CREATE INDEX IF NOT EXISTS uid_date_mid_idx_messages ON messages(uid, date, mid);").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS user_contacts_v6(uid INTEGER PRIMARY KEY, fname TEXT, sname TEXT)").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS user_phones_v6(uid INTEGER, phone TEXT, sphone TEXT, deleted INTEGER, PRIMARY KEY (uid, phone))").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS sphone_deleted_idx_user_phones ON user_phones_v6(sphone, deleted);").stepThis().dispose();
} }
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
@ -291,37 +299,55 @@ public class MessagesStorage {
} }
public void getUserPhotos(final int uid, final int offset, final int count, final long max_id, final int classGuid) { public void getUserPhotos(final int uid, final int offset, final int count, final long max_id, final int classGuid) {
try { storageQueue.postRunnable(new Runnable() {
SQLiteCursor cursor; @Override
public void run() {
try {
SQLiteCursor cursor;
if (max_id != 0) { if (max_id != 0) {
cursor = database.queryFinalized(String.format(Locale.US, "SELECT data FROM user_photos WHERE uid = %d AND id < %d ORDER BY id DESC LIMIT %d", uid, max_id, count)); cursor = database.queryFinalized(String.format(Locale.US, "SELECT data FROM user_photos WHERE uid = %d AND id < %d ORDER BY id DESC LIMIT %d", uid, max_id, count));
} else { } else {
cursor = database.queryFinalized(String.format(Locale.US, "SELECT data FROM user_photos WHERE uid = %d ORDER BY id DESC LIMIT %d,%d", uid, offset, count)); cursor = database.queryFinalized(String.format(Locale.US, "SELECT data FROM user_photos WHERE uid = %d ORDER BY id DESC LIMIT %d,%d", uid, offset, count));
} }
final TLRPC.photos_Photos res = new TLRPC.photos_Photos(); final TLRPC.photos_Photos res = new TLRPC.photos_Photos();
while (cursor.next()) { while (cursor.next()) {
byte[] messageData = cursor.byteArrayValue(0); byte[] messageData = cursor.byteArrayValue(0);
if (messageData != null) { if (messageData != null) {
SerializedData data = new SerializedData(messageData); SerializedData data = new SerializedData(messageData);
TLRPC.Photo photo = (TLRPC.Photo)TLClassStore.Instance().TLdeserialize(data, data.readInt32()); TLRPC.Photo photo = (TLRPC.Photo)TLClassStore.Instance().TLdeserialize(data, data.readInt32());
res.photos.add(photo); res.photos.add(photo);
}
}
cursor.dispose();
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
MessagesController.Instance.processLoadedUserPhotos(res, uid, offset, count, max_id, true, classGuid);
}
});
} catch (Exception e) {
FileLog.e("tmessages", e);
} }
} }
cursor.dispose(); }, true);
}
Utilities.stageQueue.postRunnable(new Runnable() { public void clearUserPhotos(final int uid) {
@Override storageQueue.postRunnable(new Runnable() {
public void run() { @Override
MessagesController.Instance.processLoadedUserPhotos(res, uid, offset, count, max_id, true, classGuid); public void run() {
try {
database.executeFast("DELETE FROM user_photos WHERE uid = " + uid).stepThis().dispose();
} catch (Exception e) {
FileLog.e("tmessages", e);
} }
}); }
});
} catch (Exception e) {
FileLog.e("tmessages", e);
}
} }
public void putUserPhotos(final int uid, final TLRPC.photos_Photos photos) { public void putUserPhotos(final int uid, final TLRPC.photos_Photos photos) {
@ -394,10 +420,11 @@ public class MessagesStorage {
int minDate = Integer.MAX_VALUE; int minDate = Integer.MAX_VALUE;
SparseArray<ArrayList<Integer>> messages = new SparseArray<ArrayList<Integer>>(); SparseArray<ArrayList<Integer>> messages = new SparseArray<ArrayList<Integer>>();
String mids = ""; String mids = "";
SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid, ttl FROM messages WHERE uid = %d AND out = %d AND read_state = 1 AND ttl > 0 AND date <= %d AND send_state = 0", ((long)chat_id) << 32, isOut, time)); SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid, ttl, read_state FROM messages WHERE uid = %d AND out = %d AND ttl > 0 AND date <= %d AND send_state = 0", ((long)chat_id) << 32, isOut, time));
while (cursor.next()) { while (cursor.next()) {
int mid = cursor.intValue(0); int mid = cursor.intValue(0);
int ttl = cursor.intValue(1); int ttl = cursor.intValue(1);
int read_state = cursor.intValue(2);
int date = readTime + ttl; int date = readTime + ttl;
minDate = Math.min(minDate, date); minDate = Math.min(minDate, date);
ArrayList<Integer> arr = messages.get(date); ArrayList<Integer> arr = messages.get(date);
@ -690,6 +717,63 @@ public class MessagesStorage {
}); });
} }
public void updateChatInfo(final int chat_id, final int user_id, final boolean deleted, final int invited_id, final int version) {
storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
try {
SQLiteCursor cursor = database.queryFinalized("SELECT participants FROM chat_settings WHERE uid = " + chat_id);
TLRPC.ChatParticipants info = null;
ArrayList<TLRPC.User> loadedUsers = new ArrayList<TLRPC.User>();
if (cursor.next()) {
byte[] userData = cursor.byteArrayValue(0);
if (userData != null) {
SerializedData data = new SerializedData(userData);
info = (TLRPC.ChatParticipants)TLClassStore.Instance().TLdeserialize(data, data.readInt32());
}
}
cursor.dispose();
if (info != null) {
if (deleted) {
for (int a = 0; a < info.participants.size(); a++) {
TLRPC.TL_chatParticipant participant = info.participants.get(a);
if (participant.user_id == user_id) {
info.participants.remove(a);
break;
}
}
} else {
TLRPC.TL_chatParticipant participant = new TLRPC.TL_chatParticipant();
participant.user_id = user_id;
participant.inviter_id = invited_id;
participant.date = ConnectionsManager.Instance.getCurrentTime();
info.participants.add(participant);
}
info.version = version;
final TLRPC.ChatParticipants finalInfo = info;
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
NotificationCenter.Instance.postNotificationName(MessagesController.chatInfoDidLoaded, finalInfo.chat_id, finalInfo);
}
});
SQLitePreparedStatement state = database.executeFast("REPLACE INTO chat_settings VALUES(?, ?)");
SerializedData data = new SerializedData();
info.serializeToStream(data);
state.bindInteger(1, chat_id);
state.bindByteArray(2, data.toByteArray());
state.step();
state.dispose();
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
}
public void loadChatInfo(final int chat_id) { public void loadChatInfo(final int chat_id) {
storageQueue.postRunnable(new Runnable() { storageQueue.postRunnable(new Runnable() {
@Override @Override
@ -883,7 +967,7 @@ public class MessagesStorage {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
} }
} }
}); }, true);
} }
public void putContacts(final ArrayList<TLRPC.TL_contact> contacts, final boolean deleteAll) { public void putContacts(final ArrayList<TLRPC.TL_contact> contacts, final boolean deleteAll) {
@ -914,6 +998,118 @@ public class MessagesStorage {
}); });
} }
public void deleteContacts(final ArrayList<Integer> uids) {
if (uids == null || uids.isEmpty()) {
return;
}
storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
try {
String ids = "";
for (Integer uid : uids) {
if (ids.length() != 0) {
ids += ",";
}
ids += "" + uid;
}
database.executeFast("DELETE FROM contacts WHERE uid IN (" + ids + ")").stepThis().dispose();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
}
public void applyPhoneBookUpdates(final String adds, final String deletes) {
if (adds.length() == 0 && deletes.length() == 0) {
return;
}
storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
try {
if (adds.length() != 0) {
database.executeFast(String.format(Locale.US, "UPDATE user_phones_v6 SET deleted = 0 WHERE sphone IN (%s)", adds)).stepThis().dispose();
}
if (deletes.length() != 0) {
database.executeFast(String.format(Locale.US, "UPDATE user_phones_v6 SET deleted = 1 WHERE sphone IN (%s)", deletes)).stepThis().dispose();
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
}
public void putCachedPhoneBook(final HashMap<Integer, ContactsController.Contact> contactHashMap) {
storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
try {
database.executeFast("DELETE FROM user_contacts_v6 WHERE 1").stepThis().dispose();
database.executeFast("DELETE FROM user_phones_v6 WHERE 1").stepThis().dispose();
database.beginTransaction();
SQLitePreparedStatement state = database.executeFast("REPLACE INTO user_contacts_v6 VALUES(?, ?, ?)");
SQLitePreparedStatement state2 = database.executeFast("REPLACE INTO user_phones_v6 VALUES(?, ?, ?, ?)");
for (HashMap.Entry<Integer, ContactsController.Contact> entry : contactHashMap.entrySet()) {
ContactsController.Contact contact = entry.getValue();
state.requery();
state.bindInteger(1, contact.id);
state.bindString(2, contact.first_name);
state.bindString(3, contact.last_name);
state.step();
for (int a = 0; a < contact.phones.size(); a++) {
state2.requery();
state2.bindInteger(1, contact.id);
state2.bindString(2, contact.phones.get(a));
state2.bindString(3, contact.shortPhones.get(a));
state2.bindInteger(4, contact.phoneDeleted.get(a));
state2.step();
}
}
state.dispose();
state2.dispose();
database.commitTransaction();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
}
public void getCachedPhoneBook() {
storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
HashMap<Integer, ContactsController.Contact> contactHashMap = new HashMap<Integer, ContactsController.Contact>();
try {
SQLiteCursor cursor = database.queryFinalized("SELECT us.uid, us.fname, us.sname, up.phone, up.sphone, up.deleted FROM user_contacts_v6 as us LEFT JOIN user_phones_v6 as up ON us.uid = up.uid WHERE 1");
while (cursor.next()) {
int uid = cursor.intValue(0);
ContactsController.Contact contact = contactHashMap.get(uid);
if (contact == null) {
contact = new ContactsController.Contact();
contact.first_name = cursor.stringValue(1);
contact.last_name = cursor.stringValue(2);
contact.id = uid;
contactHashMap.put(uid, contact);
}
contact.phones.add(cursor.stringValue(3));
contact.shortPhones.add(cursor.stringValue(4));
contact.phoneDeleted.add(cursor.intValue(5));
contact.phoneTypes.add("");
}
cursor.dispose();
} catch (Exception e) {
FileLog.e("tmessages", e);
} finally {
ContactsController.Instance.performSyncPhoneBook(contactHashMap, true, true);
}
}
}, true);
}
public void getContacts() { public void getContacts() {
storageQueue.postRunnable(new Runnable() { storageQueue.postRunnable(new Runnable() {
@Override @Override
@ -954,12 +1150,12 @@ public class MessagesStorage {
} }
cursor.dispose(); cursor.dispose();
} }
MessagesController.Instance.processLoadedContacts(contacts, users, 1); ContactsController.Instance.processLoadedContacts(contacts, users, 1);
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
} }
} }
}); }, true);
} }
public void putMediaCount(final long uid, final int count) { public void putMediaCount(final long uid, final int count) {
@ -1007,7 +1203,7 @@ public class MessagesStorage {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
} }
} }
}); }, true);
} }
public void loadMedia(final long uid, final int offset, final int count, final int max_id, final int classGuid) { public void loadMedia(final long uid, final int offset, final int count, final int max_id, final int classGuid) {
@ -1083,7 +1279,7 @@ public class MessagesStorage {
MessagesController.Instance.processLoadedMedia(res, uid, offset, count, max_id, true, classGuid); MessagesController.Instance.processLoadedMedia(res, uid, offset, count, max_id, true, classGuid);
} }
} }
}); }, true);
} }
public void putMedia(final long uid, final ArrayList<TLRPC.Message> messages) { public void putMedia(final long uid, final ArrayList<TLRPC.Message> messages) {
@ -1103,8 +1299,6 @@ public class MessagesStorage {
state2.bindInteger(3, message.date); state2.bindInteger(3, message.date);
state2.bindByteArray(4, data.toByteArray()); state2.bindByteArray(4, data.toByteArray());
state2.step(); state2.step();
} else {
Log.e("tmessages", "test");
} }
} }
state2.dispose(); state2.dispose();
@ -1136,7 +1330,7 @@ public class MessagesStorage {
if (lower_id != 0) { if (lower_id != 0) {
if (forward) { if (forward) {
cursor = database.queryFinalized(String.format(Locale.US, "SELECT read_state, data, send_state, mid, date FROM messages WHERE uid = %d AND mid > %d ORDER BY date ASC, mid ASC LIMIT %d", dialog_id, max_id, count_query)); cursor = database.queryFinalized(String.format(Locale.US, "SELECT read_state, data, send_state, mid, date FROM messages WHERE uid = %d AND date >= %d AND mid > %d ORDER BY date ASC, mid ASC LIMIT %d", dialog_id, minDate, max_id, count_query));
} else if (minDate != 0) { } else if (minDate != 0) {
if (max_id != 0) { if (max_id != 0) {
cursor = database.queryFinalized(String.format(Locale.US, "SELECT read_state, data, send_state, mid, date FROM messages WHERE uid = %d AND date < %d AND mid < %d ORDER BY date DESC, mid DESC LIMIT %d", dialog_id, minDate, max_id, count_query)); cursor = database.queryFinalized(String.format(Locale.US, "SELECT read_state, data, send_state, mid, date FROM messages WHERE uid = %d AND date < %d AND mid < %d ORDER BY date DESC, mid DESC LIMIT %d", dialog_id, minDate, max_id, count_query));
@ -1275,7 +1469,7 @@ public class MessagesStorage {
MessagesController.Instance.processLoadedMessages(res, dialog_id, offset, count_query, max_id, true, classGuid, min_unread_id, max_unread_id, count_unread, max_unread_date, forward); MessagesController.Instance.processLoadedMessages(res, dialog_id, offset, count_query, max_id, true, classGuid, min_unread_id, max_unread_id, count_unread, max_unread_date, forward);
} }
} }
}); }, true);
} }
public void startTransaction(boolean useQueue) { public void startTransaction(boolean useQueue) {
@ -1559,9 +1753,87 @@ public class MessagesStorage {
HashMap<Long, TLRPC.Message> messagesMap = new HashMap<Long, TLRPC.Message>(); HashMap<Long, TLRPC.Message> messagesMap = new HashMap<Long, TLRPC.Message>();
HashMap<Long, Integer> messagesCounts = new HashMap<Long, Integer>(); HashMap<Long, Integer> messagesCounts = new HashMap<Long, Integer>();
HashMap<Long, Integer> mediaCounts = new HashMap<Long, Integer>(); HashMap<Long, Integer> mediaCounts = new HashMap<Long, Integer>();
HashMap<Integer, Long> messagesIdsMap = new HashMap<Integer, Long>();
HashMap<Integer, Long> messagesMediaIdsMap = new HashMap<Integer, Long>();
String messageIds = "";
String messageMediaIds = "";
SQLitePreparedStatement state = database.executeFast("REPLACE INTO messages VALUES(?, ?, ?, ?, ?, ?, ?, ?)"); SQLitePreparedStatement state = database.executeFast("REPLACE INTO messages VALUES(?, ?, ?, ?, ?, ?, ?, ?)");
SQLitePreparedStatement state2 = database.executeFast("REPLACE INTO media VALUES(?, ?, ?, ?)"); SQLitePreparedStatement state2 = database.executeFast("REPLACE INTO media VALUES(?, ?, ?, ?)");
SQLitePreparedStatement state3 = database.executeFast("REPLACE INTO randoms VALUES(?, ?)"); SQLitePreparedStatement state3 = database.executeFast("REPLACE INTO randoms VALUES(?, ?)");
for (TLRPC.Message message : messages) {
long dialog_id = 0;
if (message.unread && !message.out) {
if (messageIds.length() > 0) {
messageIds += ",";
}
messageIds += message.id;
dialog_id = message.dialog_id;
if (dialog_id == 0) {
if (message.to_id.chat_id != 0) {
dialog_id = -message.to_id.chat_id;
} else if (message.to_id.user_id != 0) {
dialog_id = message.to_id.user_id;
}
}
messagesIdsMap.put(message.id, dialog_id);
}
if (message.media instanceof TLRPC.TL_messageMediaVideo || message.media instanceof TLRPC.TL_messageMediaPhoto) {
if (dialog_id == 0) {
dialog_id = message.dialog_id;
if (dialog_id == 0) {
if (message.to_id.chat_id != 0) {
dialog_id = -message.to_id.chat_id;
} else if (message.to_id.user_id != 0) {
dialog_id = message.to_id.user_id;
}
}
}
if (messageMediaIds.length() > 0) {
messageMediaIds += ",";
}
messageMediaIds += message.id;
messagesMediaIdsMap.put(message.id, dialog_id);
}
}
if (messageIds.length() > 0) {
SQLiteCursor cursor = database.queryFinalized("SELECT mid FROM messages WHERE mid IN(" + messageIds + ")");
while (cursor.next()) {
int mid = cursor.intValue(0);
messagesIdsMap.remove(mid);
}
cursor.dispose();
for (Long dialog_id : messagesIdsMap.values()) {
Integer count = messagesCounts.get(dialog_id);
if (count == null) {
count = 0;
}
count++;
messagesCounts.put(dialog_id, count);
}
}
if (messageMediaIds.length() > 0) {
SQLiteCursor cursor = database.queryFinalized("SELECT mid FROM media WHERE mid IN(" + messageMediaIds + ")");
while (cursor.next()) {
int mid = cursor.intValue(0);
messagesMediaIdsMap.remove(mid);
}
cursor.dispose();
for (Long dialog_id : messagesMediaIdsMap.values()) {
Integer count = mediaCounts.get(dialog_id);
if (count == null) {
count = 0;
}
count++;
mediaCounts.put(dialog_id, count);
}
}
for (TLRPC.Message message : messages) { for (TLRPC.Message message : messages) {
long dialog_id = message.dialog_id; long dialog_id = message.dialog_id;
if (dialog_id == 0) { if (dialog_id == 0) {
@ -1584,14 +1856,6 @@ public class MessagesStorage {
if (lastMessage == null || message.date > lastMessage.date) { if (lastMessage == null || message.date > lastMessage.date) {
messagesMap.put(dialog_id, message); messagesMap.put(dialog_id, message);
} }
if (message.unread && !message.out) {
Integer count = messagesCounts.get(dialog_id);
if (count == null) {
count = 0;
}
count++;
messagesCounts.put(dialog_id, count);
}
state.bindInteger(1, messageId); state.bindInteger(1, messageId);
state.bindLong(2, dialog_id); state.bindLong(2, dialog_id);
state.bindInteger(3, (message.unread ? 0 : 1)); state.bindInteger(3, (message.unread ? 0 : 1));
@ -1611,28 +1875,12 @@ public class MessagesStorage {
} }
if (message.media instanceof TLRPC.TL_messageMediaVideo || message.media instanceof TLRPC.TL_messageMediaPhoto) { if (message.media instanceof TLRPC.TL_messageMediaVideo || message.media instanceof TLRPC.TL_messageMediaPhoto) {
boolean exist = false;
SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid FROM media WHERE mid = %d LIMIT 1", message.id));
if (cursor.next()) {
exist = true;
}
cursor.dispose();
state2.requery(); state2.requery();
state2.bindInteger(1, messageId); state2.bindInteger(1, messageId);
state2.bindLong(2, dialog_id); state2.bindLong(2, dialog_id);
state2.bindInteger(3, message.date); state2.bindInteger(3, message.date);
state2.bindByteArray(4, bytes); state2.bindByteArray(4, bytes);
state2.step(); state2.step();
if (!exist) {
Integer count = mediaCounts.get(dialog_id);
if (count == null) {
count = 0;
}
count++;
mediaCounts.put(dialog_id, count);
}
} }
} }
state.dispose(); state.dispose();
@ -1662,6 +1910,7 @@ public class MessagesStorage {
if (withTransaction) { if (withTransaction) {
database.commitTransaction(); database.commitTransaction();
} }
MessagesController.Instance.dialogsUnreadCountIncr(messagesCounts);
if (!mediaCounts.isEmpty()) { if (!mediaCounts.isEmpty()) {
state = database.executeFast("REPLACE INTO media_counts VALUES(?, ?)"); state = database.executeFast("REPLACE INTO media_counts VALUES(?, ?)");
@ -2442,7 +2691,7 @@ public class MessagesStorage {
MessagesController.Instance.processLoadedDialogs(dialogs, encryptedChats, 0, 0, 100, true, true); MessagesController.Instance.processLoadedDialogs(dialogs, encryptedChats, 0, 0, 100, true, true);
} }
} }
}); }, true);
} }
public void putDialogs(final TLRPC.messages_Dialogs dialogs) { public void putDialogs(final TLRPC.messages_Dialogs dialogs) {

View file

@ -12,42 +12,41 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
public class NotificationCenter { public class NotificationCenter {
public static NotificationCenter Instance = new NotificationCenter();
final private HashMap<Integer, ArrayList<Object>> observers = new HashMap<Integer, ArrayList<Object>>(); final private HashMap<Integer, ArrayList<Object>> observers = new HashMap<Integer, ArrayList<Object>>();
final private HashMap<Integer, Object> memCache = new HashMap<Integer, Object>();
final private HashMap<String, Object> memCacheString = new HashMap<String, Object>(); final private HashMap<String, Object> memCache = new HashMap<String, Object>();
private boolean broadcasting = false;
final private HashMap<Integer, Object> removeAfterBroadcast = new HashMap<Integer, Object>(); final private HashMap<Integer, Object> removeAfterBroadcast = new HashMap<Integer, Object>();
final private HashMap<Integer, Object> addAfterBroadcast = new HashMap<Integer, Object>();
private boolean broadcasting = false;
public interface NotificationCenterDelegate { public interface NotificationCenterDelegate {
public abstract void didReceivedNotification(int id, Object... args); public abstract void didReceivedNotification(int id, Object... args);
} }
public static NotificationCenter Instance = new NotificationCenter();
public void addToMemCache(int id, Object object) { public void addToMemCache(int id, Object object) {
memCache.put(id, object); addToMemCache(String.valueOf(id), object);
} }
public void addToMemCache(String id, Object object) { public void addToMemCache(String id, Object object) {
memCacheString.put(id, object); memCache.put(id, object);
} }
public Object getFromMemCache(int id) { public Object getFromMemCache(int id) {
Object obj = memCache.get(id); return getFromMemCache(String.valueOf(id), null);
if (obj != null) {
memCache.remove(id);
}
return obj;
} }
public Object getFromMemCache(String id, Object defaultValue) { public Object getFromMemCache(String id, Object defaultValue) {
Object obj = memCacheString.get(id); Object obj = memCache.get(id);
if (obj != null) { if (obj != null) {
memCacheString.remove(id); memCache.remove(id);
} else { return obj;
return defaultValue;
} }
return obj; return defaultValue;
} }
public void postNotificationName(int id, Object... args) { public void postNotificationName(int id, Object... args) {
@ -66,15 +65,24 @@ public class NotificationCenter {
} }
removeAfterBroadcast.clear(); removeAfterBroadcast.clear();
} }
if (!addAfterBroadcast.isEmpty()) {
for (HashMap.Entry<Integer, Object> entry : addAfterBroadcast.entrySet()) {
addObserver(entry.getValue(), entry.getKey());
}
addAfterBroadcast.clear();
}
} }
} }
public void addObserver(Object observer, int id) { public void addObserver(Object observer, int id) {
synchronized (observers) { synchronized (observers) {
if (broadcasting) {
addAfterBroadcast.put(id, observer);
return;
}
ArrayList<Object> objects = observers.get(id); ArrayList<Object> objects = observers.get(id);
if (objects == null) { if (objects == null) {
objects = new ArrayList<Object>(); observers.put(id, (objects = new ArrayList<Object>()));
observers.put(id, objects);
} }
if (objects.contains(observer)) { if (objects.contains(observer)) {
return; return;
@ -83,25 +91,6 @@ public class NotificationCenter {
} }
} }
// public void removeObserver(Object observer) {
// synchronized (observers) {
// if (broadcasting) {
// removeAfterBroadcast.put(-1, observer);
// return;
// }
// Integer[] keyArr = (Integer[])observers.keySet().toArray();
// for (int a = 0; a < observers.size(); a++) {
// Integer id = keyArr[a];
// ArrayList<Object> objects = observers.get(id);
// objects.remove(observer);
// if (objects.size() == 0) {
// observers.remove(id);
// a--;
// }
// }
// }
// }
public void removeObserver(Object observer, int id) { public void removeObserver(Object observer, int id) {
synchronized (observers) { synchronized (observers) {
if (broadcasting) { if (broadcasting) {

View file

@ -29,6 +29,7 @@ public class RPCRequest {
public static int RPCRequestClassUploadMedia = 4; public static int RPCRequestClassUploadMedia = 4;
public static int RPCRequestClassEnableUnauthorized = 8; public static int RPCRequestClassEnableUnauthorized = 8;
public static int RPCRequestClassFailOnServerErrors = 16; public static int RPCRequestClassFailOnServerErrors = 16;
public static int RPCRequestClassCanCompress = 32;
static int RPCRequestClassTransportMask = (RPCRequestClassGeneric | RPCRequestClassDownloadMedia | RPCRequestClassUploadMedia); static int RPCRequestClassTransportMask = (RPCRequestClassGeneric | RPCRequestClassDownloadMedia | RPCRequestClassUploadMedia);
@ -37,6 +38,7 @@ public class RPCRequest {
int serverFailureCount; int serverFailureCount;
int flags; int flags;
public int retryCount = 0;
TLObject rawRequest; TLObject rawRequest;
TLObject rpcRequest; TLObject rpcRequest;

View file

@ -15,8 +15,6 @@ import android.content.SharedPreferences;
import android.os.Bundle; import android.os.Bundle;
import android.telephony.SmsMessage; import android.telephony.SmsMessage;
import org.telegram.messenger.NotificationCenter;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -27,6 +25,9 @@ public class SmsListener extends BroadcastReceiver {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) { if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
if (!Utilities.isWaitingForSms()) {
return;
}
Bundle bundle = intent.getExtras(); Bundle bundle = intent.getExtras();
SmsMessage[] msgs; SmsMessage[] msgs;
if (bundle != null) { if (bundle != null) {

View file

@ -50,6 +50,7 @@ public class TcpConnection extends PyroClientAdapter {
private boolean hasSomeDataSinceLastConnect = false; private boolean hasSomeDataSinceLastConnect = false;
private int willRetryConnectCount = 5; private int willRetryConnectCount = 5;
private boolean isNextPort = false; private boolean isNextPort = false;
private final Integer timerSync = 1;
public int transportRequestClass; public int transportRequestClass;
@ -86,9 +87,11 @@ public class TcpConnection extends PyroClientAdapter {
connectionState = TcpConnectionState.TcpConnectionStageConnecting; connectionState = TcpConnectionState.TcpConnectionStageConnecting;
try { try {
try { try {
if (reconnectTimer != null) { synchronized (timerSync) {
reconnectTimer.cancel(); if (reconnectTimer != null) {
reconnectTimer = null; reconnectTimer.cancel();
reconnectTimer = null;
}
} }
} catch (Exception e2) { } catch (Exception e2) {
FileLog.e("tmessages", e2); FileLog.e("tmessages", e2);
@ -115,19 +118,22 @@ public class TcpConnection extends PyroClientAdapter {
selector.wakeup(); selector.wakeup();
} catch (Exception e) { } catch (Exception e) {
try { try {
if (reconnectTimer != null) { synchronized (timerSync) {
reconnectTimer.cancel(); if (reconnectTimer != null) {
reconnectTimer = null; reconnectTimer.cancel();
reconnectTimer = null;
}
} }
} catch (Exception e2) { } catch (Exception e2) {
FileLog.e("tmessages", e2); FileLog.e("tmessages", e2);
} }
connectionState = TcpConnectionState.TcpConnectionStageReconnecting; connectionState = TcpConnectionState.TcpConnectionStageReconnecting;
if (delegate != null) { if (delegate != null) {
final TcpConnectionDelegate finalDelegate = delegate;
Utilities.stageQueue.postRunnable(new Runnable() { Utilities.stageQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
delegate.tcpConnectionClosed(TcpConnection.this); finalDelegate.tcpConnectionClosed(TcpConnection.this);
} }
}); });
} }
@ -160,9 +166,11 @@ public class TcpConnection extends PyroClientAdapter {
@Override @Override
public void run() { public void run() {
try { try {
if (reconnectTimer != null) { synchronized (timerSync) {
reconnectTimer.cancel(); if (reconnectTimer != null) {
reconnectTimer = null; reconnectTimer.cancel();
reconnectTimer = null;
}
} }
} catch (Exception e2) { } catch (Exception e2) {
FileLog.e("tmessages", e2); FileLog.e("tmessages", e2);
@ -181,9 +189,11 @@ public class TcpConnection extends PyroClientAdapter {
} }
private void suspendConnectionInternal() { private void suspendConnectionInternal() {
if (reconnectTimer != null) { synchronized (timerSync) {
reconnectTimer.cancel(); if (reconnectTimer != null) {
reconnectTimer = null; reconnectTimer.cancel();
reconnectTimer = null;
}
} }
if (connectionState == TcpConnectionState.TcpConnectionStageIdle || connectionState == TcpConnectionState.TcpConnectionStageSuspended) { if (connectionState == TcpConnectionState.TcpConnectionStageIdle || connectionState == TcpConnectionState.TcpConnectionStageSuspended) {
return; return;
@ -196,10 +206,11 @@ public class TcpConnection extends PyroClientAdapter {
client = null; client = null;
} }
if (delegate != null) { if (delegate != null) {
final TcpConnectionDelegate finalDelegate = delegate;
Utilities.stageQueue.postRunnable(new Runnable() { Utilities.stageQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
delegate.tcpConnectionClosed(TcpConnection.this); finalDelegate.tcpConnectionClosed(TcpConnection.this);
} }
}); });
} }
@ -314,10 +325,11 @@ public class TcpConnection extends PyroClientAdapter {
buffer.order(ByteOrder.BIG_ENDIAN); buffer.order(ByteOrder.BIG_ENDIAN);
final int ackId = buffer.getInt() & (~(1 << 31)); final int ackId = buffer.getInt() & (~(1 << 31));
if (delegate != null) { if (delegate != null) {
final TcpConnectionDelegate finalDelegate = delegate;
Utilities.stageQueue.postRunnable(new Runnable() { Utilities.stageQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
delegate.tcpConnectionQuiackAckReceived(TcpConnection.this, ackId); finalDelegate.tcpConnectionQuiackAckReceived(TcpConnection.this, ackId);
} }
}); });
} }
@ -360,12 +372,13 @@ public class TcpConnection extends PyroClientAdapter {
} }
if (lastMessageId != -1 && lastMessageId != 0) { if (lastMessageId != -1 && lastMessageId != 0) {
if (delegate != null) { if (delegate != null) {
final TcpConnectionDelegate finalDelegate = delegate;
final int arg2 = buffer.remaining(); final int arg2 = buffer.remaining();
final int arg3 = currentPacketLength; final int arg3 = currentPacketLength;
Utilities.stageQueue.postRunnable(new Runnable() { Utilities.stageQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
delegate.tcpConnectionProgressChanged(TcpConnection.this, lastMessageId, arg2, arg3); finalDelegate.tcpConnectionProgressChanged(TcpConnection.this, lastMessageId, arg2, arg3);
} }
}); });
} }
@ -383,10 +396,11 @@ public class TcpConnection extends PyroClientAdapter {
buffer.get(packetData); buffer.get(packetData);
if (delegate != null) { if (delegate != null) {
final TcpConnectionDelegate finalDelegate = delegate;
Utilities.stageQueue.postRunnable(new Runnable() { Utilities.stageQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
delegate.tcpConnectionReceivedData(TcpConnection.this, packetData); finalDelegate.tcpConnectionReceivedData(TcpConnection.this, packetData);
} }
}); });
} }
@ -394,9 +408,11 @@ public class TcpConnection extends PyroClientAdapter {
} }
public void handleDisconnect(PyroClient client, Exception e) { public void handleDisconnect(PyroClient client, Exception e) {
if (reconnectTimer != null) { synchronized (timerSync) {
reconnectTimer.cancel(); if (reconnectTimer != null) {
reconnectTimer = null; reconnectTimer.cancel();
reconnectTimer = null;
}
} }
if (e != null) { if (e != null) {
FileLog.d("tmessages", "Disconnected " + TcpConnection.this + " with error " + e); FileLog.d("tmessages", "Disconnected " + TcpConnection.this + " with error " + e);
@ -410,12 +426,11 @@ public class TcpConnection extends PyroClientAdapter {
connectionState = TcpConnectionState.TcpConnectionStageIdle; connectionState = TcpConnectionState.TcpConnectionStageIdle;
} }
if (delegate != null) { if (delegate != null) {
final TcpConnectionDelegate finalDelegate = delegate;
Utilities.stageQueue.postRunnable(new Runnable() { Utilities.stageQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
if (delegate != null) { finalDelegate.tcpConnectionClosed(TcpConnection.this);
delegate.tcpConnectionClosed(TcpConnection.this);
}
} }
}); });
} }
@ -447,9 +462,11 @@ public class TcpConnection extends PyroClientAdapter {
@Override @Override
public void run() { public void run() {
try { try {
if (reconnectTimer != null) { synchronized (timerSync) {
reconnectTimer.cancel(); if (reconnectTimer != null) {
reconnectTimer = null; reconnectTimer.cancel();
reconnectTimer = null;
}
} }
} catch (Exception e2) { } catch (Exception e2) {
FileLog.e("tmessages", e2); FileLog.e("tmessages", e2);
@ -471,10 +488,11 @@ public class TcpConnection extends PyroClientAdapter {
channelToken = generateChannelToken(); channelToken = generateChannelToken();
FileLog.d("tmessages", String.format(TcpConnection.this + " Connected (%s:%d)", hostAddress, hostPort)); FileLog.d("tmessages", String.format(TcpConnection.this + " Connected (%s:%d)", hostAddress, hostPort));
if (delegate != null) { if (delegate != null) {
final TcpConnectionDelegate finalDelegate = delegate;
Utilities.stageQueue.postRunnable(new Runnable() { Utilities.stageQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
delegate.tcpConnectionConnected(TcpConnection.this); finalDelegate.tcpConnectionConnected(TcpConnection.this);
} }
}); });
} }

View file

@ -27,7 +27,6 @@ public class UserConfig {
public static int lastSendMessageId = -210000; public static int lastSendMessageId = -210000;
public static int lastLocalId = -210000; public static int lastLocalId = -210000;
public static String contactsHash = ""; public static String contactsHash = "";
public static String importHash = "";
private final static Integer sync = 1; private final static Integer sync = 1;
public static boolean saveIncomingPhotos = false; public static boolean saveIncomingPhotos = false;
@ -55,7 +54,6 @@ public class UserConfig {
editor.putInt("lastSendMessageId", lastSendMessageId); editor.putInt("lastSendMessageId", lastSendMessageId);
editor.putInt("lastLocalId", lastLocalId); editor.putInt("lastLocalId", lastLocalId);
editor.putString("contactsHash", contactsHash); editor.putString("contactsHash", contactsHash);
editor.putString("importHash", importHash);
editor.putBoolean("saveIncomingPhotos", saveIncomingPhotos); editor.putBoolean("saveIncomingPhotos", saveIncomingPhotos);
if (withFile) { if (withFile) {
SerializedData data = new SerializedData(); SerializedData data = new SerializedData();
@ -71,7 +69,6 @@ public class UserConfig {
editor.putInt("lastSendMessageId", lastSendMessageId); editor.putInt("lastSendMessageId", lastSendMessageId);
editor.putInt("lastLocalId", lastLocalId); editor.putInt("lastLocalId", lastLocalId);
editor.putString("contactsHash", contactsHash); editor.putString("contactsHash", contactsHash);
editor.putString("importHash", importHash);
editor.putBoolean("saveIncomingPhotos", saveIncomingPhotos); editor.putBoolean("saveIncomingPhotos", saveIncomingPhotos);
editor.remove("user"); editor.remove("user");
} }
@ -105,7 +102,7 @@ public class UserConfig {
lastSendMessageId = data.readInt32(); lastSendMessageId = data.readInt32();
lastLocalId = data.readInt32(); lastLocalId = data.readInt32();
contactsHash = data.readString(); contactsHash = data.readString();
importHash = data.readString(); data.readString();
saveIncomingPhotos = data.readBool(); saveIncomingPhotos = data.readBool();
if (currentUser.status != null) { if (currentUser.status != null) {
if (currentUser.status.expires != 0) { if (currentUser.status.expires != 0) {
@ -139,7 +136,6 @@ public class UserConfig {
lastSendMessageId = preferences.getInt("lastSendMessageId", -210000); lastSendMessageId = preferences.getInt("lastSendMessageId", -210000);
lastLocalId = preferences.getInt("lastLocalId", -210000); lastLocalId = preferences.getInt("lastLocalId", -210000);
contactsHash = preferences.getString("contactsHash", ""); contactsHash = preferences.getString("contactsHash", "");
importHash = preferences.getString("importHash", "");
saveIncomingPhotos = preferences.getBoolean("saveIncomingPhotos", false); saveIncomingPhotos = preferences.getBoolean("saveIncomingPhotos", false);
} }
if (lastLocalId > -210000) { if (lastLocalId > -210000) {
@ -164,7 +160,6 @@ public class UserConfig {
lastSendMessageId = preferences.getInt("lastSendMessageId", -210000); lastSendMessageId = preferences.getInt("lastSendMessageId", -210000);
lastLocalId = preferences.getInt("lastLocalId", -210000); lastLocalId = preferences.getInt("lastLocalId", -210000);
contactsHash = preferences.getString("contactsHash", ""); contactsHash = preferences.getString("contactsHash", "");
importHash = preferences.getString("importHash", "");
saveIncomingPhotos = preferences.getBoolean("saveIncomingPhotos", false); saveIncomingPhotos = preferences.getBoolean("saveIncomingPhotos", false);
String user = preferences.getString("user", null); String user = preferences.getString("user", null);
if (user != null) { if (user != null) {
@ -191,7 +186,6 @@ public class UserConfig {
registeredForPush = false; registeredForPush = false;
contactsHash = ""; contactsHash = "";
lastLocalId = -210000; lastLocalId = -210000;
importHash = "";
lastSendMessageId = -210000; lastSendMessageId = -210000;
saveIncomingPhotos = false; saveIncomingPhotos = false;
saveConfig(true); saveConfig(true);

View file

@ -10,13 +10,18 @@ package org.telegram.messenger;
import android.app.Activity; import android.app.Activity;
import android.app.ProgressDialog; import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Typeface; import android.graphics.Typeface;
import android.net.Uri; import android.net.Uri;
import android.os.Build;
import android.os.Environment; import android.os.Environment;
import android.os.Handler; import android.os.Handler;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.Html; import android.text.Html;
import android.text.SpannableStringBuilder; import android.text.SpannableStringBuilder;
import android.text.format.DateFormat; import android.text.format.DateFormat;
@ -49,7 +54,10 @@ import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.Locale; import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream; import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import javax.crypto.Cipher; import javax.crypto.Cipher;
@ -57,8 +65,13 @@ public class Utilities {
public static Handler applicationHandler; public static Handler applicationHandler;
public static int statusBarHeight = 0; public static int statusBarHeight = 0;
public static float density = 1; public static float density = 1;
public static boolean isRTL = false;
public static Pattern pattern = Pattern.compile("[0-9]+");
private final static Integer lock = 1; private final static Integer lock = 1;
private static boolean waitingForSms = false;
private static final Integer smsLock = 2;
public static ArrayList<String> goodPrimes = new ArrayList<String>(); public static ArrayList<String> goodPrimes = new ArrayList<String>();
public static class TPFactorizedValue { public static class TPFactorizedValue {
@ -74,6 +87,30 @@ 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); public native static byte[] aesIgeEncryption(byte[] _what, byte[] _key, byte[] _iv, boolean encrypt, boolean changeIv);
public static boolean isWaitingForSms() {
boolean value = false;
synchronized (smsLock) {
value = waitingForSms;
}
return value;
}
public static void setWaitingForSms(boolean value) {
synchronized (smsLock) {
waitingForSms = value;
}
}
public static Integer parseInt(String value) {
Integer val = 0;
Matcher matcher = pattern.matcher(value);
if (matcher.find()) {
String num = matcher.group(0);
val = Integer.parseInt(num);
}
return val;
}
static { static {
density = ApplicationLoader.applicationContext.getResources().getDisplayMetrics().density; density = ApplicationLoader.applicationContext.getResources().getDisplayMetrics().density;
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("primes", Context.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("primes", Context.MODE_PRIVATE);
@ -360,6 +397,25 @@ public class Utilities {
return null; return null;
} }
public static byte[] compress(byte[] data) {
if (data == null) {
return null;
}
byte[] packedData = null;
ByteArrayOutputStream bytesStream = new ByteArrayOutputStream();
try {
GZIPOutputStream zip = new GZIPOutputStream(bytesStream);
zip.write(data);
zip.close();
packedData = bytesStream.toByteArray();
} catch (IOException e) {
FileLog.e("tmessages", e);
}
return packedData;
}
private static final String TAG = "Typefaces"; private static final String TAG = "Typefaces";
private static final Hashtable<String, Typeface> cache = new Hashtable<String, Typeface>(); private static final Hashtable<String, Typeface> cache = new Hashtable<String, Typeface>();
@ -434,15 +490,25 @@ public class Utilities {
public static FastDateFormat chatDate; public static FastDateFormat chatDate;
public static FastDateFormat chatFullDate; public static FastDateFormat chatFullDate;
static { public static void recreateFormatters() {
Locale locale = Locale.getDefault(); Locale locale = Locale.getDefault();
String lang = locale.getLanguage(); String lang = locale.getLanguage();
if (lang == null) {
lang = "en";
}
isRTL = lang.toLowerCase().equals("ar");
if (lang.equals("en")) { if (lang.equals("en")) {
formatterMonth = FastDateFormat.getInstance("MMM dd", locale); formatterMonth = FastDateFormat.getInstance("MMM dd", locale);
formatterYear = FastDateFormat.getInstance("dd.MM.yy", locale); formatterYear = FastDateFormat.getInstance("dd.MM.yy", locale);
formatterYearMax = FastDateFormat.getInstance("dd.MM.yyyy", locale); formatterYearMax = FastDateFormat.getInstance("dd.MM.yyyy", locale);
chatDate = FastDateFormat.getInstance("MMMM d", locale); chatDate = FastDateFormat.getInstance("MMMM d", locale);
chatFullDate = FastDateFormat.getInstance("MMMM d, yyyy", locale); chatFullDate = FastDateFormat.getInstance("MMMM d, yyyy", locale);
} else if (lang.startsWith("es")) {
formatterMonth = FastDateFormat.getInstance("dd 'de' MMM", locale);
formatterYear = FastDateFormat.getInstance("dd.MM.yy", locale);
formatterYearMax = FastDateFormat.getInstance("dd.MM.yyyy", locale);
chatDate = FastDateFormat.getInstance("d 'de' MMMM", locale);
chatFullDate = FastDateFormat.getInstance("d 'de' MMMM 'de' yyyy", locale);
} else { } else {
formatterMonth = FastDateFormat.getInstance("dd MMM", locale); formatterMonth = FastDateFormat.getInstance("dd MMM", locale);
formatterYear = FastDateFormat.getInstance("dd.MM.yy", locale); formatterYear = FastDateFormat.getInstance("dd.MM.yy", locale);
@ -467,6 +533,10 @@ public class Utilities {
} }
} }
static {
recreateFormatters();
}
public static String formatDateChat(long date) { public static String formatDateChat(long date) {
Calendar rightNow = Calendar.getInstance(); Calendar rightNow = Calendar.getInstance();
int year = rightNow.get(Calendar.YEAR); int year = rightNow.get(Calendar.YEAR);
@ -508,13 +578,13 @@ public class Utilities {
int dateYear = rightNow.get(Calendar.YEAR); int dateYear = rightNow.get(Calendar.YEAR);
if (dateDay == day && year == dateYear) { if (dateDay == day && year == dateYear) {
return String.format("%s %s", ApplicationLoader.applicationContext.getResources().getString(R.string.TodayAt), formatterDay.format(new Date(date * 1000))); return String.format("%s %s %s", ApplicationLoader.applicationContext.getString(R.string.LastSeen), ApplicationLoader.applicationContext.getString(R.string.TodayAt), formatterDay.format(new Date(date * 1000)));
} else if (dateDay + 1 == day && year == dateYear) { } else if (dateDay + 1 == day && year == dateYear) {
return String.format("%s %s", ApplicationLoader.applicationContext.getResources().getString(R.string.YesterdayAt), formatterDay.format(new Date(date * 1000))); return String.format("%s %s %s", ApplicationLoader.applicationContext.getString(R.string.LastSeen), ApplicationLoader.applicationContext.getString(R.string.YesterdayAt), formatterDay.format(new Date(date * 1000)));
} else if (year == dateYear) { } else if (year == dateYear) {
return String.format("%s %s %s", formatterMonth.format(new Date(date * 1000)), ApplicationLoader.applicationContext.getResources().getString(R.string.OtherAt), formatterDay.format(new Date(date * 1000))); return String.format("%s %s %s %s", ApplicationLoader.applicationContext.getString(R.string.LastSeenDate), formatterMonth.format(new Date(date * 1000)), ApplicationLoader.applicationContext.getString(R.string.OtherAt), formatterDay.format(new Date(date * 1000)));
} else { } else {
return String.format("%s %s %s", formatterYear.format(new Date(date * 1000)), ApplicationLoader.applicationContext.getResources().getString(R.string.OtherAt), formatterDay.format(new Date(date * 1000))); return String.format("%s %s %s %s", ApplicationLoader.applicationContext.getString(R.string.LastSeenDate), formatterYear.format(new Date(date * 1000)), ApplicationLoader.applicationContext.getString(R.string.OtherAt), formatterDay.format(new Date(date * 1000)));
} }
} }
@ -556,9 +626,6 @@ public class Utilities {
public static void RunOnUIThread(Runnable runnable) { public static void RunOnUIThread(Runnable runnable) {
synchronized (lock) { synchronized (lock) {
if (applicationHandler == null) {
applicationHandler = new Handler(ApplicationLoader.applicationContext.getMainLooper());
}
applicationHandler.post(runnable); applicationHandler.post(runnable);
} }
} }
@ -682,6 +749,83 @@ public class Utilities {
return storageDir; return storageDir;
} }
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
} else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
} else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public static File generatePicturePath() { public static File generatePicturePath() {
try { try {
File storageDir = getAlbumDir(); File storageDir = getAlbumDir();

View file

@ -22,6 +22,7 @@ import org.telegram.ui.ApplicationLoader;
import java.util.AbstractMap; import java.util.AbstractMap;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
public class MessageObject { public class MessageObject {
@ -33,6 +34,7 @@ public class MessageObject {
public PhotoObject previewPhoto; public PhotoObject previewPhoto;
public String dateKey; public String dateKey;
public boolean deleted = false; public boolean deleted = false;
public Object TAG;
public MessageObject(TLRPC.Message message, AbstractMap<Integer, TLRPC.User> users) { public MessageObject(TLRPC.Message message, AbstractMap<Integer, TLRPC.User> users) {
messageOwner = message; messageOwner = message;
@ -45,7 +47,7 @@ public class MessageObject {
} }
if (message.action instanceof TLRPC.TL_messageActionChatCreate) { if (message.action instanceof TLRPC.TL_messageActionChatCreate) {
if (message.from_id == UserConfig.clientUserId) { if (message.from_id == UserConfig.clientUserId) {
messageText = ApplicationLoader.applicationContext.getString(R.string.ActionCreateGroup).replace("un1", ApplicationLoader.applicationContext.getString(R.string.FromYou)); messageText = ApplicationLoader.applicationContext.getString(R.string.ActionYouCreateGroup);
} else { } else {
if (fromUser != null) { if (fromUser != null) {
messageText = ApplicationLoader.applicationContext.getString(R.string.ActionCreateGroup).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name)); messageText = ApplicationLoader.applicationContext.getString(R.string.ActionCreateGroup).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name));
@ -56,7 +58,7 @@ public class MessageObject {
} else if (message.action instanceof TLRPC.TL_messageActionChatDeleteUser) { } else if (message.action instanceof TLRPC.TL_messageActionChatDeleteUser) {
if (message.action.user_id == message.from_id) { if (message.action.user_id == message.from_id) {
if (message.from_id == UserConfig.clientUserId) { if (message.from_id == UserConfig.clientUserId) {
messageText = ApplicationLoader.applicationContext.getString(R.string.ActionLeftUser).replace("un1", ApplicationLoader.applicationContext.getString(R.string.FromYou)); messageText = ApplicationLoader.applicationContext.getString(R.string.ActionYouLeftUser);
} else { } else {
if (fromUser != null) { if (fromUser != null) {
messageText = ApplicationLoader.applicationContext.getString(R.string.ActionLeftUser).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name)); messageText = ApplicationLoader.applicationContext.getString(R.string.ActionLeftUser).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name));
@ -69,17 +71,16 @@ public class MessageObject {
if (who == null) { if (who == null) {
MessagesController.Instance.users.get(message.action.user_id); MessagesController.Instance.users.get(message.action.user_id);
} }
String str = ApplicationLoader.applicationContext.getString(R.string.ActionKickUser);
if (who != null && fromUser != null) { if (who != null && fromUser != null) {
if (message.from_id == UserConfig.clientUserId) { if (message.from_id == UserConfig.clientUserId) {
messageText = str.replace("un2", Utilities.formatName(who.first_name, who.last_name)).replace("un1", ApplicationLoader.applicationContext.getString(R.string.FromYou)); messageText = ApplicationLoader.applicationContext.getString(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.clientUserId) {
messageText = str.replace("un2", ApplicationLoader.applicationContext.getString(R.string.FromYou)).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name)); messageText = ApplicationLoader.applicationContext.getString(R.string.ActionKickUserYou).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name));
} else { } else {
messageText = str.replace("un2", Utilities.formatName(who.first_name, who.last_name)).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name)); messageText = ApplicationLoader.applicationContext.getString(R.string.ActionKickUser).replace("un2", Utilities.formatName(who.first_name, who.last_name)).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name));
} }
} else { } else {
messageText = str.replace("un2", "").replace("un1", ""); messageText = ApplicationLoader.applicationContext.getString(R.string.ActionKickUser).replace("un2", "").replace("un1", "");
} }
} }
} else if (message.action instanceof TLRPC.TL_messageActionChatAddUser) { } else if (message.action instanceof TLRPC.TL_messageActionChatAddUser) {
@ -87,17 +88,16 @@ public class MessageObject {
if (whoUser == null) { if (whoUser == null) {
MessagesController.Instance.users.get(message.action.user_id); MessagesController.Instance.users.get(message.action.user_id);
} }
String str = ApplicationLoader.applicationContext.getString(R.string.ActionAddUser);
if (whoUser != null && fromUser != null) { if (whoUser != null && fromUser != null) {
if (message.from_id == UserConfig.clientUserId) { if (message.from_id == UserConfig.clientUserId) {
messageText = str.replace("un2", Utilities.formatName(whoUser.first_name, whoUser.last_name)).replace("un1", ApplicationLoader.applicationContext.getString(R.string.FromYou)); messageText = ApplicationLoader.applicationContext.getString(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.clientUserId) {
messageText = str.replace("un2", ApplicationLoader.applicationContext.getString(R.string.FromYou)).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name)); messageText = ApplicationLoader.applicationContext.getString(R.string.ActionAddUserYou).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name));
} else { } else {
messageText = str.replace("un2", Utilities.formatName(whoUser.first_name, whoUser.last_name)).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name)); messageText = ApplicationLoader.applicationContext.getString(R.string.ActionAddUser).replace("un2", Utilities.formatName(whoUser.first_name, whoUser.last_name)).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name));
} }
} else { } else {
messageText = str.replace("un2", "").replace("un1", ""); messageText = ApplicationLoader.applicationContext.getString(R.string.ActionAddUser).replace("un2", "").replace("un1", "");
} }
} else if (message.action instanceof TLRPC.TL_messageActionChatEditPhoto) { } else if (message.action instanceof TLRPC.TL_messageActionChatEditPhoto) {
photoThumbs = new ArrayList<PhotoObject>(); photoThumbs = new ArrayList<PhotoObject>();
@ -105,7 +105,7 @@ public class MessageObject {
photoThumbs.add(new PhotoObject(size)); photoThumbs.add(new PhotoObject(size));
} }
if (message.from_id == UserConfig.clientUserId) { if (message.from_id == UserConfig.clientUserId) {
messageText = ApplicationLoader.applicationContext.getString(R.string.ActionChangedPhoto).replace("un1", ApplicationLoader.applicationContext.getString(R.string.FromYou)); messageText = ApplicationLoader.applicationContext.getString(R.string.ActionYouChangedPhoto);
} else { } else {
if (fromUser != null) { if (fromUser != null) {
messageText = ApplicationLoader.applicationContext.getString(R.string.ActionChangedPhoto).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name)); messageText = ApplicationLoader.applicationContext.getString(R.string.ActionChangedPhoto).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name));
@ -115,7 +115,7 @@ public class MessageObject {
} }
} else if (message.action instanceof TLRPC.TL_messageActionChatEditTitle) { } else if (message.action instanceof TLRPC.TL_messageActionChatEditTitle) {
if (message.from_id == UserConfig.clientUserId) { if (message.from_id == UserConfig.clientUserId) {
messageText = ApplicationLoader.applicationContext.getString(R.string.ActionChangedTitle).replace("un1", ApplicationLoader.applicationContext.getString(R.string.FromYou)).replace("un2", message.action.title); messageText = ApplicationLoader.applicationContext.getString(R.string.ActionYouChangedTitle).replace("un2", message.action.title);
} else { } else {
if (fromUser != null) { if (fromUser != null) {
messageText = ApplicationLoader.applicationContext.getString(R.string.ActionChangedTitle).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name)).replace("un2", message.action.title); messageText = ApplicationLoader.applicationContext.getString(R.string.ActionChangedTitle).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name)).replace("un2", message.action.title);
@ -125,7 +125,7 @@ public class MessageObject {
} }
} else if (message.action instanceof TLRPC.TL_messageActionChatDeletePhoto) { } else if (message.action instanceof TLRPC.TL_messageActionChatDeletePhoto) {
if (message.from_id == UserConfig.clientUserId) { if (message.from_id == UserConfig.clientUserId) {
messageText = ApplicationLoader.applicationContext.getString(R.string.ActionRemovedPhoto).replace("un1", ApplicationLoader.applicationContext.getString(R.string.FromYou)); messageText = ApplicationLoader.applicationContext.getString(R.string.ActionYouRemovedPhoto);
} else { } else {
if (fromUser != null) { if (fromUser != null) {
messageText = ApplicationLoader.applicationContext.getString(R.string.ActionRemovedPhoto).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name)); messageText = ApplicationLoader.applicationContext.getString(R.string.ActionRemovedPhoto).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name));
@ -162,7 +162,7 @@ public class MessageObject {
} }
} else { } else {
if (message.from_id == UserConfig.clientUserId) { if (message.from_id == UserConfig.clientUserId) {
messageText = String.format(ApplicationLoader.applicationContext.getString(R.string.MessageLifetimeRemoved), ApplicationLoader.applicationContext.getString(R.string.FromYou)); messageText = String.format(ApplicationLoader.applicationContext.getString(R.string.MessageLifetimeYouRemoved));
} else { } else {
if (fromUser != null) { if (fromUser != null) {
messageText = String.format(ApplicationLoader.applicationContext.getString(R.string.MessageLifetimeRemoved), fromUser.first_name); messageText = String.format(ApplicationLoader.applicationContext.getString(R.string.MessageLifetimeRemoved), fromUser.first_name);
@ -172,7 +172,8 @@ public class MessageObject {
} }
} }
} else if (message.action instanceof TLRPC.TL_messageActionLoginUnknownLocation) { } else if (message.action instanceof TLRPC.TL_messageActionLoginUnknownLocation) {
messageText = ApplicationLoader.applicationContext.getString(R.string.NotificationUnrecognizedDevice, message.action.title, message.action.address); String date = String.format("%s %s %s", Utilities.formatterYear.format(((long)message.date) * 1000), ApplicationLoader.applicationContext.getString(R.string.OtherAt), Utilities.formatterDay.format(((long)message.date) * 1000));
messageText = ApplicationLoader.applicationContext.getString(R.string.NotificationUnrecognizedDevice, UserConfig.currentUser.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 = ApplicationLoader.applicationContext.getString(R.string.NotificationContactJoined, Utilities.formatName(fromUser.first_name, fromUser.last_name)); messageText = ApplicationLoader.applicationContext.getString(R.string.NotificationContactJoined, Utilities.formatName(fromUser.first_name, fromUser.last_name));
@ -266,9 +267,17 @@ public class MessageObject {
} else { } else {
type = 17; type = 17;
} }
} else if (message.media != null && message.media instanceof TLRPC.TL_messageMediaAudio) {
if (message.from_id == UserConfig.clientUserId) {
type = 0;
} else {
type = 1;
}
} }
} else if (message instanceof TLRPC.TL_messageService) { } else if (message instanceof TLRPC.TL_messageService) {
if (message.action instanceof TLRPC.TL_messageActionChatEditPhoto || message.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) { if (message.action instanceof TLRPC.TL_messageActionLoginUnknownLocation) {
type = 1;
} else if (message.action instanceof TLRPC.TL_messageActionChatEditPhoto || message.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) {
type = 11; type = 11;
} else { } else {
type = 10; type = 10;

View file

@ -30,7 +30,7 @@ public class PhotoObject {
opts.outWidth = photo.w; opts.outWidth = photo.w;
opts.outHeight = photo.h; opts.outHeight = photo.h;
image = BitmapFactory.decodeByteArray(photoOwner.bytes, 0, photoOwner.bytes.length, opts); image = BitmapFactory.decodeByteArray(photoOwner.bytes, 0, photoOwner.bytes.length, opts);
if (FileLoader.Instance.runtimeHack != null) { if (image != null && FileLoader.Instance.runtimeHack != null) {
FileLoader.Instance.runtimeHack.trackFree(image.getRowBytes() * image.getHeight()); FileLoader.Instance.runtimeHack.trackFree(image.getRowBytes() * image.getHeight());
} }
} }
@ -46,7 +46,7 @@ public class PhotoObject {
} }
int diffW = Math.abs(obj.photoOwner.w - width); int diffW = Math.abs(obj.photoOwner.w - width);
int diffH = Math.abs(obj.photoOwner.h - height); int diffH = Math.abs(obj.photoOwner.h - height);
if (closestObject == null || closestWidth > diffW && closestHeight > diffH || closestObject.photoOwner instanceof TLRPC.TL_photoCachedSize) { if (closestObject == null || closestWidth > diffW || closestHeight > diffH || closestObject.photoOwner instanceof TLRPC.TL_photoCachedSize) {
closestObject = obj; closestObject = obj;
closestWidth = diffW; closestWidth = diffW;
closestHeight = diffH; closestHeight = diffH;

View file

@ -25,6 +25,7 @@ import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.view.ViewTreeObserver; import android.view.ViewTreeObserver;
import android.view.WindowManager; import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView; import android.widget.TextView;
import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.ConnectionsManager;
@ -196,7 +197,7 @@ public class ApplicationActivity extends ActionBarActivity implements Notificati
method.invoke(field.get(getSupportActionBar()), false); method.invoke(field.get(getSupportActionBar()), false);
} }
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); e.printStackTrace();
} }
} }
@ -333,6 +334,10 @@ public class ApplicationActivity extends ActionBarActivity implements Notificati
if (notificationView != null) { if (notificationView != null) {
notificationView.hide(false); notificationView.hide(false);
} }
View focusView = getCurrentFocus();
if (focusView instanceof EditText) {
focusView.clearFocus();
}
} }
@Override @Override
@ -581,13 +586,13 @@ public class ApplicationActivity extends ActionBarActivity implements Notificati
try { try {
if (statusView.getLayoutParams() instanceof android.support.v7.app.ActionBar.LayoutParams) { if (statusView.getLayoutParams() instanceof android.support.v7.app.ActionBar.LayoutParams) {
android.support.v7.app.ActionBar.LayoutParams statusParams = (android.support.v7.app.ActionBar.LayoutParams)statusView.getLayoutParams(); android.support.v7.app.ActionBar.LayoutParams statusParams = (android.support.v7.app.ActionBar.LayoutParams)statusView.getLayoutParams();
statusText.measure(View.MeasureSpec.makeMeasureSpec(800, View.MeasureSpec.AT_MOST), 100); statusText.measure(View.MeasureSpec.makeMeasureSpec(800, View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.AT_MOST));
statusParams.width = (int)(statusText.getMeasuredWidth() + Utilities.dp(54)); statusParams.width = (statusText.getMeasuredWidth() + Utilities.dp(54));
statusView.setLayoutParams(statusParams); statusView.setLayoutParams(statusParams);
} else if (statusView.getLayoutParams() instanceof android.app.ActionBar.LayoutParams) { } else if (statusView.getLayoutParams() instanceof android.app.ActionBar.LayoutParams) {
android.app.ActionBar.LayoutParams statusParams = (android.app.ActionBar.LayoutParams)statusView.getLayoutParams(); android.app.ActionBar.LayoutParams statusParams = (android.app.ActionBar.LayoutParams)statusView.getLayoutParams();
statusText.measure(View.MeasureSpec.makeMeasureSpec(800, View.MeasureSpec.AT_MOST), 100); statusText.measure(View.MeasureSpec.makeMeasureSpec(800, View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.AT_MOST));
statusParams.width = (int)(statusText.getMeasuredWidth() + Utilities.dp(54)); statusParams.width = (statusText.getMeasuredWidth() + Utilities.dp(54));
statusView.setLayoutParams(statusParams); statusView.setLayoutParams(statusParams);
} }
} catch (Exception e) { } catch (Exception e) {
@ -621,7 +626,7 @@ public class ApplicationActivity extends ActionBarActivity implements Notificati
ApplicationLoader.fragmentsStack.remove(ApplicationLoader.fragmentsStack.size() - 1); ApplicationLoader.fragmentsStack.remove(ApplicationLoader.fragmentsStack.size() - 1);
current.onFragmentDestroy(); current.onFragmentDestroy();
} }
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
boolean animations = preferences.getBoolean("view_animations", true); boolean animations = preferences.getBoolean("view_animations", true);
if (animations) { if (animations) {
if (bySwipe) { if (bySwipe) {
@ -660,7 +665,7 @@ public class ApplicationActivity extends ActionBarActivity implements Notificati
BaseFragment prev = ApplicationLoader.fragmentsStack.get(ApplicationLoader.fragmentsStack.size() - 2); BaseFragment prev = ApplicationLoader.fragmentsStack.get(ApplicationLoader.fragmentsStack.size() - 2);
FragmentManager fm = getSupportFragmentManager(); FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fTrans = fm.beginTransaction(); FragmentTransaction fTrans = fm.beginTransaction();
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
boolean animations = preferences.getBoolean("view_animations", true); boolean animations = preferences.getBoolean("view_animations", true);
if (animations) { if (animations) {
if (bySwipe) { if (bySwipe) {

View file

@ -8,13 +8,16 @@
package org.telegram.ui; package org.telegram.ui;
import android.app.Activity;
import android.app.Application; import android.app.Application;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; 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.graphics.Bitmap; import android.graphics.Bitmap;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.Handler;
import android.view.ViewConfiguration; import android.view.ViewConfiguration;
import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.ConnectionResult;
@ -22,7 +25,6 @@ import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging; import com.google.android.gms.gcm.GoogleCloudMessaging;
import org.telegram.PhoneFormat.PhoneFormat; import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.TL.TLRPC;
import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLog; import org.telegram.messenger.FileLog;
import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesController;
@ -34,6 +36,7 @@ import org.telegram.ui.Views.BaseFragment;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
public class ApplicationLoader extends Application { public class ApplicationLoader extends Application {
@ -48,6 +51,7 @@ public class ApplicationLoader extends Application {
public static long lastPauseTime; public static long lastPauseTime;
public static Bitmap cachedWallpaper = null; public static Bitmap cachedWallpaper = null;
public static Context applicationContext; public static Context applicationContext;
private Locale currentLocale;
public static ApplicationLoader Instance = null; public static ApplicationLoader Instance = null;
@ -56,42 +60,47 @@ public class ApplicationLoader extends Application {
@Override @Override
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
currentLocale = Locale.getDefault();
Instance = this; Instance = this;
java.lang.System.setProperty("java.net.preferIPv4Stack", "true"); java.lang.System.setProperty("java.net.preferIPv4Stack", "true");
java.lang.System.setProperty("java.net.preferIPv6Addresses", "false"); java.lang.System.setProperty("java.net.preferIPv6Addresses", "false");
applicationContext = getApplicationContext(); applicationContext = getApplicationContext();
Utilities.getTypeface("fonts/rmedium.ttf"); Utilities.applicationHandler = new Handler(applicationContext.getMainLooper());
UserConfig.loadConfig();
SharedPreferences preferences = getSharedPreferences("Notifications", MODE_PRIVATE);
if (UserConfig.currentUser != null) {
int value = preferences.getInt("version", 0);
if (value != 15) {
UserConfig.contactsHash = "";
MessagesStorage.lastDateValue = 0;
MessagesStorage.lastPtsValue = 0;
MessagesStorage.lastSeqValue = 0;
MessagesStorage.lastQtsValue = 0;
UserConfig.saveConfig(false);
MessagesStorage.Instance.cleanUp();
ArrayList<TLRPC.User> users = new ArrayList<TLRPC.User>();
users.add(UserConfig.currentUser);
MessagesStorage.Instance.putUsersAndChats(users, null, true, true);
SharedPreferences.Editor editor = preferences.edit(); UserConfig.loadConfig();
editor.putInt("version", 15); if (UserConfig.currentUser != null) {
boolean changed = false;
SharedPreferences preferences = getSharedPreferences("Notifications", MODE_PRIVATE);
int v = preferences.getInt("v", 0);
if (v != 1) {
SharedPreferences preferences2 = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences2.edit();
if (preferences.contains("view_animations")) {
editor.putBoolean("view_animations", preferences.getBoolean("view_animations", false));
}
if (preferences.contains("selectedBackground")) {
editor.putInt("selectedBackground", preferences.getInt("selectedBackground", 1000001));
}
if (preferences.contains("selectedColor")) {
editor.putInt("selectedColor", preferences.getInt("selectedColor", 0));
}
if (preferences.contains("fons_size")) {
editor.putInt("fons_size", preferences.getInt("fons_size", 16));
}
editor.commit();
editor = preferences.edit();
editor.putInt("v", 1);
editor.remove("view_animations");
editor.remove("selectedBackground");
editor.remove("selectedColor");
editor.remove("fons_size");
editor.commit(); editor.commit();
} else {
MessagesStorage init = MessagesStorage.Instance;
} }
MessagesStorage init = MessagesStorage.Instance;
MessagesController.Instance.users.put(UserConfig.clientUserId, UserConfig.currentUser); MessagesController.Instance.users.put(UserConfig.clientUserId, UserConfig.currentUser);
} else {
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("version", 15);
editor.commit();
} }
MessagesController.Instance.checkAppAccount();
try { try {
ViewConfiguration config = ViewConfiguration.get(this); ViewConfiguration config = ViewConfiguration.get(this);
@ -101,7 +110,7 @@ public class ApplicationLoader extends Application {
menuKeyField.setBoolean(config, false); menuKeyField.setBoolean(config, false);
} }
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); e.printStackTrace();
} }
if (checkPlayServices()) { if (checkPlayServices()) {
@ -123,6 +132,20 @@ public class ApplicationLoader extends Application {
FileLog.e("tmessages", "start application with time " + lastPauseTime); FileLog.e("tmessages", "start application with time " + lastPauseTime);
} }
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Locale newLocale = newConfig.locale;
if (newLocale != null) {
String d1 = newLocale.getDisplayName();
String d2 = currentLocale.getDisplayName();
if (d1 != null && d2 != null && !d1.equals(d2)) {
Utilities.recreateFormatters();
}
currentLocale = newLocale;
}
}
public static void resetLastPauseTime() { public static void resetLastPauseTime() {
lastPauseTime = 0; lastPauseTime = 0;
ConnectionsManager.Instance.applicationMovedToForeground(); ConnectionsManager.Instance.applicationMovedToForeground();

View file

@ -0,0 +1,36 @@
/*
* This is the source code of Telegram for Android v. 1.3.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.
*/
package org.telegram.ui.Cells;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
public class BaseCell extends View {
public BaseCell(Context context) {
super(context);
}
public BaseCell(Context context, AttributeSet attrs) {
super(context, attrs);
}
public BaseCell(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
protected void setDrawableBounds(Drawable drawable, int x, int y) {
setDrawableBounds(drawable, x, y, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
}
protected void setDrawableBounds(Drawable drawable, int x, int y, int w, int h) {
drawable.setBounds(x, y, x + w, y + h);
}
}

View file

@ -0,0 +1,464 @@
/*
* This is the source code of Telegram for Android v. 1.3.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.
*/
package org.telegram.ui.Cells;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.TL.TLRPC;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.R;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
import org.telegram.ui.ApplicationLoader;
import org.telegram.ui.Views.ImageReceiver;
import java.lang.ref.WeakReference;
public class ChatOrUserCell extends BaseCell {
private static TextPaint namePaint;
private static TextPaint nameEncryptedPaint;
private static TextPaint onlinePaint;
private static TextPaint offlinePaint;
private static Drawable lockDrawable;
private static Paint linePaint;
private CharSequence currentName;
private ImageReceiver avatarImage;
private String subLabel;
private ChatOrUserCellLayout cellLayout;
private TLRPC.User user = null;
private TLRPC.Chat chat = null;
private TLRPC.EncryptedChat encryptedChat = null;
private String lastName = null;
private int lastStatus = 0;
private TLRPC.FileLocation lastAvatar = null;
public boolean usePadding = true;
public boolean useBoldFont = false;
public boolean useSeparator = false;
public float drawAlpha = 1;
public ChatOrUserCell(Context context) {
super(context);
init();
}
public ChatOrUserCell(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ChatOrUserCell(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
if (namePaint == null) {
namePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
namePaint.setTextSize(Utilities.dp(18));
namePaint.setColor(0xff222222);
}
if (nameEncryptedPaint == null) {
nameEncryptedPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
nameEncryptedPaint.setTextSize(Utilities.dp(18));
nameEncryptedPaint.setColor(0xff00a60e);
}
if (onlinePaint == null) {
onlinePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
onlinePaint.setTextSize(Utilities.dp(15));
onlinePaint.setColor(0xff316f9f);
}
if (offlinePaint == null) {
offlinePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
offlinePaint.setTextSize(Utilities.dp(15));
offlinePaint.setColor(0xff999999);
}
if (lockDrawable == null) {
lockDrawable = getResources().getDrawable(R.drawable.ic_lock_green);
}
if (linePaint == null) {
linePaint = new Paint();
linePaint.setColor(0xffdcdcdc);
}
if (avatarImage == null) {
avatarImage = new ImageReceiver();
avatarImage.parentView = new WeakReference<View>(this);
}
if (cellLayout == null) {
cellLayout = new ChatOrUserCellLayout();
}
}
public void setData(TLRPC.User u, TLRPC.Chat c, TLRPC.EncryptedChat ec, CharSequence n, String s) {
currentName = n;
user = u;
chat = c;
encryptedChat = ec;
subLabel = s;
update(0);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), Utilities.dp(64));
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
if (user == null && chat == null && encryptedChat == null) {
super.onLayout(changed, left, top, right, bottom);
return;
}
if (changed) {
buildLayout();
}
}
public void buildLayout() {
cellLayout.build(getMeasuredWidth(), getMeasuredHeight());
}
public void update(int mask) {
int placeHolderId = 0;
TLRPC.FileLocation photo = null;
if (user != null) {
if (user.photo != null) {
photo = user.photo.photo_small;
}
placeHolderId = Utilities.getUserAvatarForId(user.id);
} else if (chat != null) {
if (chat.photo != null) {
photo = chat.photo.photo_small;
}
placeHolderId = Utilities.getGroupAvatarForId(chat.id);
}
if (mask != 0) {
boolean continueUpdate = false;
if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 && user != null || (mask & MessagesController.UPDATE_MASK_CHAT_AVATAR) != 0 && chat != null) {
if (lastAvatar != null && photo == null || lastAvatar == null && photo != null && lastAvatar != null && photo != null && (lastAvatar.volume_id != photo.volume_id || lastAvatar.local_id != photo.local_id)) {
continueUpdate = true;
}
}
if (!continueUpdate && (mask & MessagesController.UPDATE_MASK_STATUS) != 0 && user != null) {
int newStatus = 0;
if (user.status != null) {
newStatus = user.status.expires;
if (lastStatus == 0) {
lastStatus = user.status.was_online;
}
}
if (newStatus != lastStatus) {
continueUpdate = true;
}
}
if (!continueUpdate && ((mask & MessagesController.UPDATE_MASK_NAME) != 0 && user != null) || (mask & MessagesController.UPDATE_MASK_CHAT_NAME) != 0 && chat != null) {
String newName;
if (user != null) {
newName = user.first_name + user.last_name;
} else {
newName = chat.title;
}
if (!newName.equals(lastName)) {
continueUpdate = true;
}
}
if (!continueUpdate) {
return;
}
}
if (user != null) {
if (user.status != null) {
lastStatus = user.status.expires;
if (lastStatus == 0) {
lastStatus = user.status.was_online;
}
} else {
lastStatus = 0;
}
lastName = user.first_name + user.last_name;
} else if (chat != null) {
lastName = chat.title;
}
lastAvatar = photo;
avatarImage.setImage(photo, "50_50", placeHolderId == 0 ? null : getResources().getDrawable(placeHolderId));
if (getMeasuredWidth() != 0 || getMeasuredHeight() != 0) {
buildLayout();
} else {
requestLayout();
}
postInvalidate();
}
@Override
protected void onDraw(Canvas canvas) {
if (user == null && chat == null && encryptedChat == null) {
return;
}
if (cellLayout == null) {
requestLayout();
return;
}
if (drawAlpha != 1) {
canvas.saveLayerAlpha(0, 0, canvas.getWidth(), canvas.getHeight(), (int)(255 * drawAlpha), Canvas.HAS_ALPHA_LAYER_SAVE_FLAG);
}
if (cellLayout.drawNameLock) {
setDrawableBounds(lockDrawable, cellLayout.nameLockLeft, cellLayout.nameLockTop);
lockDrawable.draw(canvas);
}
canvas.save();
canvas.translate(cellLayout.nameLeft, cellLayout.nameTop);
cellLayout.nameLayout.draw(canvas);
canvas.restore();
if (cellLayout.onlineLayout != null) {
canvas.save();
canvas.translate(cellLayout.onlineLeft, cellLayout.onlineTop);
cellLayout.onlineLayout.draw(canvas);
canvas.restore();
}
avatarImage.draw(canvas, cellLayout.avatarLeft, cellLayout.avatarTop, Utilities.dp(50), Utilities.dp(50));
if (useSeparator) {
int h = getMeasuredHeight();
if (!usePadding) {
canvas.drawLine(0, h - 1, getMeasuredWidth(), h, linePaint);
} else {
canvas.drawLine(Utilities.dp(11), h - 1, getMeasuredWidth() - Utilities.dp(11), h, linePaint);
}
}
}
private class ChatOrUserCellLayout {
private int nameLeft;
private int nameTop;
private int nameWidth;
private StaticLayout nameLayout;
private boolean drawNameLock;
private int nameLockLeft;
private int nameLockTop = Utilities.dp(15);
private int onlineLeft;
private int onlineTop = Utilities.dp(36);
private int onlineWidth;
private StaticLayout onlineLayout;
private int avatarTop = Utilities.dp(7);
private int avatarLeft;
public void build(int width, int height) {
CharSequence nameString = "";
TextPaint currentNamePaint;
if (encryptedChat != null) {
drawNameLock = true;
if (!Utilities.isRTL) {
nameLockLeft = Utilities.dp(61 + (usePadding ? 11 : 0));
nameLeft = Utilities.dp(65 + (usePadding ? 11 : 0)) + lockDrawable.getIntrinsicWidth();
} else {
nameLockLeft = width - Utilities.dp(63 + (usePadding ? 11 : 0)) - lockDrawable.getIntrinsicWidth();
nameLeft = usePadding ? Utilities.dp(11) : 0;
}
} else {
drawNameLock = false;
if (!Utilities.isRTL) {
nameLeft = Utilities.dp(61 + (usePadding ? 11 : 0));
} else {
nameLeft = usePadding ? Utilities.dp(11) : 0;
}
}
if (currentName != null) {
nameString = currentName;
} else {
if (useBoldFont) {
if (user != null) {
if (user.first_name.length() != 0 && user.last_name.length() != 0) {
nameString = Html.fromHtml(user.first_name + " <b>" + user.last_name + "</b>");
} else if (user.first_name.length() != 0) {
nameString = Html.fromHtml("<b>" + user.first_name + "</b>");
} else {
nameString = Html.fromHtml("<b>" + user.last_name + "</b>");
}
}
} else {
String nameString2 = "";
if (chat != null) {
nameString2 = chat.title;
} else if (user != null) {
if (user.id != 333000 && ContactsController.Instance.contactsDict.get(user.id) == null) {
if (ContactsController.Instance.contactsDict.size() == 0 && ContactsController.Instance.loadingContacts) {
nameString2 = Utilities.formatName(user.first_name, user.last_name);
} else {
if (user.phone != null && user.phone.length() != 0) {
nameString2 = PhoneFormat.Instance.format("+" + user.phone);
} else {
nameString2 = Utilities.formatName(user.first_name, user.last_name);
}
}
} else {
nameString2 = Utilities.formatName(user.first_name, user.last_name);
}
}
nameString = nameString2.replace("\n", " ");
}
}
if (nameString.length() == 0) {
nameString = ApplicationLoader.applicationContext.getString(R.string.HiddenName);
}
if (encryptedChat != null) {
currentNamePaint = nameEncryptedPaint;
} else {
currentNamePaint = namePaint;
}
if (!Utilities.isRTL) {
onlineWidth = nameWidth = width - nameLeft - Utilities.dp(3 + (usePadding ? 11 : 0));
} else {
onlineWidth = nameWidth = width - nameLeft - Utilities.dp(61 + (usePadding ? 11 : 0));
}
if (drawNameLock) {
nameWidth -= Utilities.dp(6) + lockDrawable.getIntrinsicWidth();
}
CharSequence nameStringFinal = TextUtils.ellipsize(nameString, currentNamePaint, nameWidth - Utilities.dp(12), TextUtils.TruncateAt.END);
nameLayout = new StaticLayout(nameStringFinal, currentNamePaint, nameWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
if (chat == null) {
if (!Utilities.isRTL) {
onlineLeft = Utilities.dp(61 + (usePadding ? 11 : 0));
} else {
onlineLeft = usePadding ? Utilities.dp(11) : 0;
}
String onlineString = "";
TextPaint currentOnlinePaint = offlinePaint;
if (subLabel != null) {
onlineString = subLabel;
} else {
if (user != null) {
if (user.status == null) {
onlineString = getResources().getString(R.string.Offline);
} else {
int currentTime = ConnectionsManager.Instance.getCurrentTime();
if (user.id == UserConfig.clientUserId || user.status.expires > currentTime || user.status.was_online > currentTime) {
currentOnlinePaint = onlinePaint;
onlineString = getResources().getString(R.string.Online);
} else {
if (user.status.was_online <= 10000 && user.status.expires <= 10000) {
onlineString = getResources().getString(R.string.Invisible);
} else {
int value = user.status.was_online;
if (value == 0) {
value = user.status.expires;
}
onlineString = getResources().getString(R.string.LastSeen) + " " + Utilities.formatDateOnline(value);
}
}
}
}
}
CharSequence onlineStringFinal = TextUtils.ellipsize(onlineString, currentOnlinePaint, nameWidth - Utilities.dp(12), TextUtils.TruncateAt.END);
onlineLayout = new StaticLayout(onlineStringFinal, currentOnlinePaint, nameWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
nameTop = Utilities.dp(12);
} else {
onlineLayout = null;
nameTop = Utilities.dp(22);
}
if (!Utilities.isRTL) {
avatarLeft = usePadding ? Utilities.dp(11) : 0;
} else {
avatarLeft = width - Utilities.dp(50 + (usePadding ? 11 : 0));
}
avatarImage.imageX = avatarLeft;
avatarImage.imageY = avatarTop;
avatarImage.imageW = Utilities.dp(50);
avatarImage.imageH = Utilities.dp(50);
double widthpx = 0;
float left = 0;
if (Utilities.isRTL) {
if (nameLayout.getLineCount() > 0) {
left = nameLayout.getLineLeft(0);
if (left == 0) {
widthpx = Math.ceil(nameLayout.getLineWidth(0));
if (widthpx < nameWidth) {
nameLeft += (nameWidth - widthpx);
}
}
}
if (onlineLayout != null && onlineLayout.getLineCount() > 0) {
left = onlineLayout.getLineLeft(0);
if (left == 0) {
widthpx = Math.ceil(onlineLayout.getLineWidth(0));
if (widthpx < onlineWidth) {
onlineLeft += (onlineWidth - widthpx);
}
}
}
} else {
if (nameLayout.getLineCount() > 0) {
left = nameLayout.getLineRight(0);
if (left == nameWidth) {
widthpx = Math.ceil(nameLayout.getLineWidth(0));
if (widthpx < nameWidth) {
nameLeft -= (nameWidth - widthpx);
}
}
}
if (onlineLayout != null && onlineLayout.getLineCount() > 0) {
left = onlineLayout.getLineRight(0);
if (left == onlineWidth) {
widthpx = Math.ceil(onlineLayout.getLineWidth(0));
if (widthpx < onlineWidth) {
onlineLeft -= (onlineWidth - widthpx);
}
}
}
}
}
}
}

View file

@ -0,0 +1,684 @@
/*
* This is the source code of Telegram for Android v. 1.3.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.
*/
package org.telegram.ui.Cells;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.TL.TLRPC;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.Emoji;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.R;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
import org.telegram.objects.MessageObject;
import org.telegram.ui.ApplicationLoader;
import org.telegram.ui.Views.ImageReceiver;
import java.lang.ref.WeakReference;
public class DialogCell extends BaseCell {
private static TextPaint namePaint;
private static TextPaint nameEncryptedPaint;
private static TextPaint nameUnknownPaint;
private static TextPaint messagePaint;
private static TextPaint messagePrintingPaint;
private static TextPaint timePaint;
private static TextPaint countPaint;
private static Drawable checkDrawable;
private static Drawable halfCheckDrawable;
private static Drawable clockDrawable;
private static Drawable errorDrawable;
private static Drawable lockDrawable;
private static Drawable countDrawable;
private TLRPC.TL_dialog currentDialog;
private ImageReceiver avatarImage;
private DialogCellLayout cellLayout;
private TLRPC.User user = null;
private TLRPC.Chat chat = null;
private TLRPC.EncryptedChat encryptedChat = null;
private CharSequence lastPrintString = null;
private void init() {
if (namePaint == null) {
namePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
namePaint.setTextSize(Utilities.dp(19));
namePaint.setColor(0xff222222);
namePaint.setTypeface(Utilities.getTypeface("fonts/rmedium.ttf"));
}
if (nameEncryptedPaint == null) {
nameEncryptedPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
nameEncryptedPaint.setTextSize(Utilities.dp(19));
nameEncryptedPaint.setColor(0xff00a60e);
nameEncryptedPaint.setTypeface(Utilities.getTypeface("fonts/rmedium.ttf"));
}
if (nameUnknownPaint == null) {
nameUnknownPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
nameUnknownPaint.setTextSize(Utilities.dp(19));
nameUnknownPaint.setColor(0xff316f9f);
nameUnknownPaint.setTypeface(Utilities.getTypeface("fonts/rmedium.ttf"));
}
if (messagePaint == null) {
messagePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
messagePaint.setTextSize(Utilities.dp(16));
messagePaint.setColor(0xff808080);
}
if (messagePrintingPaint == null) {
messagePrintingPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
messagePrintingPaint.setTextSize(Utilities.dp(16));
messagePrintingPaint.setColor(0xff316f9f);
}
if (timePaint == null) {
timePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
timePaint.setTextSize(Utilities.dp(14));
timePaint.setColor(0xff9e9e9e);
}
if (countPaint == null) {
countPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
countPaint.setTextSize(Utilities.dp(13));
countPaint.setColor(0xffffffff);
}
if (lockDrawable == null) {
lockDrawable = getResources().getDrawable(R.drawable.ic_lock_green);
}
if (checkDrawable == null) {
checkDrawable = getResources().getDrawable(R.drawable.dialogs_check);
}
if (halfCheckDrawable == null) {
halfCheckDrawable = getResources().getDrawable(R.drawable.dialogs_halfcheck);
}
if (clockDrawable == null) {
clockDrawable = getResources().getDrawable(R.drawable.msg_clock);
}
if (errorDrawable == null) {
errorDrawable = getResources().getDrawable(R.drawable.dialogs_warning);
}
if (countDrawable == null) {
countDrawable = getResources().getDrawable(R.drawable.dialogs_badge);
}
if (avatarImage == null) {
avatarImage = new ImageReceiver();
avatarImage.parentView = new WeakReference<View>(this);
}
if (cellLayout == null) {
cellLayout = new DialogCellLayout();
}
}
public DialogCell(Context context) {
super(context);
init();
}
public DialogCell(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public DialogCell(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public void setDialog(TLRPC.TL_dialog dialog) {
currentDialog = dialog;
update(0);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), Utilities.dp(70));
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
if (currentDialog == null) {
super.onLayout(changed, left, top, right, bottom);
return;
}
if (changed) {
buildLayout();
}
}
public void buildLayout() {
cellLayout.build(getMeasuredWidth(), getMeasuredHeight());
}
public void update(int mask) {
if (mask != 0) {
boolean continueUpdate = false;
if ((mask & MessagesController.UPDATE_MASK_USER_PRINT) != 0) {
CharSequence printString = MessagesController.Instance.printingStrings.get(currentDialog.id);
if (lastPrintString != null && printString == null || lastPrintString == null && printString != null || lastPrintString != null && printString != null && !lastPrintString.equals(printString)) {
continueUpdate = true;
}
}
if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0) {
if (chat == null) {
continueUpdate = true;
}
}
if ((mask & MessagesController.UPDATE_MASK_NAME) != 0) {
if (chat == null) {
continueUpdate = true;
}
}
if ((mask & MessagesController.UPDATE_MASK_CHAT_AVATAR) != 0) {
if (user == null) {
continueUpdate = true;
}
}
if ((mask & MessagesController.UPDATE_MASK_CHAT_NAME) != 0) {
if (user == null) {
continueUpdate = true;
}
}
if (!continueUpdate) {
return;
}
}
user = null;
chat = null;
encryptedChat = null;
int lower_id = (int)currentDialog.id;
if (lower_id != 0) {
if (lower_id < 0) {
chat = MessagesController.Instance.chats.get(-lower_id);
} else {
user = MessagesController.Instance.users.get(lower_id);
}
} else {
encryptedChat = MessagesController.Instance.encryptedChats.get((int)(currentDialog.id >> 32));
if (encryptedChat != null) {
user = MessagesController.Instance.users.get(encryptedChat.user_id);
}
}
int placeHolderId = 0;
TLRPC.FileLocation photo = null;
if (user != null) {
if (user.photo != null) {
photo = user.photo.photo_small;
}
placeHolderId = Utilities.getUserAvatarForId(user.id);
} else if (chat != null) {
if (chat.photo != null) {
photo = chat.photo.photo_small;
}
placeHolderId = Utilities.getGroupAvatarForId(chat.id);
}
avatarImage.setImage(photo, "50_50", placeHolderId == 0 ? null : getResources().getDrawable(placeHolderId));
if (getMeasuredWidth() != 0 || getMeasuredHeight() != 0) {
buildLayout();
} else {
requestLayout();
}
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
if (currentDialog == null) {
return;
}
if (cellLayout == null) {
requestLayout();
return;
}
if (cellLayout.drawNameLock) {
setDrawableBounds(lockDrawable, cellLayout.nameLockLeft, cellLayout.nameLockTop);
lockDrawable.draw(canvas);
}
canvas.save();
canvas.translate(cellLayout.nameLeft, cellLayout.nameTop);
cellLayout.nameLayout.draw(canvas);
canvas.restore();
canvas.save();
canvas.translate(cellLayout.timeLeft, cellLayout.timeTop);
cellLayout.timeLayout.draw(canvas);
canvas.restore();
canvas.save();
canvas.translate(cellLayout.messageLeft, cellLayout.messageTop);
cellLayout.messageLayout.draw(canvas);
canvas.restore();
if (cellLayout.drawClock) {
setDrawableBounds(clockDrawable, cellLayout.checkDrawLeft, cellLayout.checkDrawTop);
clockDrawable.draw(canvas);
} else if (cellLayout.drawCheck2) {
if (cellLayout.drawCheck1) {
setDrawableBounds(halfCheckDrawable, cellLayout.halfCheckDrawLeft, cellLayout.checkDrawTop);
halfCheckDrawable.draw(canvas);
setDrawableBounds(checkDrawable, cellLayout.checkDrawLeft, cellLayout.checkDrawTop);
checkDrawable.draw(canvas);
} else {
setDrawableBounds(checkDrawable, cellLayout.checkDrawLeft, cellLayout.checkDrawTop);
checkDrawable.draw(canvas);
}
}
if (cellLayout.drawError) {
setDrawableBounds(errorDrawable, cellLayout.errorLeft, cellLayout.errorTop);
errorDrawable.draw(canvas);
} else if (cellLayout.drawCount) {
setDrawableBounds(countDrawable, cellLayout.countLeft - Utilities.dp(5), cellLayout.countTop, cellLayout.countWidth + Utilities.dp(10), countDrawable.getIntrinsicHeight());
countDrawable.draw(canvas);
canvas.save();
canvas.translate(cellLayout.countLeft, cellLayout.countTop + Utilities.dp(3));
cellLayout.countLayout.draw(canvas);
canvas.restore();
}
avatarImage.draw(canvas, cellLayout.avatarLeft, cellLayout.avatarTop, Utilities.dp(54), Utilities.dp(54));
}
private class DialogCellLayout {
private int nameLeft;
private int nameTop = Utilities.dp(10);
private int nameWidth;
private StaticLayout nameLayout;
private boolean drawNameLock;
private int nameLockLeft;
private int nameLockTop = Utilities.dp(13);
private int timeLeft;
private int timeTop = Utilities.dp(13);
private int timeWidth;
private StaticLayout timeLayout;
private boolean drawCheck1;
private boolean drawCheck2;
private boolean drawClock;
private int checkDrawLeft;
private int checkDrawTop = Utilities.dp(15);
private int halfCheckDrawLeft;
private int messageTop = Utilities.dp(40);
private int messageLeft;
private int messageWidth;
private StaticLayout messageLayout;
private boolean drawError;
private int errorTop = Utilities.dp(37);
private int errorLeft;
private boolean drawCount;
private int countTop = Utilities.dp(37);
private int countLeft;
private int countWidth;
private StaticLayout countLayout;
private int avatarTop = Utilities.dp(8);
private int avatarLeft;
public void build(int width, int height) {
MessageObject message = MessagesController.Instance.dialogMessage.get(currentDialog.top_message);
String nameString = "";
String timeString = "";
String countString = null;
CharSequence messageString = "";
CharSequence printingString = MessagesController.Instance.printingStrings.get(currentDialog.id);
TextPaint currentNamePaint = namePaint;
TextPaint currentMessagePaint = messagePaint;
boolean checkMessage = true;
if (encryptedChat != null) {
drawNameLock = true;
if (!Utilities.isRTL) {
nameLockLeft = Utilities.dp(77);
nameLeft = Utilities.dp(81) + lockDrawable.getIntrinsicWidth();
} else {
nameLockLeft = width - Utilities.dp(77) - lockDrawable.getIntrinsicWidth();
nameLeft = Utilities.dp(14);
}
} else {
drawNameLock = false;
if (!Utilities.isRTL) {
nameLeft = Utilities.dp(77);
} else {
nameLeft = Utilities.dp(14);
}
}
if (message == null) {
if (printingString != null) {
lastPrintString = messageString = printingString;
currentMessagePaint = messagePrintingPaint;
} else {
lastPrintString = null;
if (encryptedChat != null) {
currentMessagePaint = messagePrintingPaint;
if (encryptedChat instanceof TLRPC.TL_encryptedChatRequested) {
messageString = ApplicationLoader.applicationContext.getString(R.string.EncryptionProcessing);
} else if (encryptedChat instanceof TLRPC.TL_encryptedChatWaiting) {
messageString = String.format(ApplicationLoader.applicationContext.getString(R.string.AwaitingEncryption), user.first_name);
} else if (encryptedChat instanceof TLRPC.TL_encryptedChatDiscarded) {
messageString = ApplicationLoader.applicationContext.getString(R.string.EncryptionRejected);
} else if (encryptedChat instanceof TLRPC.TL_encryptedChat) {
if (encryptedChat.admin_id == UserConfig.clientUserId) {
if (user != null) {
messageString = String.format(ApplicationLoader.applicationContext.getString(R.string.EncryptedChatStartedOutgoing), user.first_name);
}
} else {
if (user != null) {
messageString = String.format(ApplicationLoader.applicationContext.getString(R.string.EncryptedChatStartedIncoming), user.first_name);
}
}
}
}
}
if (currentDialog.last_message_date != 0) {
timeString = Utilities.stringForMessageListDate(currentDialog.last_message_date);
}
drawCheck1 = false;
drawCheck2 = false;
drawClock = false;
drawCount = false;
drawError = false;
} else {
TLRPC.User fromUser = MessagesController.Instance.users.get(message.messageOwner.from_id);
if (currentDialog.last_message_date != 0) {
timeString = Utilities.stringForMessageListDate(currentDialog.last_message_date);
} else {
timeString = Utilities.stringForMessageListDate(message.messageOwner.date);
}
if (printingString != null) {
lastPrintString = messageString = printingString;
currentMessagePaint = messagePrintingPaint;
} else {
lastPrintString = null;
if (message.messageOwner instanceof TLRPC.TL_messageService) {
messageString = message.messageText;
currentMessagePaint = messagePrintingPaint;
} else {
if (chat != null) {
String name = "";
if (message.messageOwner.from_id == UserConfig.clientUserId) {
name = ApplicationLoader.applicationContext.getString(R.string.FromYou);
} else {
if (fromUser != null) {
if (fromUser.first_name.length() > 0) {
name = fromUser.first_name;
} else {
name = fromUser.last_name;
}
}
}
if (message.messageOwner.media != null && !(message.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty)) {
messageString = message.messageText;
currentMessagePaint = messagePrintingPaint;
} else {
checkMessage = false;
if (message.messageOwner.message != null) {
messageString = Emoji.replaceEmoji(Html.fromHtml(String.format("<font color=#316f9f>%s:</font> <font color=#808080>%s</font>", name, message.messageOwner.message.replace("\n", " "))));
}
}
} else {
messageString = message.messageText;
if (message.messageOwner.media != null && !(message.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty)) {
currentMessagePaint = messagePrintingPaint;
}
}
}
}
if (currentDialog.unread_count != 0) {
drawCount = true;
countString = String.format("%d", currentDialog.unread_count);
} else {
drawCount = false;
}
if (message.messageOwner.id < 0 && message.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SENT) {
if (MessagesController.Instance.sendingMessages.get(message.messageOwner.id) == null) {
message.messageOwner.send_state = MessagesController.MESSAGE_SEND_STATE_SEND_ERROR;
}
}
if (message.messageOwner.from_id == UserConfig.clientUserId) {
if (message.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENDING) {
drawCheck1 = false;
drawCheck2 = false;
drawClock = true;
drawError = false;
} else if (message.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SEND_ERROR) {
drawCheck1 = false;
drawCheck2 = false;
drawClock = false;
drawError = true;
drawCount = false;
} else if (message.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENT) {
if (!message.messageOwner.unread) {
drawCheck1 = true;
drawCheck2 = true;
} else {
drawCheck1 = false;
drawCheck2 = true;
}
drawClock = false;
drawError = false;
}
} else {
drawCheck1 = false;
drawCheck2 = false;
drawClock = false;
drawError = false;
}
}
timeWidth = (int)Math.ceil(timePaint.measureText(timeString));
timeLayout = new StaticLayout(timeString, timePaint, timeWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
if (!Utilities.isRTL) {
timeLeft = width - Utilities.dp(11) - timeWidth;
} else {
timeLeft = Utilities.dp(11);
}
if (chat != null) {
nameString = chat.title;
} else if (user != null) {
if (user.id != 333000 && ContactsController.Instance.contactsDict.get(user.id) == null) {
if (ContactsController.Instance.contactsDict.size() == 0 && (!ContactsController.Instance.contactsLoaded || ContactsController.Instance.loadingContacts)) {
nameString = Utilities.formatName(user.first_name, user.last_name);
} else {
if (user.phone != null && user.phone.length() != 0) {
nameString = PhoneFormat.Instance.format("+" + user.phone);
} else {
currentNamePaint = nameUnknownPaint;
nameString = Utilities.formatName(user.first_name, user.last_name);
}
}
} else {
nameString = Utilities.formatName(user.first_name, user.last_name);
}
if (encryptedChat != null) {
currentNamePaint = nameEncryptedPaint;
}
}
if (nameString.length() == 0) {
nameString = ApplicationLoader.applicationContext.getString(R.string.HiddenName);
}
if (!Utilities.isRTL) {
nameWidth = width - nameLeft - Utilities.dp(14) - timeWidth;
} else {
nameWidth = width - nameLeft - Utilities.dp(77) - timeWidth;
nameLeft += timeWidth;
}
if (drawNameLock) {
nameWidth -= Utilities.dp(4) + lockDrawable.getIntrinsicWidth();
}
if (drawClock) {
int w = clockDrawable.getIntrinsicWidth() + Utilities.dp(2);
nameWidth -= w;
if (!Utilities.isRTL) {
checkDrawLeft = timeLeft - w;
} else {
checkDrawLeft = timeLeft + timeWidth + Utilities.dp(2);
nameLeft += w;
}
} else if (drawCheck2) {
int w = checkDrawable.getIntrinsicWidth() + Utilities.dp(2);
nameWidth -= w;
if (drawCheck1) {
nameWidth -= halfCheckDrawable.getIntrinsicWidth() - Utilities.dp(5);
if (!Utilities.isRTL) {
halfCheckDrawLeft = timeLeft - w;
checkDrawLeft = halfCheckDrawLeft - Utilities.dp(5);
} else {
checkDrawLeft = timeLeft + timeWidth + Utilities.dp(2);
halfCheckDrawLeft = checkDrawLeft + Utilities.dp(5);
nameLeft += w + halfCheckDrawable.getIntrinsicWidth() - Utilities.dp(5);
}
} else {
if (!Utilities.isRTL) {
checkDrawLeft = timeLeft - w;
} else {
checkDrawLeft = timeLeft + timeWidth + Utilities.dp(2);
nameLeft += w;
}
}
}
CharSequence nameStringFinal = TextUtils.ellipsize(nameString.replace("\n", " "), currentNamePaint, nameWidth - Utilities.dp(12), TextUtils.TruncateAt.END);
nameLayout = new StaticLayout(nameStringFinal, currentNamePaint, nameWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
messageWidth = width - Utilities.dp(88);
if (!Utilities.isRTL) {
messageLeft = Utilities.dp(77);
avatarLeft = Utilities.dp(11);
} else {
messageLeft = Utilities.dp(11);
avatarLeft = width - Utilities.dp(65);
}
avatarImage.imageX = avatarLeft;
avatarImage.imageY = avatarTop;
avatarImage.imageW = Utilities.dp(54);
avatarImage.imageH = Utilities.dp(54);
if (drawError) {
int w = errorDrawable.getIntrinsicWidth() + Utilities.dp(8);
messageWidth -= w;
if (!Utilities.isRTL) {
errorLeft = width - errorDrawable.getIntrinsicWidth() - Utilities.dp(11);
} else {
errorLeft = Utilities.dp(11);
messageLeft += w;
}
} else if (countString != null) {
countWidth = Math.max(Utilities.dp(12), (int)Math.ceil(countPaint.measureText(countString)));
countLayout = new StaticLayout(countString, countPaint, countWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
int w = countWidth + Utilities.dp(18);
messageWidth -= w;
if (!Utilities.isRTL) {
countLeft = width - countWidth - Utilities.dp(16);
} else {
countLeft = Utilities.dp(16);
messageLeft += w;
}
drawCount = true;
} else {
drawCount = false;
}
if (checkMessage) {
if (messageString == null) {
messageString = "";
}
String mess = messageString.toString().replace("\n", " ");
if (mess.length() > 150) {
mess = mess.substring(0, 150);
}
messageString = Emoji.replaceEmoji(mess);
}
CharSequence messageStringFinal = TextUtils.ellipsize(messageString, currentMessagePaint, messageWidth - Utilities.dp(12), TextUtils.TruncateAt.END);
messageLayout = new StaticLayout(messageStringFinal, currentMessagePaint, messageWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
double widthpx = 0;
float left = 0;
if (Utilities.isRTL) {
if (nameLayout.getLineCount() > 0) {
left = nameLayout.getLineLeft(0);
if (left == 0) {
widthpx = Math.ceil(nameLayout.getLineWidth(0));
if (widthpx < nameWidth) {
nameLeft += (nameWidth - widthpx);
}
}
}
if (messageLayout.getLineCount() > 0) {
left = messageLayout.getLineLeft(0);
if (left == 0) {
widthpx = Math.ceil(messageLayout.getLineWidth(0));
if (widthpx < messageWidth) {
messageLeft += (messageWidth - widthpx);
}
}
}
} else {
if (nameLayout.getLineCount() > 0) {
left = nameLayout.getLineRight(0);
if (left == nameWidth) {
widthpx = Math.ceil(nameLayout.getLineWidth(0));
if (widthpx < nameWidth) {
nameLeft -= (nameWidth - widthpx);
}
}
}
if (messageLayout.getLineCount() > 0) {
left = messageLayout.getLineRight(0);
if (left == messageWidth) {
widthpx = Math.ceil(messageLayout.getLineWidth(0));
if (widthpx < messageWidth) {
messageLeft -= (messageWidth - widthpx);
}
}
}
}
}
}
}

View file

@ -16,7 +16,6 @@ import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo; import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.Point; import android.graphics.Point;
import android.graphics.Rect; import android.graphics.Rect;
@ -52,6 +51,7 @@ import android.view.ViewGroup;
import android.view.ViewParent; import android.view.ViewParent;
import android.view.ViewTreeObserver; import android.view.ViewTreeObserver;
import android.view.WindowManager; import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager; import android.view.inputmethod.InputMethodManager;
import android.webkit.MimeTypeMap; import android.webkit.MimeTypeMap;
import android.widget.AbsListView; import android.widget.AbsListView;
@ -61,6 +61,7 @@ import android.widget.EditText;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.ImageButton; import android.widget.ImageButton;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView; import android.widget.ListView;
import android.widget.PopupWindow; import android.widget.PopupWindow;
import android.widget.ProgressBar; import android.widget.ProgressBar;
@ -69,6 +70,7 @@ import android.widget.TextView;
import org.telegram.PhoneFormat.PhoneFormat; import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.TL.TLRPC; import org.telegram.TL.TLRPC;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.FileLog; import org.telegram.messenger.FileLog;
import org.telegram.objects.MessageObject; import org.telegram.objects.MessageObject;
import org.telegram.objects.PhotoObject; import org.telegram.objects.PhotoObject;
@ -125,12 +127,14 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
private Point displaySize = new Point(); private Point displaySize = new Point();
private boolean paused = true; private boolean paused = true;
private boolean readWhenResume = false; private boolean readWhenResume = false;
private boolean sendByEnter = false;
private int readWithDate = 0; private int readWithDate = 0;
private int readWithMid = 0; private int readWithMid = 0;
private boolean swipeOpening = false; private boolean swipeOpening = false;
public boolean scrollToTopOnResume = false; public boolean scrollToTopOnResume = false;
private boolean scrollToTopUnReadOnResume = false; private boolean scrollToTopUnReadOnResume = false;
private boolean isCustomTheme = false; private boolean isCustomTheme = false;
private boolean downloadPhotos = true;
private ImageView topPlaneClose; private ImageView topPlaneClose;
private View pagedownButton; private View pagedownButton;
private TextView topPanelText; private TextView topPanelText;
@ -173,6 +177,8 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
private HashMap<String, ArrayList<ProgressBar>> loadingFile = new HashMap<String, ArrayList<ProgressBar>>(); private HashMap<String, ArrayList<ProgressBar>> loadingFile = new HashMap<String, ArrayList<ProgressBar>>();
private HashMap<Integer, String> progressByTag = new HashMap<Integer, String>(); private HashMap<Integer, String> progressByTag = new HashMap<Integer, String>();
private CharSequence lastPrintString;
ActionMode mActionMode = null; ActionMode mActionMode = null;
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() { private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
@Override @Override
@ -276,7 +282,6 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
NotificationCenter.Instance.addObserver(this, MessagesController.updateInterfaces); NotificationCenter.Instance.addObserver(this, MessagesController.updateInterfaces);
NotificationCenter.Instance.addObserver(this, MessagesController.didReceivedNewMessages); NotificationCenter.Instance.addObserver(this, MessagesController.didReceivedNewMessages);
NotificationCenter.Instance.addObserver(this, MessagesController.closeChats); NotificationCenter.Instance.addObserver(this, MessagesController.closeChats);
NotificationCenter.Instance.addObserver(this, MessagesController.userPrintUpdate);
NotificationCenter.Instance.addObserver(this, MessagesController.messagesReaded); NotificationCenter.Instance.addObserver(this, MessagesController.messagesReaded);
NotificationCenter.Instance.addObserver(this, MessagesController.messagesDeleted); NotificationCenter.Instance.addObserver(this, MessagesController.messagesDeleted);
NotificationCenter.Instance.addObserver(this, MessagesController.messageReceivedByServer); NotificationCenter.Instance.addObserver(this, MessagesController.messageReceivedByServer);
@ -293,11 +298,16 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
NotificationCenter.Instance.addObserver(this, 997); NotificationCenter.Instance.addObserver(this, 997);
loading = true; loading = true;
MessagesController.Instance.loadMessages(dialog_id, 0, 30, 0, true, 0, classGuid, true, false); MessagesController.Instance.loadMessages(dialog_id, 0, 30, 0, true, 0, classGuid, true, false);
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
fontSize = preferences.getInt("fons_size", 16); fontSize = preferences.getInt("fons_size", 16);
sendByEnter = preferences.getBoolean("send_by_enter", false);
if (currentChat != null) {
downloadPhotos = preferences.getBoolean("photo_download_chat", true);
} else {
downloadPhotos = preferences.getBoolean("photo_download_user", true);
}
keyboardHeight = ApplicationLoader.applicationContext.getSharedPreferences("emoji", 0).getInt("kbd_height", Emoji.scale(200.0f));
keyboardHeightLand = ApplicationLoader.applicationContext.getSharedPreferences("emoji", 0).getInt("kbd_height_land3", Emoji.scale(200.0f));
return true; return true;
} }
@ -309,7 +319,6 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
NotificationCenter.Instance.removeObserver(this, MessagesController.updateInterfaces); NotificationCenter.Instance.removeObserver(this, MessagesController.updateInterfaces);
NotificationCenter.Instance.removeObserver(this, MessagesController.didReceivedNewMessages); NotificationCenter.Instance.removeObserver(this, MessagesController.didReceivedNewMessages);
NotificationCenter.Instance.removeObserver(this, MessagesController.closeChats); NotificationCenter.Instance.removeObserver(this, MessagesController.closeChats);
NotificationCenter.Instance.removeObserver(this, MessagesController.userPrintUpdate);
NotificationCenter.Instance.removeObserver(this, MessagesController.messagesReaded); NotificationCenter.Instance.removeObserver(this, MessagesController.messagesReaded);
NotificationCenter.Instance.removeObserver(this, MessagesController.messagesDeleted); NotificationCenter.Instance.removeObserver(this, MessagesController.messagesDeleted);
NotificationCenter.Instance.removeObserver(this, MessagesController.messageReceivedByServer); NotificationCenter.Instance.removeObserver(this, MessagesController.messageReceivedByServer);
@ -377,7 +386,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
ImageView backgroundImage = (ImageView) fragmentView.findViewById(R.id.background_image); ImageView backgroundImage = (ImageView) fragmentView.findViewById(R.id.background_image);
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", 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) {
@ -475,13 +484,13 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
loading = true; loading = true;
} }
} }
if (firstVisibleItem + visibleItemCount >= totalItemCount - 4) { if (firstVisibleItem + visibleItemCount >= totalItemCount - 6) {
if (!unread_end_reached && !loadingForward) { if (!unread_end_reached && !loadingForward) {
MessagesController.Instance.loadMessages(dialog_id, 0, 20, minMessageId, true, minDate, classGuid, false, true); MessagesController.Instance.loadMessages(dialog_id, 0, 20, minMessageId, true, maxDate, classGuid, false, true);
loadingForward = true; loadingForward = true;
} }
} }
if (firstVisibleItem + visibleItemCount == totalItemCount) { if (firstVisibleItem + visibleItemCount == totalItemCount && unread_end_reached) {
showPagedownButton(false, true); showPagedownButton(false, true);
} }
} else { } else {
@ -528,6 +537,25 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
showEmojiPopup(false); showEmojiPopup(false);
} }
return true; return true;
} else if (i == KeyEvent.KEYCODE_ENTER && sendByEnter && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
sendMessage();
return true;
}
return false;
}
});
messsageEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i == EditorInfo.IME_ACTION_SEND) {
sendMessage();
return true;
} else if (sendByEnter) {
if (keyEvent != null && i == EditorInfo.IME_NULL && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
sendMessage();
return true;
}
} }
return false; return false;
} }
@ -536,17 +564,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
sendButton.setOnClickListener(new View.OnClickListener() { sendButton.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
String message = messsageEditText.getText().toString().trim(); sendMessage();
if (processSendingText(message)) {
messsageEditText.setText("");
lastTypingTimeSend = 0;
chatListView.post(new Runnable() {
@Override
public void run() {
chatListView.setSelectionFromTop(messages.size() - 1, -10000 - chatListView.getPaddingTop());
}
});
}
} }
}); });
@ -597,6 +615,9 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
@Override @Override
public void afterTextChanged(Editable editable) { public void afterTextChanged(Editable editable) {
if (sendByEnter && editable.length() > 0 && editable.charAt(editable.length() - 1) == '\n') {
sendMessage();
}
int i = 0; int i = 0;
ImageSpan[] arrayOfImageSpan = editable.getSpans(0, editable.length(), ImageSpan.class); ImageSpan[] arrayOfImageSpan = editable.getSpans(0, editable.length(), ImageSpan.class);
int j = arrayOfImageSpan.length; int j = arrayOfImageSpan.length;
@ -701,6 +722,20 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
return fragmentView; return fragmentView;
} }
private void sendMessage() {
String message = messsageEditText.getText().toString().trim();
if (processSendingText(message)) {
messsageEditText.setText("");
lastTypingTimeSend = 0;
chatListView.post(new Runnable() {
@Override
public void run() {
chatListView.setSelectionFromTop(messages.size() - 1, -10000 - chatListView.getPaddingTop());
}
});
}
}
private void showPagedownButton(boolean show, boolean animated) { private void showPagedownButton(boolean show, boolean animated) {
if (pagedownButton == null) { if (pagedownButton == null) {
return; return;
@ -937,7 +972,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
title.setCompoundDrawablePadding(0); title.setCompoundDrawablePadding(0);
} }
} else if (currentUser != null) { } else if (currentUser != null) {
if (currentUser.id != 333000 && MessagesController.Instance.contactsDict.get(currentUser.id) == null && (MessagesController.Instance.contactsDict.size() != 0 || !MessagesController.Instance.loadingContacts)) { if (currentUser.id != 333000 && ContactsController.Instance.contactsDict.get(currentUser.id) == null && (ContactsController.Instance.contactsDict.size() != 0 || !ContactsController.Instance.loadingContacts)) {
if (currentUser.phone != null && currentUser.phone.length() != 0) { if (currentUser.phone != null && currentUser.phone.length() != 0) {
actionBar.setTitle(PhoneFormat.Instance.format("+" + currentUser.phone)); actionBar.setTitle(PhoneFormat.Instance.format("+" + currentUser.phone));
} else { } else {
@ -960,6 +995,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
CharSequence printString = MessagesController.Instance.printingStrings.get(dialog_id); CharSequence printString = MessagesController.Instance.printingStrings.get(dialog_id);
if (printString == null || printString.length() == 0) { if (printString == null || printString.length() == 0) {
lastPrintString = null;
setTypingAnimation(false); setTypingAnimation(false);
if (currentChat != null) { if (currentChat != null) {
if (currentChat instanceof TLRPC.TL_chatForbidden) { if (currentChat instanceof TLRPC.TL_chatForbidden) {
@ -988,12 +1024,13 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
if (value == 0) { if (value == 0) {
value = currentUser.status.expires; value = currentUser.status.expires;
} }
actionBar.setSubtitle(String.format("%s %s", getStringEntry(R.string.LastSeen), Utilities.formatDateOnline(value))); actionBar.setSubtitle(Utilities.formatDateOnline(value));
} }
} }
} }
} }
} else { } else {
lastPrintString = printString;
actionBar.setSubtitle(printString); actionBar.setSubtitle(printString);
setTypingAnimation(true); setTypingAnimation(true);
} }
@ -1053,7 +1090,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
@Override @Override
public void run() { public void run() {
contentView.setPadding(0, 0, 0, layoutParams.height); contentView.setPadding(0, 0, 0, layoutParams.height);
contentView.forceLayout(); contentView.requestLayout();
} }
}); });
} }
@ -1077,8 +1114,11 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
processSendingPhoto(currentPicturePath); processSendingPhoto(currentPicturePath);
currentPicturePath = null; currentPicturePath = null;
} else if (requestCode == 1) { } else if (requestCode == 1) {
if (data == null) {
return;
}
Uri imageUri = data.getData(); Uri imageUri = data.getData();
if (imageUri == null) { if (imageUri == null || imageUri.getScheme() == null) {
return; return;
} }
String imageFilePath = null; String imageFilePath = null;
@ -1093,14 +1133,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
return; return;
} }
try { try {
Cursor cursor = inflaterActivity.getContentResolver().query(imageUri, new String[]{android.provider.MediaStore.Images.ImageColumns.DATA}, null, null, null); imageFilePath = Utilities.getPath(inflaterActivity, imageUri);
if (cursor == null) {
return;
}
if (cursor.moveToFirst()) {
imageFilePath = cursor.getString(0);
}
cursor.close();
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
} }
@ -1133,13 +1166,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
return; return;
} }
try { try {
Cursor cursor = inflaterActivity.getContentResolver().query(uri, new String[]{android.provider.MediaStore.Images.ImageColumns.DATA}, null, null, null); videoPath = Utilities.getPath(inflaterActivity, uri);
if (cursor == null) {
return;
}
cursor.moveToFirst();
videoPath = cursor.getString(0);
cursor.close();
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
} }
@ -1450,11 +1477,11 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
} }
} else if (id == MessagesController.updateInterfaces) { } else if (id == MessagesController.updateInterfaces) {
int updateMask = (Integer)args[0]; int updateMask = (Integer)args[0];
if ((updateMask & MessagesController.UPDATE_MASK_NAME) != 0 || (updateMask & MessagesController.UPDATE_MASK_STATUS) != 0) { if ((updateMask & MessagesController.UPDATE_MASK_NAME) != 0 || (updateMask & MessagesController.UPDATE_MASK_STATUS) != 0 || (updateMask & MessagesController.UPDATE_MASK_CHAT_NAME) != 0) {
updateSubtitle(); updateSubtitle();
updateOnlineCount(); updateOnlineCount();
} }
if ((updateMask & MessagesController.UPDATE_MASK_AVATAR) != 0) { if ((updateMask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (updateMask & MessagesController.UPDATE_MASK_CHAT_AVATAR) != 0 || (updateMask & MessagesController.UPDATE_MASK_NAME) != 0) {
checkAndUpdateAvatar(); checkAndUpdateAvatar();
if (animationInProgress) { if (animationInProgress) {
invalidateAfterAnimation = true; invalidateAfterAnimation = true;
@ -1464,6 +1491,15 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
} }
} }
} }
if ((updateMask & MessagesController.UPDATE_MASK_USER_PRINT) != 0) {
CharSequence printString = MessagesController.Instance.printingStrings.get(dialog_id);
if (lastPrintString != null && printString == null || lastPrintString == null && printString != null || lastPrintString != null && printString != null && !lastPrintString.equals(printString)) {
updateSubtitle();
}
}
if ((updateMask & MessagesController.UPDATE_MASK_USER_PHONE) != 0) {
updateContactStatus();
}
} else if (id == MessagesController.didReceivedNewMessages) { } else if (id == MessagesController.didReceivedNewMessages) {
long did = (Long)args[0]; long did = (Long)args[0];
if (did == dialog_id) { if (did == dialog_id) {
@ -1505,7 +1541,9 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
readWithDate = currentMaxDate; readWithDate = currentMaxDate;
readWithMid = currentMinMsgId; readWithMid = currentMinMsgId;
} else { } else {
MessagesController.Instance.markDialogAsRead(dialog_id, messages.get(0).messageOwner.id, currentMinMsgId, 0, currentMaxDate, true); if (messages.size() > 0) {
MessagesController.Instance.markDialogAsRead(dialog_id, messages.get(0).messageOwner.id, currentMinMsgId, 0, currentMaxDate, true);
}
} }
} }
updateVisibleRows(); updateVisibleRows();
@ -1613,11 +1651,6 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
Utilities.hideKeyboard(messsageEditText); Utilities.hideKeyboard(messsageEditText);
} }
removeSelfFromStack(); removeSelfFromStack();
} else if (id == MessagesController.userPrintUpdate) {
long uid = (Long)args[0];
if (uid == dialog_id) {
updateSubtitle();
}
} else if (id == MessagesController.messagesReaded) { } else if (id == MessagesController.messagesReaded) {
ArrayList<Integer> markAsReadMessages = (ArrayList<Integer>)args[0]; ArrayList<Integer> markAsReadMessages = (ArrayList<Integer>)args[0];
boolean updated = false; boolean updated = false;
@ -1818,9 +1851,11 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
if (currentUser == null) { if (currentUser == null) {
topPanel.setVisibility(View.GONE); topPanel.setVisibility(View.GONE);
} else { } else {
if (!(currentEncryptedChat instanceof TLRPC.TL_encryptedChat) || currentUser.id == 333000 || (currentUser.phone != null && currentUser.phone.length() != 0 && if (currentEncryptedChat != null && !(currentEncryptedChat instanceof TLRPC.TL_encryptedChat)
MessagesController.Instance.contactsDict.get(currentUser.id) != null && || currentUser.id == 333000
(MessagesController.Instance.contactsDict.size() != 0 || !MessagesController.Instance.loadingContacts))) { || (currentUser.phone != null && currentUser.phone.length() != 0 &&
ContactsController.Instance.contactsDict.get(currentUser.id) != null &&
(ContactsController.Instance.contactsDict.size() != 0 || !ContactsController.Instance.loadingContacts))) {
topPanel.setVisibility(View.GONE); topPanel.setVisibility(View.GONE);
} else { } else {
topPanel.setVisibility(View.VISIBLE); topPanel.setVisibility(View.VISIBLE);
@ -1848,6 +1883,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 (parentActivity == null) {
return;
}
ContactAddActivity fragment = new ContactAddActivity(); ContactAddActivity fragment = new ContactAddActivity();
Bundle args = new Bundle(); Bundle args = new Bundle();
args.putInt("user_id", currentUser.id); args.putInt("user_id", currentUser.id);
@ -2013,7 +2051,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
((ApplicationActivity)parentActivity).showActionBar(); ((ApplicationActivity)parentActivity).showActionBar();
((ApplicationActivity)parentActivity).updateActionBar(); ((ApplicationActivity)parentActivity).updateActionBar();
fixLayout(); fixLayout();
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", 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) {
SharedPreferences.Editor editor = preferences.edit(); SharedPreferences.Editor editor = preferences.edit();
@ -2021,6 +2059,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
editor.commit(); editor.commit();
ignoreTextChange = true; ignoreTextChange = true;
messsageEditText.setText(lastMessageText); messsageEditText.setText(lastMessageText);
messsageEditText.setSelection(messsageEditText.getText().length());
ignoreTextChange = false; ignoreTextChange = false;
} }
if (messsageEditText != null) { if (messsageEditText != null) {
@ -2074,14 +2113,11 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
MessagesController.Instance.openned_dialog_id = 0; MessagesController.Instance.openned_dialog_id = 0;
if (messsageEditText != null && messsageEditText.length() != 0) { if (messsageEditText != null && messsageEditText.length() != 0) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit(); SharedPreferences.Editor editor = preferences.edit();
editor.putString("dialog_" + dialog_id, messsageEditText.getText().toString()); editor.putString("dialog_" + dialog_id, messsageEditText.getText().toString());
editor.commit(); editor.commit();
} }
if (messsageEditText != null) {
messsageEditText.clearFocus();
}
} }
private void fixLayout() { private void fixLayout() {
@ -2386,6 +2422,9 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
} }
} else if (option == 2) { } else if (option == 2) {
if (selectedObject != null) { if (selectedObject != null) {
if (parentActivity == null) {
return;
}
forwaringMessage = selectedObject; forwaringMessage = selectedObject;
selectedObject = null; selectedObject = null;
@ -2447,6 +2486,10 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
if (did != dialog_id) { if (did != dialog_id) {
int lower_part = (int)did; int lower_part = (int)did;
if (lower_part != 0) { if (lower_part != 0) {
ActionBarActivity inflaterActivity = parentActivity;
if (inflaterActivity == null) {
inflaterActivity = (ActionBarActivity)getActivity();
}
activity.removeSelfFromStack(); activity.removeSelfFromStack();
ChatActivity fragment = new ChatActivity(); ChatActivity fragment = new ChatActivity();
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
@ -2455,22 +2498,30 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
fragment.setArguments(bundle); fragment.setArguments(bundle);
fragment.scrollToTopOnResume = true; fragment.scrollToTopOnResume = true;
ActionBarActivity act = (ActionBarActivity)getActivity(); ActionBarActivity act = (ActionBarActivity)getActivity();
((ApplicationActivity)parentActivity).presentFragment(fragment, "chat" + Math.random(), false); if (inflaterActivity != null) {
((ApplicationActivity)inflaterActivity).presentFragment(fragment, "chat" + Math.random(), false);
}
} else if (lower_part < 0) { } else if (lower_part < 0) {
bundle.putInt("chat_id", -lower_part); bundle.putInt("chat_id", -lower_part);
fragment.setArguments(bundle); fragment.setArguments(bundle);
fragment.scrollToTopOnResume = true; fragment.scrollToTopOnResume = true;
((ApplicationActivity)parentActivity).presentFragment(fragment, "chat" + Math.random(), false); if (inflaterActivity != null) {
((ApplicationActivity)inflaterActivity).presentFragment(fragment, "chat" + Math.random(), false);
}
} }
removeSelfFromStack(); removeSelfFromStack();
if (forwaringMessage != null) { if (forwaringMessage != null) {
MessagesController.Instance.sendMessage(forwaringMessage, did); if (forwaringMessage.messageOwner.id > 0) {
MessagesController.Instance.sendMessage(forwaringMessage, did);
}
forwaringMessage = null; forwaringMessage = null;
} else { } else {
ArrayList<Integer> ids = new ArrayList<Integer>(selectedMessagesIds.keySet()); ArrayList<Integer> ids = new ArrayList<Integer>(selectedMessagesIds.keySet());
Collections.sort(ids); Collections.sort(ids);
for (Integer id : ids) { for (Integer id : ids) {
MessagesController.Instance.sendMessage(selectedMessagesIds.get(id), did); if (id > 0) {
MessagesController.Instance.sendMessage(selectedMessagesIds.get(id), did);
}
} }
selectedMessagesIds.clear(); selectedMessagesIds.clear();
} }
@ -2547,14 +2598,14 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
Intent pickIntent = new Intent(); Intent pickIntent = new Intent();
pickIntent.setType("video/*"); pickIntent.setType("video/*");
pickIntent.setAction(Intent.ACTION_GET_CONTENT); pickIntent.setAction(Intent.ACTION_GET_CONTENT);
pickIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 1024 * 1024 * 1000); pickIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, (long)(1024 * 1024 * 1000));
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
File video = Utilities.generateVideoPath(); File video = Utilities.generateVideoPath();
if (video != null) { if (video != null) {
if(android.os.Build.VERSION.SDK_INT > 10) { if(android.os.Build.VERSION.SDK_INT > 16) {
takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(video)); takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(video));
} }
takeVideoIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 1024 * 1024 * 1000); takeVideoIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, (long)(1024 * 1024 * 1000));
currentPicturePath = video.getAbsolutePath(); currentPicturePath = video.getAbsolutePath();
} }
Intent chooserIntent = Intent.createChooser(pickIntent, ""); Intent chooserIntent = Intent.createChooser(pickIntent, "");
@ -2906,7 +2957,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
ChatListRowHolderEx holder = (ChatListRowHolderEx)view.getTag(); ChatListRowHolderEx holder = (ChatListRowHolderEx)view.getTag();
if (holder == null) { if (holder == null) {
holder = new ChatListRowHolderEx(view); holder = new ChatListRowHolderEx(view, type);
view.setTag(holder); view.setTag(holder);
} }
holder.message = message; holder.message = message;
@ -3069,11 +3120,17 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
public ImageView addContactButton; public ImageView addContactButton;
public View addContactView; public View addContactView;
public View chatBubbleView; public View chatBubbleView;
public View photoProgressView;
public ProgressBar actionProgress; public ProgressBar actionProgress;
public View actionView; public View actionView;
public ImageView actionCancelButton; public ImageView actionCancelButton;
private PhotoObject photoObjectToSet = null;
private File photoFile = null;
private String photoFileName = null;
private String photoFilter = null;
public void update() { public void update() {
TLRPC.User fromUser = MessagesController.Instance.users.get(message.messageOwner.from_id); TLRPC.User fromUser = MessagesController.Instance.users.get(message.messageOwner.from_id);
@ -3115,24 +3172,38 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
forwardedUserText.setText(Html.fromHtml(getStringEntry(R.string.From) + " <b>" + Utilities.formatName(fwdUser.first_name, fwdUser.last_name) + "</b>")); forwardedUserText.setText(Html.fromHtml(getStringEntry(R.string.From) + " <b>" + Utilities.formatName(fwdUser.first_name, fwdUser.last_name) + "</b>"));
} }
} else if (type == 2 || type == 3 || type == 6 || type == 7) { } else if (type == 2 || type == 3 || type == 6 || type == 7) {
int width = (int)(Math.min(displaySize.x, displaySize.y) / 2.5f); int width = (int)(Math.min(displaySize.x, displaySize.y) * 0.7f);
PhotoObject photo = PhotoObject.getClosestImageWithSize(message.photoThumbs, width, width + 100); int height = width + Utilities.dp(100);
if (type == 6 || type == 7) {
width = (int)(Math.min(displaySize.x, displaySize.y) / 2.5f);
height = width + 100;
}
if (width > 800) {
width = 800;
}
if (height > 800) {
height = 800;
}
PhotoObject photo = PhotoObject.getClosestImageWithSize(message.photoThumbs, width, height);
if (type == 3) {
if (photoProgressView != null) {
photoProgressView.setVisibility(View.GONE);
}
}
if (photo != null) { if (photo != null) {
float scale = (float)photo.photoOwner.w / (float)width; float scale = (float)photo.photoOwner.w / (float)width;
if (scale < 1 && photo.photoOwner.w * scale < Utilities.dp(100)) {
scale = photo.photoOwner.w / Utilities.dp(100);
}
int w = (int)(photo.photoOwner.w / scale); int w = (int)(photo.photoOwner.w / scale);
int h = (int)(photo.photoOwner.h / scale); int h = (int)(photo.photoOwner.h / scale);
if (h > Utilities.dp(160)) { if (h > height) {
float scale2 = h; float scale2 = h;
h = Utilities.dp(160); h = height;
scale2 /= h; scale2 /= h;
w = (int)(w / scale2); w = (int)(w / scale2);
} else if (h < Utilities.dp(90)) { } else if (h < Utilities.dp(120)) {
h = Utilities.dp(90); h = Utilities.dp(120);
float hScale = (float)photo.photoOwner.h / h; float hScale = (float)photo.photoOwner.h / h;
if (photo.photoOwner.w / hScale < width) { if (photo.photoOwner.w / hScale < width) {
w = (int)(photo.photoOwner.w / hScale); w = (int)(photo.photoOwner.w / hScale);
@ -3144,13 +3215,46 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
params.height = h; params.height = h;
photoImage.setLayoutParams(params); photoImage.setLayoutParams(params);
LinearLayout.LayoutParams params2 = (LinearLayout.LayoutParams)chatBubbleView.getLayoutParams();
params2.width = w + Utilities.dp(12);
params2.height = h + Utilities.dp(12);
chatBubbleView.setLayoutParams(params2);
if (photo.image != null) { if (photo.image != null) {
photoImage.setImageBitmap(photo.image); photoImage.setImageBitmap(photo.image);
} else { } else {
if (message.imagePreview != null) { if (type == 2 || type == 3) {
photoImage.setImage(photo.photoOwner.location, String.format(Locale.US, "%d_%d", (int)(w / Utilities.density), (int)(h / Utilities.density)), message.imagePreview); String fileName = MessageObject.getAttachFileName(photo.photoOwner);
File cacheFile = new File(Utilities.getCacheDir(), fileName);
if (!cacheFile.exists()) {
photoFileName = fileName;
photoFile = cacheFile;
} else {
photoFileName = null;
photoFile = null;
}
}
if (photoFileName == null) {
if (message.imagePreview != null) {
photoImage.setImage(photo.photoOwner.location, String.format(Locale.US, "%d_%d", (int)(w / Utilities.density), (int)(h / Utilities.density)), message.imagePreview);
} else {
photoImage.setImage(photo.photoOwner.location, String.format(Locale.US, "%d_%d", (int)(w / Utilities.density), (int)(h / Utilities.density)), message.messageOwner.out ? R.drawable.photo_placeholder_out : R.drawable.photo_placeholder_in);
}
} else { } else {
photoImage.setImage(photo.photoOwner.location, String.format(Locale.US, "%d_%d", (int)(w / Utilities.density), (int)(h / Utilities.density)), message.messageOwner.out ? R.drawable.photo_placeholder_out : R.drawable.photo_placeholder_in); if (downloadPhotos) {
addToLoadingFile(photoFileName, actionProgress);
if (message.imagePreview != null) {
photoImage.setImage(photo.photoOwner.location, String.format(Locale.US, "%d_%d", (int)(w / Utilities.density), (int)(h / Utilities.density)), message.imagePreview, photo.photoOwner.size);
} else {
photoImage.setImage(photo.photoOwner.location, String.format(Locale.US, "%d_%d", (int)(w / Utilities.density), (int)(h / Utilities.density)), message.messageOwner.out ? R.drawable.photo_placeholder_out : R.drawable.photo_placeholder_in, photo.photoOwner.size);
}
photoObjectToSet = null;
photoFilter = null;
} else {
photoFilter = String.format(Locale.US, "%d_%d", (int)(w / Utilities.density), (int)(h / Utilities.density));
photoObjectToSet = photo;
photoImage.setImageBitmap(message.imagePreview);
}
} }
} }
} }
@ -3203,7 +3307,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 && MessagesController.Instance.contactsDict.get(contactUser.id) == null) { if (contactUser.id != UserConfig.clientUserId && ContactsController.Instance.contactsDict.get(contactUser.id) == null) {
addContactView.setVisibility(View.VISIBLE); addContactView.setVisibility(View.VISIBLE);
} else { } else {
addContactView.setVisibility(View.GONE); addContactView.setVisibility(View.GONE);
@ -3289,8 +3393,13 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
halfCheckImage.setImageResource(R.drawable.msg_clock); halfCheckImage.setImageResource(R.drawable.msg_clock);
} }
halfCheckImage.setVisibility(View.VISIBLE); halfCheckImage.setVisibility(View.VISIBLE);
if (actionView != null) { if (actionView != null || photoProgressView != null) {
actionView.setVisibility(View.VISIBLE); if (actionView != null) {
actionView.setVisibility(View.VISIBLE);
}
if (photoProgressView != null) {
photoProgressView.setVisibility(View.VISIBLE);
}
Float progress = FileLoader.Instance.fileProgresses.get(message.messageOwner.attachPath); Float progress = FileLoader.Instance.fileProgresses.get(message.messageOwner.attachPath);
if (progress != null) { if (progress != null) {
actionProgress.setProgress((int)(progress * 100)); actionProgress.setProgress((int)(progress * 100));
@ -3312,6 +3421,9 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
if (actionView != null) { if (actionView != null) {
actionView.setVisibility(View.GONE); actionView.setVisibility(View.GONE);
} }
if (photoProgressView != null) {
photoProgressView.setVisibility(View.GONE);
}
if (actionAttachButton != null) { if (actionAttachButton != null) {
actionAttachButton.setVisibility(View.GONE); actionAttachButton.setVisibility(View.GONE);
} }
@ -3336,13 +3448,16 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
if (actionView != null) { if (actionView != null) {
actionView.setVisibility(View.GONE); actionView.setVisibility(View.GONE);
} }
if (photoProgressView != null) {
photoProgressView.setVisibility(View.GONE);
}
if (actionAttachButton != null) { if (actionAttachButton != null) {
actionAttachButton.setVisibility(View.VISIBLE); actionAttachButton.setVisibility(View.VISIBLE);
} }
} }
} }
} }
if (message.type == 6 || message.type == 7 || message.type == 16 || message.type == 17) { if (message.type == 2 || message.type == 3 || message.type == 6 || message.type == 7 || message.type == 16 || message.type == 17) {
Integer tag = (Integer)actionProgress.getTag(); Integer tag = (Integer)actionProgress.getTag();
String file = progressByTag.get(tag); String file = progressByTag.get(tag);
if (file != null) { if (file != null) {
@ -3352,30 +3467,49 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
if (file != null) { if (file != null) {
progressBarMap.remove(file); progressBarMap.remove(file);
} }
String fileName = message.getFileName(); String fileName = null;
if (photoFileName != null) {
fileName = photoFileName;
} else {
fileName = message.getFileName();
}
boolean load = false; boolean load = false;
if (message.messageOwner.attachPath != null && message.messageOwner.attachPath.length() != 0) { if (message.type != 2 && message.type != 3 && message.messageOwner.attachPath != null && message.messageOwner.attachPath.length() != 0) {
File f = new File(message.messageOwner.attachPath); File f = new File(message.messageOwner.attachPath);
if (f.exists()) { if (f.exists()) {
actionAttachButton.setVisibility(View.VISIBLE); if (actionAttachButton != null) {
actionView.setVisibility(View.GONE); actionAttachButton.setVisibility(View.VISIBLE);
if (message.type == 6 || message.type == 7) { if (message.type == 6 || message.type == 7) {
actionAttachButton.setText(getStringEntry(R.string.ViewVideo)); actionAttachButton.setText(getStringEntry(R.string.ViewVideo));
} else if (message.type == 16 || message.type == 17) { } else if (message.type == 16 || message.type == 17) {
actionAttachButton.setText(getStringEntry(R.string.Open)); actionAttachButton.setText(getStringEntry(R.string.Open));
}
}
if (actionView != null) {
actionView.setVisibility(View.GONE);
}
if (photoProgressView != null) {
photoProgressView.setVisibility(View.GONE);
} }
} else { } else {
load = true; load = true;
} }
} else { } else {
File cacheFile = new File(Utilities.getCacheDir(), fileName); File cacheFile = null;
if (cacheFile.exists()) { if (((message.type == 2 || message.type == 3) && photoFileName == null) || (cacheFile = new File(Utilities.getCacheDir(), fileName)).exists()) {
actionAttachButton.setVisibility(View.VISIBLE); if (actionAttachButton != null) {
actionView.setVisibility(View.GONE); actionAttachButton.setVisibility(View.VISIBLE);
if (message.type == 6 || message.type == 7) { if (message.type == 6 || message.type == 7) {
actionAttachButton.setText(getStringEntry(R.string.ViewVideo)); actionAttachButton.setText(getStringEntry(R.string.ViewVideo));
} else if (message.type == 16 || message.type == 17) { } else if (message.type == 16 || message.type == 17) {
actionAttachButton.setText(getStringEntry(R.string.Open)); actionAttachButton.setText(getStringEntry(R.string.Open));
}
}
if (actionView != null) {
actionView.setVisibility(View.GONE);
}
if (photoProgressView != null) {
photoProgressView.setVisibility(View.GONE);
} }
} else { } else {
load = true; load = true;
@ -3391,41 +3525,67 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
} }
progressByTag.put((Integer)actionProgress.getTag(), fileName); progressByTag.put((Integer)actionProgress.getTag(), fileName);
addToLoadingFile(fileName, actionProgress); addToLoadingFile(fileName, actionProgress);
actionView.setVisibility(View.VISIBLE); if (actionView != null) {
actionAttachButton.setVisibility(View.GONE); if ((message.type == 2 || message.type == 3) && downloadPhotos) {
actionView.setVisibility(View.GONE);
} else {
actionView.setVisibility(View.VISIBLE);
if (photoFileName != null) {
actionCancelButton.setImageResource(R.drawable.photo_download_cancel_states);
}
}
}
if (photoProgressView != null) {
photoProgressView.setVisibility(View.VISIBLE);
}
if (actionAttachButton != null) {
actionAttachButton.setVisibility(View.GONE);
}
} else { } else {
actionView.setVisibility(View.GONE); if (actionView != null) {
actionAttachButton.setVisibility(View.VISIBLE); if ((message.type == 2 || message.type == 3) && !downloadPhotos) {
if (message.type == 6 || message.type == 7) { actionView.setVisibility(View.VISIBLE);
actionAttachButton.setText(String.format("%s %.1f MB", getStringEntry(R.string.DOWNLOAD), message.messageOwner.media.video.size / 1024.0f / 1024.0f)); actionCancelButton.setImageResource(R.drawable.photo_download_states);
} else if (message.type == 16 || message.type == 17) { } else {
actionAttachButton.setText(getStringEntry(R.string.DOWNLOAD)); actionView.setVisibility(View.GONE);
}
}
if (photoProgressView != null) {
photoProgressView.setVisibility(View.GONE);
}
if (actionAttachButton != null) {
actionAttachButton.setVisibility(View.VISIBLE);
if (message.type == 6 || message.type == 7) {
actionAttachButton.setText(String.format("%s %.1f MB", getStringEntry(R.string.DOWNLOAD), message.messageOwner.media.video.size / 1024.0f / 1024.0f));
} else if (message.type == 16 || message.type == 17) {
actionAttachButton.setText(getStringEntry(R.string.DOWNLOAD));
}
} }
} }
} }
} }
} if (message.type == 16 || message.type == 17) {
if (message.type == 16 || message.type == 17) { int width;
int width; if (currentChat != null && type != 16) {
if (currentChat != null && type != 16) { if (actionView.getVisibility() == View.VISIBLE) {
if (actionView.getVisibility() == View.VISIBLE) { width = displaySize.x - Utilities.dp(290);
width = displaySize.x - Utilities.dp(290); } else {
width = displaySize.x - Utilities.dp(270);
}
} else { } else {
width = displaySize.x - Utilities.dp(270); if (actionView.getVisibility() == View.VISIBLE) {
} width = displaySize.x - Utilities.dp(240);
} else { } else {
if (actionView.getVisibility() == View.VISIBLE) { width = displaySize.x - Utilities.dp(220);
width = displaySize.x - Utilities.dp(240); }
} else {
width = displaySize.x - Utilities.dp(220);
} }
nameTextView.setMaxWidth(width);
phoneTextView.setMaxWidth(width);
} }
nameTextView.setMaxWidth(width);
phoneTextView.setMaxWidth(width);
} }
} }
public ChatListRowHolderEx(View view) { public ChatListRowHolderEx(View view, int type) {
avatarImageView = (BackupImageView)view.findViewById(R.id.chat_group_avatar_image); avatarImageView = (BackupImageView)view.findViewById(R.id.chat_group_avatar_image);
nameTextView = (TextView)view.findViewById(R.id.chat_user_group_name); nameTextView = (TextView)view.findViewById(R.id.chat_user_group_name);
messageLayout = (MessageLayout)view.findViewById(R.id.message_layout); messageLayout = (MessageLayout)view.findViewById(R.id.message_layout);
@ -3448,6 +3608,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
addContactButton = (ImageView)view.findViewById(R.id.add_contact_button); addContactButton = (ImageView)view.findViewById(R.id.add_contact_button);
addContactView = view.findViewById(R.id.add_contact_view); addContactView = view.findViewById(R.id.add_contact_view);
chatBubbleView = view.findViewById(R.id.chat_bubble_layout); chatBubbleView = view.findViewById(R.id.chat_bubble_layout);
photoProgressView = view.findViewById(R.id.photo_progress);
if (messageTextView != null) { if (messageTextView != null) {
messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize); messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
} }
@ -3457,11 +3618,13 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
progressTag++; progressTag++;
} }
if (actionView != null) { if (type != 2 && type != 3) {
if (isCustomTheme) { if (actionView != null) {
actionView.setBackgroundResource(R.drawable.system_black); if (isCustomTheme) {
} else { actionView.setBackgroundResource(R.drawable.system_black);
actionView.setBackgroundResource(R.drawable.system_blue); } else {
actionView.setBackgroundResource(R.drawable.system_blue);
}
} }
} }
@ -3581,6 +3744,22 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
} }
updateVisibleRows(); updateVisibleRows();
} }
} else if (message.type == 2 || message.type == 3) {
if (photoFile != null && !photoFile.exists() && photoObjectToSet != null) {
if (loadingFile.containsKey(photoFileName)) {
loadingFile.remove(photoFileName);
FileLoader.Instance.cancelLoadingForImageView(photoImage);
updateVisibleRows();
} else {
addToLoadingFile(photoFileName, actionProgress);
if (message.imagePreview != null) {
photoImage.setImage(photoObjectToSet.photoOwner.location, photoFilter, message.imagePreview, photoObjectToSet.photoOwner.size);
} else {
photoImage.setImage(photoObjectToSet.photoOwner.location, photoFilter, message.messageOwner.out ? R.drawable.photo_placeholder_out : R.drawable.photo_placeholder_in, photoObjectToSet.photoOwner.size);
}
updateVisibleRows();
}
}
} }
} }
} }
@ -3621,6 +3800,26 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
} }
} }
private void alertUserOpenError() {
AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
builder.setTitle(R.string.AppName);
builder.setPositiveButton(R.string.OK, null);
if (message.type == 6 || message.type == 7) {
builder.setMessage(R.string.NoPlayerInstalled);
} else {
builder.setMessage(String.format(getStringEntry(R.string.NoHandleAppInstalled), message.messageOwner.media.document.mime_type));
}
visibleDialog = builder.show();
visibleDialog.setCanceledOnTouchOutside(true);
visibleDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
visibleDialog = null;
}
});
}
private void processOnClick(View view) { private void processOnClick(View view) {
if (mActionMode != null) { if (mActionMode != null) {
processRowSelect(view); processRowSelect(view);
@ -3635,9 +3834,19 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
LocationActivity fragment = new LocationActivity(); LocationActivity fragment = new LocationActivity();
((ApplicationActivity)parentActivity).presentFragment(fragment, "location_view", false); ((ApplicationActivity)parentActivity).presentFragment(fragment, "location_view", false);
} else if (message.type == 2 || message.type == 3) { } else if (message.type == 2 || message.type == 3) {
NotificationCenter.Instance.addToMemCache(51, message); if (photoFile == null || photoObjectToSet == null || photoFile != null && photoFile.exists()) {
Intent intent = new Intent(parentActivity, GalleryImageViewer.class); NotificationCenter.Instance.addToMemCache(51, message);
startActivity(intent); Intent intent = new Intent(parentActivity, GalleryImageViewer.class);
startActivity(intent);
} else {
addToLoadingFile(photoFileName, actionProgress);
if (message.imagePreview != null) {
photoImage.setImage(photoObjectToSet.photoOwner.location, photoFilter, message.imagePreview, photoObjectToSet.photoOwner.size);
} else {
photoImage.setImage(photoObjectToSet.photoOwner.location, photoFilter, message.messageOwner.out ? R.drawable.photo_placeholder_out : R.drawable.photo_placeholder_in, photoObjectToSet.photoOwner.size);
}
updateVisibleRows();
}
} else if (message.type == 11) { } else if (message.type == 11) {
NotificationCenter.Instance.addToMemCache(51, message); NotificationCenter.Instance.addToMemCache(51, message);
Intent intent = new Intent(parentActivity, GalleryImageViewer.class); Intent intent = new Intent(parentActivity, GalleryImageViewer.class);
@ -3651,6 +3860,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
f = new File(Utilities.getCacheDir(), fileName); f = new File(Utilities.getCacheDir(), fileName);
} }
if (f != null && f.exists()) { if (f != null && f.exists()) {
String realMimeType = null;
try { try {
Intent intent = new Intent(Intent.ACTION_VIEW); Intent intent = new Intent(Intent.ACTION_VIEW);
if (message.type == 6 || message.type == 7) { if (message.type == 6 || message.type == 7) {
@ -3660,9 +3870,9 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
int idx = fileName.lastIndexOf("."); int idx = fileName.lastIndexOf(".");
if (idx != -1) { if (idx != -1) {
String ext = fileName.substring(idx + 1); String ext = fileName.substring(idx + 1);
String mimeType = myMime.getMimeTypeFromExtension(ext.toLowerCase()); realMimeType = myMime.getMimeTypeFromExtension(ext.toLowerCase());
if (mimeType != null) { if (realMimeType != null) {
intent.setDataAndType(Uri.fromFile(f), mimeType); intent.setDataAndType(Uri.fromFile(f), realMimeType);
} else { } else {
intent.setDataAndType(Uri.fromFile(f), "text/plain"); intent.setDataAndType(Uri.fromFile(f), "text/plain");
} }
@ -3670,25 +3880,18 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
intent.setDataAndType(Uri.fromFile(f), "text/plain"); intent.setDataAndType(Uri.fromFile(f), "text/plain");
} }
} }
startActivity(intent); if (realMimeType != null) {
} catch (Exception e) { try {
AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity); startActivity(intent);
builder.setTitle(R.string.AppName); } catch (Exception e) {
builder.setPositiveButton(R.string.OK, null); intent.setDataAndType(Uri.fromFile(f), "text/plain");
if (message.type == 6 || message.type == 7) { startActivity(intent);
builder.setMessage(R.string.NoPlayerInstalled);
} else {
builder.setMessage(String.format(getStringEntry(R.string.NoHandleAppInstalled), message.messageOwner.media.document.mime_type));
}
visibleDialog = builder.show();
visibleDialog.setCanceledOnTouchOutside(true);
visibleDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
visibleDialog = null;
} }
}); } else {
startActivity(intent);
}
} catch (Exception e) {
alertUserOpenError();
} }
} else { } else {
if (message.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SEND_ERROR && message.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SENDING || !message.messageOwner.out) { if (message.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SEND_ERROR && message.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SENDING || !message.messageOwner.out) {

View file

@ -44,6 +44,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.Cells.ChatOrUserCell;
import org.telegram.ui.Views.AvatarUpdater; import org.telegram.ui.Views.AvatarUpdater;
import org.telegram.ui.Views.BackupImageView; import org.telegram.ui.Views.BackupImageView;
import org.telegram.ui.Views.BaseFragment; import org.telegram.ui.Views.BaseFragment;
@ -239,8 +240,8 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
} }
@Override @Override
public void didSelectContact(int user_id) { public void didSelectContact(TLRPC.User user) {
MessagesController.Instance.addUserToChat(chat_id, user_id, info); MessagesController.Instance.addUserToChat(chat_id, user, info);
} }
@Override @Override
@ -277,9 +278,12 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
public void didReceivedNotification(int id, Object... args) { public void didReceivedNotification(int id, Object... args) {
if (id == MessagesController.updateInterfaces) { if (id == MessagesController.updateInterfaces) {
updateOnlineCount(); int mask = (Integer)args[0];
if (listView != null) { if ((mask & MessagesController.UPDATE_MASK_CHAT_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_CHAT_NAME) != 0 || (mask & MessagesController.UPDATE_MASK_CHAT_MEMBERS) != 0) {
listView.invalidateViews(); updateOnlineCount();
}
if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0 || (mask & MessagesController.UPDATE_MASK_STATUS) != 0) {
updateVisibleRows(mask);
} }
} else if (id == MessagesController.chatInfoDidLoaded) { } else if (id == MessagesController.chatInfoDidLoaded) {
int chatId = (Integer)args[0]; int chatId = (Integer)args[0];
@ -355,6 +359,19 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
return true; return true;
} }
private void updateVisibleRows(int mask) {
if (listView == null) {
return;
}
int count = listView.getChildCount();
for (int a = 0; a < count; a++) {
View child = listView.getChildAt(a);
if (child instanceof ChatOrUserCell) {
((ChatOrUserCell) child).update(mask);
}
}
}
private void updateOnlineCount() { private void updateOnlineCount() {
if (info == null) { if (info == null) {
return; return;
@ -451,11 +468,11 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
private void kickUser(TLRPC.TL_chatParticipant user) { private void kickUser(TLRPC.TL_chatParticipant user) {
if (user != null) { if (user != null) {
MessagesController.Instance.deleteUserFromChat(chat_id, user.user_id, info); MessagesController.Instance.deleteUserFromChat(chat_id, MessagesController.Instance.users.get(user.user_id), info);
} else { } else {
NotificationCenter.Instance.removeObserver(this, MessagesController.closeChats); NotificationCenter.Instance.removeObserver(this, MessagesController.closeChats);
NotificationCenter.Instance.postNotificationName(MessagesController.closeChats); NotificationCenter.Instance.postNotificationName(MessagesController.closeChats);
MessagesController.Instance.deleteUserFromChat(chat_id, UserConfig.clientUserId, info); MessagesController.Instance.deleteUserFromChat(chat_id, MessagesController.Instance.users.get(UserConfig.clientUserId), info);
MessagesController.Instance.deleteDialog(-chat_id, 0, false); MessagesController.Instance.deleteDialog(-chat_id, 0, false);
finishFragment(); finishFragment();
} }
@ -674,60 +691,19 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
TLRPC.User user = MessagesController.Instance.users.get(part.user_id); TLRPC.User user = MessagesController.Instance.users.get(part.user_id);
if (view == null) { if (view == null) {
LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = new ChatOrUserCell(mContext);
view = li.inflate(R.layout.messages_search_user_layout, viewGroup, false); ((ChatOrUserCell)view).useBoldFont = true;
} ((ChatOrUserCell)view).usePadding = false;
ContactsActivity.ContactListRowHolder holder = (ContactsActivity.ContactListRowHolder)view.getTag(); ((ChatOrUserCell)view).useSeparator = true;
if (holder == null) {
holder = new ContactsActivity.ContactListRowHolder(view);
view.setTag(holder);
} }
View divider = view.findViewById(R.id.settings_row_divider); ((ChatOrUserCell)view).setData(user, null, null, null, null);
divider.setVisibility(View.VISIBLE);
if (user.first_name.length() != 0 && user.last_name.length() != 0) {
holder.nameTextView.setText(Html.fromHtml(user.first_name + " <b>" + user.last_name + "</b>"));
} else if (user.first_name.length() != 0) {
holder.nameTextView.setText(Html.fromHtml("<b>" + user.first_name + "</b>"));
} else {
holder.nameTextView.setText(Html.fromHtml("<b>" + user.last_name + "</b>"));
}
// if (info.admin_id != UserConfig.clientUserId && part.inviter_id != UserConfig.clientUserId && part.user_id != UserConfig.clientUserId) { // if (info.admin_id != UserConfig.clientUserId && part.inviter_id != UserConfig.clientUserId && part.user_id != UserConfig.clientUserId) {
// //
// } else { // } else {
// //
// } // }
TLRPC.FileLocation photo = null;
if (user.photo != null) {
photo = user.photo.photo_small;
}
int placeHolderId = Utilities.getUserAvatarForId(user.id);
holder.avatarImage.setImage(photo, "50_50", placeHolderId);
if (user.status == null) {
holder.messageTextView.setTextColor(0xff808080);
holder.messageTextView.setText(getStringEntry(R.string.Offline));
} else {
int currentTime = ConnectionsManager.Instance.getCurrentTime();
if ((user.status.expires > currentTime || user.status.was_online > currentTime || user.id == UserConfig.clientUserId) && user.status.expires != 0) {
holder.messageTextView.setTextColor(0xff357aa8);
holder.messageTextView.setText(getStringEntry(R.string.Online));
} else {
if (user.status.was_online <= 10000 && user.status.expires <= 10000) {
holder.messageTextView.setText(getStringEntry(R.string.Invisible));
} else {
int value = user.status.was_online;
if (value == 0) {
value = user.status.expires;
}
holder.messageTextView.setText(String.format("%s %s", getStringEntry(R.string.LastSeen), Utilities.formatDateOnline(value)));
}
holder.messageTextView.setTextColor(0xff808080);
}
}
} 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 file

@ -131,7 +131,7 @@ public class ChatProfileChangeNameActivity extends BaseFragment {
} }
((ApplicationActivity)parentActivity).updateActionBar(); ((ApplicationActivity)parentActivity).updateActionBar();
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
boolean animations = preferences.getBoolean("view_animations", true); boolean animations = preferences.getBoolean("view_animations", true);
if (!animations) { if (!animations) {
firstNameField.requestFocus(); firstNameField.requestFocus();

View file

@ -26,6 +26,7 @@ import android.widget.TextView;
import org.telegram.PhoneFormat.PhoneFormat; import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.TL.TLRPC; import org.telegram.TL.TLRPC;
import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.ContactsController;
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;
@ -49,7 +50,8 @@ public class ContactAddActivity extends BaseFragment implements NotificationCent
NotificationCenter.Instance.addObserver(this, MessagesController.updateInterfaces); NotificationCenter.Instance.addObserver(this, MessagesController.updateInterfaces);
user_id = getArguments().getInt("user_id", 0); user_id = getArguments().getInt("user_id", 0);
phone = getArguments().getString("phone"); phone = getArguments().getString("phone");
return true; TLRPC.User user = MessagesController.Instance.users.get(user_id);
return user != null;
} }
@Override @Override
@ -64,8 +66,10 @@ public class ContactAddActivity extends BaseFragment implements NotificationCent
fragmentView = inflater.inflate(R.layout.contact_add_layout, container, false); fragmentView = inflater.inflate(R.layout.contact_add_layout, container, false);
TLRPC.User user = MessagesController.Instance.users.get(user_id); TLRPC.User user = MessagesController.Instance.users.get(user_id);
if (phone != null) { if (user.phone == null) {
user.phone = PhoneFormat.stripExceptNumbers(phone); if (phone != null) {
user.phone = PhoneFormat.stripExceptNumbers(phone);
}
} }
onlineText = (TextView)fragmentView.findViewById(R.id.settings_online); onlineText = (TextView)fragmentView.findViewById(R.id.settings_online);
@ -137,7 +141,7 @@ public class ContactAddActivity extends BaseFragment implements NotificationCent
if (value == 0) { if (value == 0) {
value = user.status.expires; value = user.status.expires;
} }
onlineText.setText(String.format("%s %s", getStringEntry(R.string.LastSeen), Utilities.formatDateOnline(value))); onlineText.setText(Utilities.formatDateOnline(value));
} }
} }
} }
@ -151,7 +155,10 @@ public class ContactAddActivity extends BaseFragment implements NotificationCent
public void didReceivedNotification(int id, Object... args) { public void didReceivedNotification(int id, Object... args) {
if (id == MessagesController.updateInterfaces) { if (id == MessagesController.updateInterfaces) {
updateAvatarLayout(); int mask = (Integer)args[0];
if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_STATUS) != 0) {
updateAvatarLayout();
}
} }
} }
@ -197,8 +204,9 @@ public class ContactAddActivity extends BaseFragment implements NotificationCent
TLRPC.User user = MessagesController.Instance.users.get(user_id); TLRPC.User user = MessagesController.Instance.users.get(user_id);
user.first_name = firstNameField.getText().toString(); user.first_name = firstNameField.getText().toString();
user.last_name = lastNameField.getText().toString(); user.last_name = lastNameField.getText().toString();
MessagesController.Instance.addContact(user); ContactsController.Instance.addContact(user);
finishFragment(); finishFragment();
NotificationCenter.Instance.postNotificationName(MessagesController.updateInterfaces, MessagesController.UPDATE_MASK_NAME);
} }
} }
}); });
@ -212,7 +220,7 @@ public class ContactAddActivity extends BaseFragment implements NotificationCent
} }
((ApplicationActivity)parentActivity).updateActionBar(); ((ApplicationActivity)parentActivity).updateActionBar();
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
boolean animations = preferences.getBoolean("view_animations", true); boolean animations = preferences.getBoolean("view_animations", true);
if (!animations) { if (!animations) {
firstNameField.requestFocus(); firstNameField.requestFocus();

View file

@ -30,16 +30,15 @@ import android.widget.BaseAdapter;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.TextView; import android.widget.TextView;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.TL.TLRPC; import org.telegram.TL.TLRPC;
import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.ContactsController;
import org.telegram.messenger.FileLog; import org.telegram.messenger.FileLog;
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;
import org.telegram.messenger.UserConfig; import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
import org.telegram.ui.Views.BackupImageView; import org.telegram.ui.Cells.ChatOrUserCell;
import org.telegram.ui.Views.BaseFragment; import org.telegram.ui.Views.BaseFragment;
import org.telegram.ui.Views.OnSwipeTouchListener; import org.telegram.ui.Views.OnSwipeTouchListener;
import org.telegram.ui.Views.PinnedHeaderListView; import org.telegram.ui.Views.PinnedHeaderListView;
@ -49,7 +48,6 @@ import java.lang.reflect.Field;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Locale;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
@ -70,7 +68,6 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
private TextView epmtyTextView; private TextView epmtyTextView;
private HashMap<Integer, TLRPC.User> ignoreUsers; private HashMap<Integer, TLRPC.User> ignoreUsers;
private SupportMenuItem searchItem; private SupportMenuItem searchItem;
private boolean isRTL;
private Timer searchDialogsTimer; private Timer searchDialogsTimer;
public ArrayList<TLRPC.User> searchResult; public ArrayList<TLRPC.User> searchResult;
@ -78,14 +75,13 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
public ContactsActivityDelegate delegate; public ContactsActivityDelegate delegate;
public static interface ContactsActivityDelegate { public static interface ContactsActivityDelegate {
public abstract void didSelectContact(int user_id); public abstract void didSelectContact(TLRPC.User user);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public boolean onFragmentCreate() { public boolean onFragmentCreate() {
super.onFragmentCreate(); super.onFragmentCreate();
NotificationCenter.Instance.addObserver(this, MessagesController.contactsBookDidLoaded);
NotificationCenter.Instance.addObserver(this, MessagesController.contactsDidLoaded); NotificationCenter.Instance.addObserver(this, MessagesController.contactsDidLoaded);
NotificationCenter.Instance.addObserver(this, MessagesController.updateInterfaces); NotificationCenter.Instance.addObserver(this, MessagesController.updateInterfaces);
NotificationCenter.Instance.addObserver(this, MessagesController.encryptedChatCreated); NotificationCenter.Instance.addObserver(this, MessagesController.encryptedChatCreated);
@ -105,7 +101,6 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
@Override @Override
public void onFragmentDestroy() { public void onFragmentDestroy() {
super.onFragmentDestroy(); super.onFragmentDestroy();
NotificationCenter.Instance.removeObserver(this, MessagesController.contactsBookDidLoaded);
NotificationCenter.Instance.removeObserver(this, MessagesController.contactsDidLoaded); NotificationCenter.Instance.removeObserver(this, MessagesController.contactsDidLoaded);
NotificationCenter.Instance.removeObserver(this, MessagesController.updateInterfaces); NotificationCenter.Instance.removeObserver(this, MessagesController.updateInterfaces);
NotificationCenter.Instance.removeObserver(this, MessagesController.encryptedChatCreated); NotificationCenter.Instance.removeObserver(this, MessagesController.encryptedChatCreated);
@ -132,10 +127,6 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (fragmentView == null) { if (fragmentView == null) {
Locale locale = Locale.getDefault();
String lang = locale.getLanguage();
isRTL = lang != null && lang.toLowerCase().equals("ar");
fragmentView = inflater.inflate(R.layout.contacts_layout, container, false); fragmentView = inflater.inflate(R.layout.contacts_layout, container, false);
epmtyTextView = (TextView)fragmentView.findViewById(R.id.searchEmptyView); epmtyTextView = (TextView)fragmentView.findViewById(R.id.searchEmptyView);
@ -150,23 +141,23 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
@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 (searching && searchWas) { if (searching && searchWas) {
int user_id = searchResult.get(i).id; TLRPC.User user = searchResult.get(i);
if (user_id == UserConfig.clientUserId) { if (user.id == UserConfig.clientUserId) {
return; return;
} }
if (returnAsResult) { if (returnAsResult) {
if (ignoreUsers != null && ignoreUsers.containsKey(user_id)) { if (ignoreUsers != null && ignoreUsers.containsKey(user.id)) {
return; return;
} }
didSelectResult(user_id, true); didSelectResult(user, true);
} else { } else {
if (createSecretChat) { if (createSecretChat) {
creatingChat = true; creatingChat = true;
MessagesController.Instance.startSecretChat(parentActivity, user_id); MessagesController.Instance.startSecretChat(parentActivity, user);
} else { } else {
ChatActivity fragment = new ChatActivity(); ChatActivity fragment = new ChatActivity();
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putInt("user_id", user_id); bundle.putInt("user_id", user.id);
fragment.setArguments(bundle); fragment.setArguments(bundle);
((ApplicationActivity)parentActivity).presentFragment(fragment, "chat" + Math.random(), destroyAfterSelect, false); ((ApplicationActivity)parentActivity).presentFragment(fragment, "chat" + Math.random(), destroyAfterSelect, false);
} }
@ -174,11 +165,14 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
} else { } else {
int section = listViewAdapter.getSectionForPosition(i); int section = listViewAdapter.getSectionForPosition(i);
int row = listViewAdapter.getPositionInSectionForPosition(i); int row = listViewAdapter.getPositionInSectionForPosition(i);
int uid = 0; TLRPC.User user = null;
if (usersAsSections) { if (usersAsSections) {
if (section < MessagesController.Instance.sortedUsersSectionsArray.size()) { if (section < ContactsController.Instance.sortedUsersSectionsArray.size()) {
ArrayList<TLRPC.TL_contact> arr = MessagesController.Instance.usersSectionsDict.get(MessagesController.Instance.sortedUsersSectionsArray.get(section)); ArrayList<TLRPC.TL_contact> arr = ContactsController.Instance.usersSectionsDict.get(ContactsController.Instance.sortedUsersSectionsArray.get(section));
uid = arr.get(row).user_id; if (row >= arr.size()) {
return;
}
user = MessagesController.Instance.users.get(arr.get(row).user_id);
} }
} else { } else {
if (section == 0) { if (section == 0) {
@ -193,8 +187,8 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
} }
return; return;
} else { } else {
if (row - 1 < MessagesController.Instance.contacts.size()) { if (row - 1 < ContactsController.Instance.contacts.size()) {
uid = MessagesController.Instance.contacts.get(row - 1).user_id; user = MessagesController.Instance.users.get(ContactsController.Instance.contacts.get(row - 1).user_id);
} else { } else {
return; return;
} }
@ -202,53 +196,36 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
} }
} }
if (uid != 0) { if (user != null) {
if (uid == UserConfig.clientUserId) { if (user.id == UserConfig.clientUserId) {
return; return;
} }
if (returnAsResult) { if (returnAsResult) {
if (ignoreUsers != null && ignoreUsers.containsKey(uid)) { if (ignoreUsers != null && ignoreUsers.containsKey(user.id)) {
return; return;
} }
didSelectResult(uid, true); didSelectResult(user, true);
} else { } else {
if (createSecretChat) { if (createSecretChat) {
creatingChat = true; creatingChat = true;
MessagesController.Instance.startSecretChat(parentActivity, uid); MessagesController.Instance.startSecretChat(parentActivity, user);
} else { } else {
ChatActivity fragment = new ChatActivity(); ChatActivity fragment = new ChatActivity();
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putInt("user_id", uid); bundle.putInt("user_id", user.id);
fragment.setArguments(bundle); fragment.setArguments(bundle);
((ApplicationActivity)parentActivity).presentFragment(fragment, "chat" + Math.random(), destroyAfterSelect, false); ((ApplicationActivity)parentActivity).presentFragment(fragment, "chat" + Math.random(), destroyAfterSelect, false);
} }
} }
} else { } else {
ArrayList<MessagesController.Contact> arr = MessagesController.Instance.contactsSectionsDict.get(MessagesController.Instance.sortedContactsSectionsArray.get(section - 1)); ArrayList<ContactsController.Contact> arr = ContactsController.Instance.contactsSectionsDict.get(ContactsController.Instance.sortedContactsSectionsArray.get(section - 1));
MessagesController.Contact contact = arr.get(row); ContactsController.Contact contact = arr.get(row);
String usePhone = null; String usePhone = null;
for (String phone : contact.phones) { if (!contact.phones.isEmpty()) {
if (usePhone == null) { usePhone = contact.phones.get(0);
usePhone = phone; }
} if (usePhone == null) {
String cleanPhone = PhoneFormat.stripExceptNumbers(usePhone); return;
TLRPC.TL_contact cLocal = MessagesController.Instance.contactsByPhones.get(cleanPhone);
if (cLocal != null) {
if (cLocal.user_id == UserConfig.clientUserId) {
return;
}
if (createSecretChat) {
creatingChat = true;
MessagesController.Instance.startSecretChat(parentActivity, cLocal.user_id);
} else {
ChatActivity fragment = new ChatActivity();
Bundle bundle = new Bundle();
bundle.putInt("user_id", cLocal.user_id);
fragment.setArguments(bundle);
((ApplicationActivity)parentActivity).presentFragment(fragment, "chat" + Math.random(), destroyAfterSelect, false);
}
return;
}
} }
AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity); AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
builder.setMessage(getStringEntry(R.string.InviteUser)); builder.setMessage(getStringEntry(R.string.InviteUser));
@ -302,23 +279,22 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
return fragmentView; return fragmentView;
} }
private void didSelectResult(final int user_id, boolean useAlert) { private void didSelectResult(final TLRPC.User user, boolean useAlert) {
if (useAlert && selectAlertString != 0) { if (useAlert && selectAlertString != 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity); AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
builder.setTitle(R.string.AppName); builder.setTitle(R.string.AppName);
TLRPC.User user = MessagesController.Instance.users.get(user_id);
builder.setMessage(String.format(getStringEntry(selectAlertString), Utilities.formatName(user.first_name, user.last_name))); builder.setMessage(String.format(getStringEntry(selectAlertString), Utilities.formatName(user.first_name, user.last_name)));
builder.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() { builder.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
@Override @Override
public void onClick(DialogInterface dialogInterface, int i) { public void onClick(DialogInterface dialogInterface, int i) {
didSelectResult(user_id, false); didSelectResult(user, false);
} }
}); });
builder.setNegativeButton(R.string.Cancel, null); builder.setNegativeButton(R.string.Cancel, null);
builder.show().setCanceledOnTouchOutside(true); builder.show().setCanceledOnTouchOutside(true);
} else { } else {
if (delegate != null) { if (delegate != null) {
delegate.didSelectContact(user_id); delegate.didSelectContact(user);
delegate = null; delegate = null;
} }
finishFragment(); finishFragment();
@ -422,7 +398,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
ArrayList<TLRPC.User> resultArray = new ArrayList<TLRPC.User>(); ArrayList<TLRPC.User> resultArray = new ArrayList<TLRPC.User>();
ArrayList<CharSequence> resultArrayNames = new ArrayList<CharSequence>(); ArrayList<CharSequence> resultArrayNames = new ArrayList<CharSequence>();
for (TLRPC.TL_contact contact : MessagesController.Instance.contacts) { for (TLRPC.TL_contact contact : ContactsController.Instance.contacts) {
TLRPC.User user = MessagesController.Instance.users.get(contact.user_id); TLRPC.User user = MessagesController.Instance.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.clientUserId) {
@ -537,7 +513,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);
if (!isRTL) { if (!Utilities.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 {
listView.setPadding(Utilities.dp(30), listView.getPaddingTop(), Utilities.dp(16), listView.getPaddingBottom()); listView.setPadding(Utilities.dp(30), listView.getPaddingTop(), Utilities.dp(16), listView.getPaddingBottom());
@ -557,13 +533,14 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
@Override @Override
public void didReceivedNotification(int id, Object... args) { public void didReceivedNotification(int id, Object... args) {
if (id == MessagesController.contactsDidLoaded || id == MessagesController.contactsBookDidLoaded) { if (id == MessagesController.contactsDidLoaded) {
if (listViewAdapter != null) { if (listViewAdapter != null) {
listViewAdapter.notifyDataSetChanged(); listViewAdapter.notifyDataSetChanged();
} }
} else if (id == MessagesController.updateInterfaces) { } else if (id == MessagesController.updateInterfaces) {
if (listView != null) { int mask = (Integer)args[0];
listView.invalidateViews(); if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0 || (mask & MessagesController.UPDATE_MASK_STATUS) != 0) {
updateVisibleRows(mask);
} }
} else if (id == MessagesController.encryptedChatCreated) { } else if (id == MessagesController.encryptedChatCreated) {
if (createSecretChat && creatingChat) { if (createSecretChat && creatingChat) {
@ -577,6 +554,19 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
} }
} }
private void updateVisibleRows(int mask) {
if (listView == null) {
return;
}
int count = listView.getChildCount();
for (int a = 0; a < count; a++) {
View child = listView.getChildAt(a);
if (child instanceof ChatOrUserCell) {
((ChatOrUserCell) child).update(mask);
}
}
}
private class SearchAdapter extends BaseAdapter { private class SearchAdapter extends BaseAdapter {
private Context mContext; private Context mContext;
@ -619,76 +609,24 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
@Override @Override
public View getView(int i, View view, ViewGroup viewGroup) { public View getView(int i, View view, ViewGroup viewGroup) {
int type = getItemViewType(i);
if (view == null) { if (view == null) {
LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = new ChatOrUserCell(mContext);
if (type == 0) { ((ChatOrUserCell)view).usePadding = false;
view = li.inflate(R.layout.messages_search_user_layout, viewGroup, false);
} else {
view = li.inflate(R.layout.messages_search_chat_layout, viewGroup, false);
}
}
ContactListRowHolder holder = (ContactListRowHolder)view.getTag();
if (holder == null) {
holder = new ContactListRowHolder(view);
view.setTag(holder);
}
View divider = view.findViewById(R.id.settings_row_divider);
if (i == searchResult.size() - 1) {
divider.setVisibility(View.INVISIBLE);
} else {
divider.setVisibility(View.VISIBLE);
} }
((ChatOrUserCell) view).useSeparator = i != searchResult.size() - 1;
Object obj = searchResult.get(i); Object obj = searchResult.get(i);
CharSequence name = searchResultNames.get(i);
TLRPC.User user = MessagesController.Instance.users.get(((TLRPC.User)obj).id); TLRPC.User user = MessagesController.Instance.users.get(((TLRPC.User)obj).id);
holder.nameTextView.setText(name);
if (user != null) { if (user != null) {
((ChatOrUserCell)view).setData(user, null, null, searchResultNames.get(i), null);
if (ignoreUsers != null) { if (ignoreUsers != null) {
if (ignoreUsers.containsKey(user.id)) { if (ignoreUsers.containsKey(user.id)) {
if(android.os.Build.VERSION.SDK_INT >= 11) { ((ChatOrUserCell)view).drawAlpha = 0.5f;
holder.avatarImage.setAlpha(0.5f);
holder.messageTextView.setAlpha(0.5f);
holder.nameTextView.setAlpha(0.5f);
}
} else { } else {
if(android.os.Build.VERSION.SDK_INT >= 11) { ((ChatOrUserCell)view).drawAlpha = 1.0f;
holder.avatarImage.setAlpha(1.0f);
holder.messageTextView.setAlpha(1.0f);
holder.nameTextView.setAlpha(1.0f);
}
}
}
TLRPC.FileLocation photo = null;
if (user.photo != null) {
photo = user.photo.photo_small;
}
int placeHolderId = Utilities.getUserAvatarForId(user.id);
holder.avatarImage.setImage(photo, "50_50", placeHolderId);
if (user.status == null) {
holder.messageTextView.setTextColor(0xff808080);
holder.messageTextView.setText(getStringEntry(R.string.Offline));
} else {
int currentTime = ConnectionsManager.Instance.getCurrentTime();
if (user.status.expires > currentTime || user.status.was_online > currentTime) {
holder.messageTextView.setTextColor(0xff357aa8);
holder.messageTextView.setText(getStringEntry(R.string.Online));
} else {
if (user.status.was_online <= 10000 && user.status.expires <= 10000) {
holder.messageTextView.setText(getStringEntry(R.string.Invisible));
} else {
int value = user.status.was_online;
if (value == 0) {
value = user.status.expires;
}
holder.messageTextView.setText(getStringEntry(R.string.LastSeen) + " " + Utilities.formatDateOnline(value));
}
holder.messageTextView.setTextColor(0xff808080);
} }
} }
} }
@ -697,17 +635,12 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
@Override @Override
public int getItemViewType(int i) { public int getItemViewType(int i) {
Object obj = searchResult.get(i); return 0;
if (obj instanceof TLRPC.User) {
return 0;
} else {
return 1;
}
} }
@Override @Override
public int getViewTypeCount() { public int getViewTypeCount() {
return 2; return 1;
} }
@Override @Override
@ -737,12 +670,12 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
public int getSectionCount() { public int getSectionCount() {
int count = 0; int count = 0;
if (usersAsSections) { if (usersAsSections) {
count += MessagesController.Instance.sortedUsersSectionsArray.size(); count += ContactsController.Instance.sortedUsersSectionsArray.size();
} else { } else {
count++; count++;
} }
if (!onlyUsers) { if (!onlyUsers) {
count += MessagesController.Instance.sortedContactsSectionsArray.size(); count += ContactsController.Instance.sortedContactsSectionsArray.size();
} }
return count; return count;
} }
@ -750,16 +683,16 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
@Override @Override
public int getCountForSection(int section) { public int getCountForSection(int section) {
if (usersAsSections) { if (usersAsSections) {
if (section < MessagesController.Instance.sortedUsersSectionsArray.size()) { if (section < ContactsController.Instance.sortedUsersSectionsArray.size()) {
ArrayList<TLRPC.TL_contact> arr = MessagesController.Instance.usersSectionsDict.get(MessagesController.Instance.sortedUsersSectionsArray.get(section)); ArrayList<TLRPC.TL_contact> arr = ContactsController.Instance.usersSectionsDict.get(ContactsController.Instance.sortedUsersSectionsArray.get(section));
return arr.size(); return arr.size();
} }
} else { } else {
if (section == 0) { if (section == 0) {
return MessagesController.Instance.contacts.size() + 1; return ContactsController.Instance.contacts.size() + 1;
} }
} }
ArrayList<MessagesController.Contact> arr = MessagesController.Instance.contactsSectionsDict.get(MessagesController.Instance.sortedContactsSectionsArray.get(section - 1)); ArrayList<ContactsController.Contact> arr = ContactsController.Instance.contactsSectionsDict.get(ContactsController.Instance.sortedContactsSectionsArray.get(section - 1));
return arr.size(); return arr.size();
} }
@ -769,8 +702,8 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
TLRPC.User user = null; TLRPC.User user = null;
int count = 0; int count = 0;
if (usersAsSections) { if (usersAsSections) {
if (section < MessagesController.Instance.sortedUsersSectionsArray.size()) { if (section < ContactsController.Instance.sortedUsersSectionsArray.size()) {
ArrayList<TLRPC.TL_contact> arr = MessagesController.Instance.usersSectionsDict.get(MessagesController.Instance.sortedUsersSectionsArray.get(section)); ArrayList<TLRPC.TL_contact> arr = ContactsController.Instance.usersSectionsDict.get(ContactsController.Instance.sortedUsersSectionsArray.get(section));
user = MessagesController.Instance.users.get(arr.get(position).user_id); user = MessagesController.Instance.users.get(arr.get(position).user_id);
count = arr.size(); count = arr.size();
} }
@ -782,86 +715,36 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
convertView = li.inflate(R.layout.contacts_invite_row_layout, parent, false); convertView = li.inflate(R.layout.contacts_invite_row_layout, parent, false);
} }
View divider = convertView.findViewById(R.id.settings_row_divider); View divider = convertView.findViewById(R.id.settings_row_divider);
if (MessagesController.Instance.contacts.isEmpty()) { if (ContactsController.Instance.contacts.isEmpty()) {
divider.setVisibility(View.INVISIBLE); divider.setVisibility(View.INVISIBLE);
} else { } else {
divider.setVisibility(View.VISIBLE); divider.setVisibility(View.VISIBLE);
} }
return convertView; return convertView;
} }
user = MessagesController.Instance.users.get(MessagesController.Instance.contacts.get(position - 1).user_id); user = MessagesController.Instance.users.get(ContactsController.Instance.contacts.get(position - 1).user_id);
count = MessagesController.Instance.contacts.size(); count = ContactsController.Instance.contacts.size();
} }
} }
if (user != null) { if (user != null) {
if (convertView == null) { if (convertView == null) {
LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = new ChatOrUserCell(mContext);
convertView = li.inflate(R.layout.messages_search_user_layout, parent, false); ((ChatOrUserCell)convertView).useBoldFont = true;
} ((ChatOrUserCell)convertView).usePadding = false;
ContactListRowHolder holder = (ContactListRowHolder)convertView.getTag();
if (holder == null) {
holder = new ContactListRowHolder(convertView);
convertView.setTag(holder);
} }
((ChatOrUserCell)convertView).setData(user, null, null, null, null);
if (ignoreUsers != null) { if (ignoreUsers != null) {
if (ignoreUsers.containsKey(user.id)) { if (ignoreUsers.containsKey(user.id)) {
if(android.os.Build.VERSION.SDK_INT >= 11) { ((ChatOrUserCell)convertView).drawAlpha = 0.5f;
holder.avatarImage.setAlpha(0.5f);
holder.messageTextView.setAlpha(0.5f);
holder.nameTextView.setAlpha(0.5f);
}
} else { } else {
if(android.os.Build.VERSION.SDK_INT >= 11) { ((ChatOrUserCell)convertView).drawAlpha = 1.0f;
holder.avatarImage.setAlpha(1.0f);
holder.messageTextView.setAlpha(1.0f);
holder.nameTextView.setAlpha(1.0f);
}
} }
} }
View divider = convertView.findViewById(R.id.settings_row_divider); ((ChatOrUserCell) convertView).useSeparator = position != count - 1;
if (position == count - 1) {
divider.setVisibility(View.INVISIBLE);
} else {
divider.setVisibility(View.VISIBLE);
}
TLRPC.FileLocation photo = null;
if (user.first_name.length() != 0 && user.last_name.length() != 0) {
holder.nameTextView.setText(Html.fromHtml(user.first_name + " <b>" + user.last_name + "</b>"));
} else if (user.first_name.length() != 0) {
holder.nameTextView.setText(Html.fromHtml("<b>" + user.first_name + "</b>"));
} else {
holder.nameTextView.setText(Html.fromHtml("<b>" + user.last_name + "</b>"));
}
if (user.photo != null) {
photo = user.photo.photo_small;
}
int placeHolderId = Utilities.getUserAvatarForId(user.id);
holder.avatarImage.setImage(photo, "50_50", placeHolderId);
if (user.status == null) {
holder.messageTextView.setText(getStringEntry(R.string.Offline));
holder.messageTextView.setTextColor(0xff808080);
} else {
int currentTime = ConnectionsManager.Instance.getCurrentTime();
if (user.status.expires > currentTime || user.status.was_online > currentTime) {
holder.messageTextView.setTextColor(0xff357aa8);
holder.messageTextView.setText(getStringEntry(R.string.Online));
} else {
if (user.status.was_online <= 10000 && user.status.expires <= 10000) {
holder.messageTextView.setText(getStringEntry(R.string.Invisible));
} else {
int value = user.status.was_online;
if (value == 0) {
value = user.status.expires;
}
holder.messageTextView.setText(getStringEntry(R.string.LastSeen) + " " + Utilities.formatDateOnline(value));
}
holder.messageTextView.setTextColor(0xff808080);
}
}
return convertView; return convertView;
} }
@ -873,13 +756,16 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
} else { } else {
textView = (TextView)convertView.findViewById(R.id.settings_row_text); textView = (TextView)convertView.findViewById(R.id.settings_row_text);
} }
View divider = convertView.findViewById(R.id.settings_row_divider); View divider = convertView.findViewById(R.id.settings_row_divider);
ArrayList<MessagesController.Contact> arr = MessagesController.Instance.contactsSectionsDict.get(MessagesController.Instance.sortedContactsSectionsArray.get(section - 1)); ArrayList<ContactsController.Contact> arr = ContactsController.Instance.contactsSectionsDict.get(ContactsController.Instance.sortedContactsSectionsArray.get(section - 1));
MessagesController.Contact contact = arr.get(position); ContactsController.Contact contact = arr.get(position);
if (position == arr.size() - 1) { if (divider != null) {
divider.setVisibility(View.INVISIBLE); if (position == arr.size() - 1) {
} else { divider.setVisibility(View.INVISIBLE);
divider.setVisibility(View.VISIBLE); } else {
divider.setVisibility(View.VISIBLE);
}
} }
if (contact.first_name != null && contact.last_name != null) { if (contact.first_name != null && contact.last_name != null) {
textView.setText(Html.fromHtml(contact.first_name + " <b>" + contact.last_name + "</b>")); textView.setText(Html.fromHtml(contact.first_name + " <b>" + contact.last_name + "</b>"));
@ -894,7 +780,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
@Override @Override
public int getItemViewType(int section, int position) { public int getItemViewType(int section, int position) {
if (usersAsSections) { if (usersAsSections) {
if (section < MessagesController.Instance.sortedUsersSectionsArray.size()) { if (section < ContactsController.Instance.sortedUsersSectionsArray.size()) {
return 0; return 0;
} }
} else if (section == 0) { } else if (section == 0) {
@ -914,7 +800,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
@Override @Override
public int getSectionHeaderViewType(int section) { public int getSectionHeaderViewType(int section) {
if (usersAsSections) { if (usersAsSections) {
if (section < MessagesController.Instance.sortedUsersSectionsArray.size()) { if (section < ContactsController.Instance.sortedUsersSectionsArray.size()) {
return 1; return 1;
} }
} else if (section == 0) { } else if (section == 0) {
@ -931,14 +817,14 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
@Override @Override
public View getSectionHeaderView(int section, View convertView, ViewGroup parent) { public View getSectionHeaderView(int section, View convertView, ViewGroup parent) {
if (usersAsSections) { if (usersAsSections) {
if (section < MessagesController.Instance.sortedUsersSectionsArray.size()) { if (section < ContactsController.Instance.sortedUsersSectionsArray.size()) {
if (convertView == null) { if (convertView == null) {
LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = li.inflate(R.layout.settings_section_layout, parent, false); convertView = li.inflate(R.layout.settings_section_layout, parent, false);
convertView.setBackgroundColor(0xffffffff); convertView.setBackgroundColor(0xffffffff);
} }
TextView textView = (TextView)convertView.findViewById(R.id.settings_section_text); TextView textView = (TextView)convertView.findViewById(R.id.settings_section_text);
textView.setText(MessagesController.Instance.sortedUsersSectionsArray.get(section)); textView.setText(ContactsController.Instance.sortedUsersSectionsArray.get(section));
return convertView; return convertView;
} }
} else { } else {
@ -957,20 +843,8 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
convertView.setBackgroundColor(0xffffffff); convertView.setBackgroundColor(0xffffffff);
} }
TextView textView = (TextView)convertView.findViewById(R.id.settings_section_text); TextView textView = (TextView)convertView.findViewById(R.id.settings_section_text);
textView.setText(MessagesController.Instance.sortedContactsSectionsArray.get(section - 1)); textView.setText(ContactsController.Instance.sortedContactsSectionsArray.get(section - 1));
return convertView; return convertView;
} }
} }
public static class ContactListRowHolder {
public BackupImageView avatarImage;
public TextView messageTextView;
public TextView nameTextView;
public ContactListRowHolder(View view) {
messageTextView = (TextView)view.findViewById(R.id.messages_list_row_message);
nameTextView = (TextView)view.findViewById(R.id.messages_list_row_name);
avatarImage = (BackupImageView)view.findViewById(R.id.messages_list_row_avatar);
}
}
} }

View file

@ -41,7 +41,6 @@ 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.Locale;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
@ -54,7 +53,6 @@ public class CountrySelectActivity extends ActionBarActivity {
private boolean searching; private boolean searching;
private BaseAdapter searchListViewAdapter; private BaseAdapter searchListViewAdapter;
private TextView epmtyTextView; private TextView epmtyTextView;
private boolean isRTL;
private HashMap<String, ArrayList<Country>> countries = new HashMap<String, ArrayList<Country>>(); private HashMap<String, ArrayList<Country>> countries = new HashMap<String, ArrayList<Country>>();
private ArrayList<String> sortedCountries = new ArrayList<String>(); private ArrayList<String> sortedCountries = new ArrayList<String>();
@ -71,10 +69,6 @@ public class CountrySelectActivity extends ActionBarActivity {
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
Locale locale = Locale.getDefault();
String lang = locale.getLanguage();
isRTL = lang != null && lang.toLowerCase().equals("ar");
try { try {
BufferedReader reader = new BufferedReader(new InputStreamReader(getResources().getAssets().open("countries.txt"))); BufferedReader reader = new BufferedReader(new InputStreamReader(getResources().getAssets().open("countries.txt")));
String line; String line;
@ -260,7 +254,7 @@ public class CountrySelectActivity extends ActionBarActivity {
searchWas = false; searchWas = false;
ViewGroup group = (ViewGroup) listView.getParent(); ViewGroup group = (ViewGroup) listView.getParent();
listView.setAdapter(listViewAdapter); listView.setAdapter(listViewAdapter);
if (!isRTL) { if (!Utilities.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 {
listView.setPadding(Utilities.dp(30), listView.getPaddingTop(), Utilities.dp(16), listView.getPaddingBottom()); listView.setPadding(Utilities.dp(30), listView.getPaddingTop(), Utilities.dp(16), listView.getPaddingBottom());

View file

@ -102,8 +102,12 @@ public class DocumentSelectActivity extends BaseFragment {
@Override @Override
public void onFragmentDestroy() { public void onFragmentDestroy() {
if (receiverRegistered) { try {
parentActivity.unregisterReceiver(receiver); if (receiverRegistered) {
parentActivity.unregisterReceiver(receiver);
}
} catch (Exception e) {
FileLog.e("tmessages", e);
} }
super.onFragmentDestroy(); super.onFragmentDestroy();
} }
@ -376,13 +380,17 @@ public class DocumentSelectActivity extends BaseFragment {
if (extDevice != null) { if (extDevice != null) {
result.removeAll(aliases.get(extDevice)); result.removeAll(aliases.get(extDevice));
for (String path : result) { for (String path : result) {
boolean isSd = path.toLowerCase().contains("sd"); try {
ListItem item = new ListItem(); boolean isSd = path.toLowerCase().contains("sd");
item.title = getString(isSd ? R.string.SdCard : R.string.ExternalStorage); ListItem item = new ListItem();
item.icon = R.drawable.ic_external_storage; item.title = getString(isSd ? R.string.SdCard : R.string.ExternalStorage);
item.subtitle = getRootSubtitle(path); item.icon = R.drawable.ic_external_storage;
item.file = new File(path); item.subtitle = getRootSubtitle(path);
items.add(item); item.file = new File(path);
items.add(item);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
} }
} }
} catch (Exception e) { } catch (Exception e) {

View file

@ -9,12 +9,14 @@
package org.telegram.ui; package org.telegram.ui;
import android.content.Intent; import android.content.Intent;
import android.graphics.Point;
import android.net.Uri; import android.net.Uri;
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;
import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBar;
import android.view.Display;
import android.view.Menu; import android.view.Menu;
import android.view.MenuInflater; import android.view.MenuInflater;
import android.view.MenuItem; import android.view.MenuItem;
@ -64,6 +66,7 @@ public class GalleryImageViewer extends AbstractGalleryActivity implements Notif
private ProgressBar loadingProgress; private ProgressBar loadingProgress;
private String currentFileName; private String currentFileName;
private int user_id = 0; private int user_id = 0;
private Point displaySize = new Point();
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>();
@ -80,6 +83,14 @@ public class GalleryImageViewer extends AbstractGalleryActivity implements Notif
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
Display display = getWindowManager().getDefaultDisplay();
if(android.os.Build.VERSION.SDK_INT < 13) {
displaySize.set(display.getWidth(), display.getHeight());
} else {
display.getSize(displaySize);
}
classGuid = ConnectionsManager.Instance.generateClassGuid(); classGuid = ConnectionsManager.Instance.generateClassGuid();
setContentView(R.layout.gallery_layout); setContentView(R.layout.gallery_layout);
@ -112,6 +123,7 @@ public class GalleryImageViewer extends AbstractGalleryActivity implements Notif
NotificationCenter.Instance.addObserver(this, MessagesController.mediaCountDidLoaded); NotificationCenter.Instance.addObserver(this, MessagesController.mediaCountDidLoaded);
NotificationCenter.Instance.addObserver(this, MessagesController.mediaDidLoaded); NotificationCenter.Instance.addObserver(this, MessagesController.mediaDidLoaded);
NotificationCenter.Instance.addObserver(this, MessagesController.userPhotosLoaded); NotificationCenter.Instance.addObserver(this, MessagesController.userPhotosLoaded);
NotificationCenter.Instance.addObserver(this, 658);
Integer index = null; Integer index = null;
if (localPagerAdapter == null) { if (localPagerAdapter == null) {
@ -212,6 +224,9 @@ public class GalleryImageViewer extends AbstractGalleryActivity implements Notif
deleteButton.setOnClickListener(new View.OnClickListener() { deleteButton.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
if (mViewPager == null) {
return;
}
int item = mViewPager.getCurrentItem(); int item = mViewPager.getCurrentItem();
MessageObject obj = localPagerAdapter.imagesArr.get(item); MessageObject obj = localPagerAdapter.imagesArr.get(item);
if (obj.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENT) { if (obj.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENT) {
@ -241,6 +256,7 @@ public class GalleryImageViewer extends AbstractGalleryActivity implements Notif
NotificationCenter.Instance.removeObserver(this, MessagesController.mediaCountDidLoaded); NotificationCenter.Instance.removeObserver(this, MessagesController.mediaCountDidLoaded);
NotificationCenter.Instance.removeObserver(this, MessagesController.mediaDidLoaded); NotificationCenter.Instance.removeObserver(this, MessagesController.mediaDidLoaded);
NotificationCenter.Instance.removeObserver(this, MessagesController.userPhotosLoaded); NotificationCenter.Instance.removeObserver(this, MessagesController.userPhotosLoaded);
NotificationCenter.Instance.removeObserver(this, 658);
ConnectionsManager.Instance.cancelRpcsForClassGuid(classGuid); ConnectionsManager.Instance.cancelRpcsForClassGuid(classGuid);
} }
@ -354,7 +370,7 @@ public class GalleryImageViewer extends AbstractGalleryActivity implements Notif
getSupportActionBar().setTitle(String.format("%d %s %d", pos, getString(R.string.Of), totalCount)); getSupportActionBar().setTitle(String.format("%d %s %d", pos, getString(R.string.Of), totalCount));
if (title != null) { if (title != null) {
fakeTitleView.setText(String.format("%d %s %d", pos, getString(R.string.Of), totalCount)); fakeTitleView.setText(String.format("%d %s %d", pos, getString(R.string.Of), totalCount));
fakeTitleView.measure(View.MeasureSpec.makeMeasureSpec(400, View.MeasureSpec.AT_MOST), 40); fakeTitleView.measure(View.MeasureSpec.makeMeasureSpec(400, View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.AT_MOST));
title.setWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); title.setWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8));
title.setMaxWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); title.setMaxWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8));
} }
@ -450,10 +466,21 @@ public class GalleryImageViewer extends AbstractGalleryActivity implements Notif
} }
} }
} }
} else if (id == 658) {
try {
if (!isFinishing()) {
finish();
}
} catch (Exception e) {
e.printStackTrace();
}
} }
} }
private TLRPC.FileLocation getCurrentFile() { private TLRPC.FileLocation getCurrentFile() {
if (mViewPager == null) {
return null;
}
int item = mViewPager.getCurrentItem(); int item = mViewPager.getCurrentItem();
if (withoutBottom) { if (withoutBottom) {
return localPagerAdapter.imagesArrLocations.get(item); return localPagerAdapter.imagesArrLocations.get(item);
@ -775,7 +802,7 @@ public class GalleryImageViewer extends AbstractGalleryActivity implements Notif
getSupportActionBar().setTitle(String.format("%d %s %d", (totalCount - imagesArr.size()) + position + 1, getString(R.string.Of), totalCount)); getSupportActionBar().setTitle(String.format("%d %s %d", (totalCount - imagesArr.size()) + position + 1, getString(R.string.Of), totalCount));
if (title != null) { if (title != null) {
fakeTitleView.setText(String.format("%d %s %d", (totalCount - imagesArr.size()) + position + 1, getString(R.string.Of), totalCount)); fakeTitleView.setText(String.format("%d %s %d", (totalCount - imagesArr.size()) + position + 1, getString(R.string.Of), totalCount));
fakeTitleView.measure(View.MeasureSpec.makeMeasureSpec(400, View.MeasureSpec.AT_MOST), 40); fakeTitleView.measure(View.MeasureSpec.makeMeasureSpec(400, View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.AT_MOST));
title.setWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); title.setWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8));
title.setMaxWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); title.setMaxWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8));
} }
@ -794,7 +821,7 @@ public class GalleryImageViewer extends AbstractGalleryActivity implements Notif
getSupportActionBar().setTitle(String.format("%d %s %d", position + 1, getString(R.string.Of), imagesArrLocations.size())); getSupportActionBar().setTitle(String.format("%d %s %d", position + 1, getString(R.string.Of), imagesArrLocations.size()));
if (title != null) { if (title != null) {
fakeTitleView.setText(String.format("%d %s %d", position + 1, getString(R.string.Of), imagesArrLocations.size())); fakeTitleView.setText(String.format("%d %s %d", position + 1, getString(R.string.Of), imagesArrLocations.size()));
fakeTitleView.measure(View.MeasureSpec.makeMeasureSpec(400, View.MeasureSpec.AT_MOST), 40); fakeTitleView.measure(View.MeasureSpec.makeMeasureSpec(400, View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.AT_MOST));
title.setWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); title.setWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8));
title.setMaxWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); title.setMaxWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8));
} }
@ -885,7 +912,16 @@ public class GalleryImageViewer extends AbstractGalleryActivity implements Notif
ArrayList<TLRPC.PhotoSize> sizes = message.messageOwner.media.photo.sizes; ArrayList<TLRPC.PhotoSize> sizes = message.messageOwner.media.photo.sizes;
iv.isVideo = false; iv.isVideo = false;
if (sizes.size() > 0) { if (sizes.size() > 0) {
TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(sizes, 800, 800); int width = (int)(Math.min(displaySize.x, displaySize.y) * 0.7f);
int height = width + Utilities.dp(100);
if (width > 800) {
width = 800;
}
if (height > 800) {
height = 800;
}
TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(sizes, width, height);
if (message.imagePreview != null) { if (message.imagePreview != null) {
iv.setImage(sizeFull.location, null, message.imagePreview, sizeFull.size); iv.setImage(sizeFull.location, null, message.imagePreview, sizeFull.size);
} else { } else {

View file

@ -37,6 +37,7 @@ import android.widget.TextView;
import org.telegram.TL.TLRPC; import org.telegram.TL.TLRPC;
import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.Emoji; import org.telegram.messenger.Emoji;
import org.telegram.messenger.FileLog; import org.telegram.messenger.FileLog;
import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesController;
@ -44,6 +45,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.Views.BackupImageView;
import org.telegram.ui.Views.BaseFragment; import org.telegram.ui.Views.BaseFragment;
import org.telegram.ui.Views.PinnedHeaderListView; import org.telegram.ui.Views.PinnedHeaderListView;
import org.telegram.ui.Views.SectionedBaseAdapter; import org.telegram.ui.Views.SectionedBaseAdapter;
@ -198,7 +200,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
if (searching && searchWas) { if (searching && searchWas) {
user = searchResult.get(row); user = searchResult.get(row);
} else { } else {
ArrayList<TLRPC.TL_contact> arr = MessagesController.Instance.usersSectionsDict.get(MessagesController.Instance.sortedUsersSectionsArray.get(section)); ArrayList<TLRPC.TL_contact> arr = ContactsController.Instance.usersSectionsDict.get(ContactsController.Instance.sortedUsersSectionsArray.get(section));
user = MessagesController.Instance.users.get(arr.get(row).user_id); user = MessagesController.Instance.users.get(arr.get(row).user_id);
listView.invalidateViews(); listView.invalidateViews();
} }
@ -367,7 +369,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
ArrayList<CharSequence> resultArrayNames = new ArrayList<CharSequence>(); ArrayList<CharSequence> resultArrayNames = new ArrayList<CharSequence>();
String q = query.toLowerCase(); String q = query.toLowerCase();
for (TLRPC.TL_contact contact : MessagesController.Instance.contacts) { for (TLRPC.TL_contact contact : ContactsController.Instance.contacts) {
TLRPC.User user = MessagesController.Instance.users.get(contact.user_id); TLRPC.User user = MessagesController.Instance.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.clientUserId) {
@ -432,8 +434,11 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
listViewAdapter.notifyDataSetChanged(); listViewAdapter.notifyDataSetChanged();
} }
} else if (id == MessagesController.updateInterfaces) { } else if (id == MessagesController.updateInterfaces) {
if (listView != null) { int mask = (Integer)args[0];
listView.invalidateViews(); if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0 || (mask & MessagesController.UPDATE_MASK_STATUS) != 0) {
if (listView != null) {
listView.invalidateViews();
}
} }
} else if (id == MessagesController.chatDidCreated) { } else if (id == MessagesController.chatDidCreated) {
Utilities.RunOnUIThread(new Runnable() { Utilities.RunOnUIThread(new Runnable() {
@ -467,7 +472,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
if (searching && searchWas) { if (searching && searchWas) {
return searchResult == null || searchResult.isEmpty() ? 0 : 1; return searchResult == null || searchResult.isEmpty() ? 0 : 1;
} }
return MessagesController.Instance.sortedUsersSectionsArray.size(); return ContactsController.Instance.sortedUsersSectionsArray.size();
} }
@Override @Override
@ -475,7 +480,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
if (searching && searchWas) { if (searching && searchWas) {
return searchResult == null ? 0 : searchResult.size(); return searchResult == null ? 0 : searchResult.size();
} }
ArrayList<TLRPC.TL_contact> arr = MessagesController.Instance.usersSectionsDict.get(MessagesController.Instance.sortedUsersSectionsArray.get(section)); ArrayList<TLRPC.TL_contact> arr = ContactsController.Instance.usersSectionsDict.get(ContactsController.Instance.sortedUsersSectionsArray.get(section));
return arr.size(); return arr.size();
} }
@ -488,7 +493,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
user = MessagesController.Instance.users.get(searchResult.get(position).id); user = MessagesController.Instance.users.get(searchResult.get(position).id);
size = searchResult.size(); size = searchResult.size();
} else { } else {
ArrayList<TLRPC.TL_contact> arr = MessagesController.Instance.usersSectionsDict.get(MessagesController.Instance.sortedUsersSectionsArray.get(section)); ArrayList<TLRPC.TL_contact> arr = ContactsController.Instance.usersSectionsDict.get(ContactsController.Instance.sortedUsersSectionsArray.get(section));
user = MessagesController.Instance.users.get(arr.get(position).user_id); user = MessagesController.Instance.users.get(arr.get(position).user_id);
size = arr.size(); size = arr.size();
} }
@ -497,9 +502,9 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = li.inflate(R.layout.group_create_row_layout, parent, false); convertView = li.inflate(R.layout.group_create_row_layout, parent, false);
} }
ContactsActivity.ContactListRowHolder holder = (ContactsActivity.ContactListRowHolder)convertView.getTag(); ContactListRowHolder holder = (ContactListRowHolder)convertView.getTag();
if (holder == null) { if (holder == null) {
holder = new ContactsActivity.ContactListRowHolder(convertView); holder = new ContactListRowHolder(convertView);
convertView.setTag(holder); convertView.setTag(holder);
} }
@ -552,7 +557,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
if (value == 0) { if (value == 0) {
value = user.status.expires; value = user.status.expires;
} }
holder.messageTextView.setText(getStringEntry(R.string.LastSeen) + " " + Utilities.formatDateOnline(value)); holder.messageTextView.setText(Utilities.formatDateOnline(value));
} }
holder.messageTextView.setTextColor(0xff808080); holder.messageTextView.setTextColor(0xff808080);
} }
@ -592,9 +597,21 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
if (searching && searchWas) { if (searching && searchWas) {
textView.setText(getStringEntry(R.string.AllContacts)); textView.setText(getStringEntry(R.string.AllContacts));
} else { } else {
textView.setText(MessagesController.Instance.sortedUsersSectionsArray.get(section)); textView.setText(ContactsController.Instance.sortedUsersSectionsArray.get(section));
} }
return convertView; return convertView;
} }
} }
public static class ContactListRowHolder {
public BackupImageView avatarImage;
public TextView messageTextView;
public TextView nameTextView;
public ContactListRowHolder(View view) {
messageTextView = (TextView)view.findViewById(R.id.messages_list_row_message);
nameTextView = (TextView)view.findViewById(R.id.messages_list_row_name);
avatarImage = (BackupImageView)view.findViewById(R.id.messages_list_row_avatar);
}
}
} }

View file

@ -15,7 +15,6 @@ import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.internal.view.SupportMenuItem; import android.support.v4.internal.view.SupportMenuItem;
import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBar;
import android.text.Html;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.Menu; import android.view.Menu;
import android.view.MenuInflater; import android.view.MenuInflater;
@ -27,12 +26,12 @@ import android.widget.ImageButton;
import android.widget.TextView; import android.widget.TextView;
import org.telegram.TL.TLRPC; import org.telegram.TL.TLRPC;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLog; import org.telegram.messenger.FileLog;
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;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
import org.telegram.ui.Cells.ChatOrUserCell;
import org.telegram.ui.Views.AvatarUpdater; import org.telegram.ui.Views.AvatarUpdater;
import org.telegram.ui.Views.BackupImageView; import org.telegram.ui.Views.BackupImageView;
import org.telegram.ui.Views.BaseFragment; import org.telegram.ui.Views.BaseFragment;
@ -228,8 +227,9 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
@Override @Override
public void didReceivedNotification(int id, final Object... args) { public void didReceivedNotification(int id, final Object... args) {
if (id == MessagesController.updateInterfaces) { if (id == MessagesController.updateInterfaces) {
if (listView != null) { int mask = (Integer)args[0];
listView.invalidateViews(); if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0 || (mask & MessagesController.UPDATE_MASK_STATUS) != 0) {
updateVisibleRows(mask);
} }
} else if (id == MessagesController.chatDidFailCreate) { } else if (id == MessagesController.chatDidFailCreate) {
Utilities.HideProgressDialog(parentActivity); Utilities.HideProgressDialog(parentActivity);
@ -250,6 +250,19 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
} }
} }
private void updateVisibleRows(int mask) {
if (listView == null) {
return;
}
int count = listView.getChildCount();
for (int a = 0; a < count; a++) {
View child = listView.getChildAt(a);
if (child instanceof ChatOrUserCell) {
((ChatOrUserCell) child).update(mask);
}
}
}
private class ListAdapter extends SectionedBaseAdapter { private class ListAdapter extends SectionedBaseAdapter {
private Context mContext; private Context mContext;
@ -295,58 +308,13 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
TLRPC.User user = MessagesController.Instance.users.get(selectedContacts.get(position)); TLRPC.User user = MessagesController.Instance.users.get(selectedContacts.get(position));
if (convertView == null) { if (convertView == null) {
LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = new ChatOrUserCell(mContext);
convertView = li.inflate(R.layout.messages_search_user_layout, parent, false); ((ChatOrUserCell)convertView).useBoldFont = true;
} ((ChatOrUserCell)convertView).usePadding = false;
ContactsActivity.ContactListRowHolder holder = (ContactsActivity.ContactListRowHolder)convertView.getTag();
if (holder == null) {
holder = new ContactsActivity.ContactListRowHolder(convertView);
convertView.setTag(holder);
} }
View divider = convertView.findViewById(R.id.settings_row_divider); ((ChatOrUserCell)convertView).setData(user, null, null, null, null);
if (position == selectedContacts.size() - 1) { ((ChatOrUserCell) convertView).useSeparator = position != selectedContacts.size() - 1;
divider.setVisibility(View.INVISIBLE);
} else {
divider.setVisibility(View.VISIBLE);
}
if (user.first_name.length() != 0 && user.last_name.length() != 0) {
holder.nameTextView.setText(Html.fromHtml(user.first_name + " <b>" + user.last_name + "</b>"));
} else if (user.first_name.length() != 0) {
holder.nameTextView.setText(Html.fromHtml("<b>" + user.first_name + "</b>"));
} else {
holder.nameTextView.setText(Html.fromHtml("<b>" + user.last_name + "</b>"));
}
TLRPC.FileLocation photo = null;
if (user.photo != null) {
photo = user.photo.photo_small;
}
int placeHolderId = Utilities.getUserAvatarForId(user.id);
holder.avatarImage.setImage(photo, "50_50", placeHolderId);
if (user.status == null) {
holder.messageTextView.setTextColor(0xff808080);
holder.messageTextView.setText(getStringEntry(R.string.Offline));
} else {
int currentTime = ConnectionsManager.Instance.getCurrentTime();
if (user.status.expires > currentTime || user.status.was_online > currentTime) {
holder.messageTextView.setTextColor(0xff357aa8);
holder.messageTextView.setText(getStringEntry(R.string.Online));
} else {
if (user.status.was_online <= 10000 && user.status.expires <= 10000) {
holder.messageTextView.setText(getStringEntry(R.string.Invisible));
} else {
int value = user.status.was_online;
if (value == 0) {
value = user.status.expires;
}
holder.messageTextView.setText(getStringEntry(R.string.LastSeen) + " " + Utilities.formatDateOnline(value));
}
holder.messageTextView.setTextColor(0xff808080);
}
}
return convertView; return convertView;
} }

View file

@ -23,8 +23,7 @@ import android.widget.ImageView;
import android.widget.TextView; import android.widget.TextView;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;
import java.util.Locale;
public class IntroActivity extends ActionBarActivity { public class IntroActivity extends ActionBarActivity {
private ViewPager viewPager; private ViewPager viewPager;
@ -32,7 +31,6 @@ public class IntroActivity extends ActionBarActivity {
private ImageView topImage2; private ImageView topImage2;
private ViewGroup bottomPages; private ViewGroup bottomPages;
private int lastPage = 0; private int lastPage = 0;
private boolean isRTL = false;
private boolean justCreated = false; private boolean justCreated = false;
private boolean startPressed = false; private boolean startPressed = false;
private int[] icons; private int[] icons;
@ -45,10 +43,7 @@ public class IntroActivity extends ActionBarActivity {
setContentView(R.layout.intro_layout); setContentView(R.layout.intro_layout);
Locale locale = Locale.getDefault(); if (Utilities.isRTL) {
String lang = locale.getLanguage();
if (lang != null && lang.toLowerCase().equals("ar")) {
isRTL = true;
icons = new int[] { icons = new int[] {
R.drawable.intro7, R.drawable.intro7,
R.drawable.intro6, R.drawable.intro6,
@ -212,7 +207,7 @@ public class IntroActivity extends ActionBarActivity {
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
if (justCreated) { if (justCreated) {
if (isRTL) { if (Utilities.isRTL) {
viewPager.setCurrentItem(6); viewPager.setCurrentItem(6);
lastPage = 6; lastPage = 6;
} else { } else {

View file

@ -14,6 +14,7 @@ import android.content.Intent;
import android.database.Cursor; import android.database.Cursor;
import android.net.Uri; import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.os.Parcelable;
import org.telegram.TL.TLRPC; import org.telegram.TL.TLRPC;
import org.telegram.messenger.FileLog; import org.telegram.messenger.FileLog;
@ -21,6 +22,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.messenger.UserConfig; import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
import org.telegram.ui.Views.PausableActivity; import org.telegram.ui.Views.PausableActivity;
public class LaunchActivity extends PausableActivity { public class LaunchActivity extends PausableActivity {
@ -46,13 +48,22 @@ public class LaunchActivity extends PausableActivity {
if (Intent.ACTION_SEND.equals(intent.getAction())) { if (Intent.ACTION_SEND.equals(intent.getAction())) {
if (intent.getType() != null) { if (intent.getType() != null) {
if (intent.getType().startsWith("image/")) { if (intent.getType().startsWith("image/")) {
String path = intent.getParcelableExtra(Intent.EXTRA_STREAM).toString(); Parcelable parcelable = intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (path.startsWith("content:")) { if (parcelable == null) {
Cursor cursor = getContentResolver().query(Uri.parse(path), new String[]{android.provider.MediaStore.Images.ImageColumns.DATA}, null, null, null); return;
if (cursor != null) { }
cursor.moveToFirst(); String path = null;
path = cursor.getString(0); if (parcelable instanceof Uri) {
cursor.close(); path = Utilities.getPath(this, (Uri)parcelable);
} else {
path = intent.getParcelableExtra(Intent.EXTRA_STREAM).toString();
if (path.startsWith("content:")) {
Cursor cursor = getContentResolver().query(Uri.parse(path), new String[]{android.provider.MediaStore.Images.ImageColumns.DATA}, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
path = cursor.getString(0);
cursor.close();
}
} }
} }
if (path != null) { if (path != null) {
@ -62,13 +73,22 @@ public class LaunchActivity extends PausableActivity {
NotificationCenter.Instance.addToMemCache(533, path); NotificationCenter.Instance.addToMemCache(533, path);
} }
} else if (intent.getType().startsWith("video/")) { } else if (intent.getType().startsWith("video/")) {
String path = intent.getParcelableExtra(Intent.EXTRA_STREAM).toString(); Parcelable parcelable = intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (path.startsWith("content:")) { if (parcelable == null) {
Cursor cursor = getContentResolver().query(Uri.parse(path), new String[]{android.provider.MediaStore.Images.ImageColumns.DATA}, null, null, null); return;
if (cursor != null) { }
cursor.moveToFirst(); String path = null;
path = cursor.getString(0); if (parcelable instanceof Uri) {
cursor.close(); path = Utilities.getPath(this, (Uri)parcelable);
} else {
path = parcelable.toString();
if (path.startsWith("content:")) {
Cursor cursor = getContentResolver().query(Uri.parse(path), new String[]{android.provider.MediaStore.Images.ImageColumns.DATA}, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
path = cursor.getString(0);
cursor.close();
}
} }
} }
if (path != null) { if (path != null) {
@ -79,17 +99,24 @@ public class LaunchActivity extends PausableActivity {
} }
} else if (intent.getType().equals("text/plain")) { } else if (intent.getType().equals("text/plain")) {
String text = intent.getStringExtra(Intent.EXTRA_TEXT); String text = intent.getStringExtra(Intent.EXTRA_TEXT);
if (text.length() != 0) { if (text != null && text.length() != 0) {
NotificationCenter.Instance.addToMemCache(535, text); NotificationCenter.Instance.addToMemCache(535, text);
} }
} }
} }
} else if (Intent.ACTION_VIEW.equals(intent.getAction())) { } else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Cursor cursor = getContentResolver().query(intent.getData(), null, null, null, null); try {
if (cursor.moveToFirst()) { Cursor cursor = getContentResolver().query(intent.getData(), null, null, null, null);
int userId = cursor.getInt(cursor.getColumnIndex("DATA4")); if (cursor != null) {
NotificationCenter.Instance.postNotificationName(MessagesController.closeChats); if (cursor.moveToFirst()) {
NotificationCenter.Instance.addToMemCache("push_user_id", userId); int userId = cursor.getInt(cursor.getColumnIndex("DATA4"));
NotificationCenter.Instance.postNotificationName(MessagesController.closeChats);
NotificationCenter.Instance.addToMemCache("push_user_id", userId);
}
cursor.close();
}
} catch (Exception e) {
FileLog.e("tmessages", e);
} }
} else if (intent.getAction().equals("org.telegram.messenger.OPEN_ACCOUNT")) { } else if (intent.getAction().equals("org.telegram.messenger.OPEN_ACCOUNT")) {
NotificationCenter.Instance.addToMemCache("open_settings", 1); NotificationCenter.Instance.addToMemCache("open_settings", 1);
@ -115,6 +142,7 @@ public class LaunchActivity extends PausableActivity {
} }
int chatId = getIntent().getIntExtra("chatId", 0); int chatId = getIntent().getIntExtra("chatId", 0);
int userId = getIntent().getIntExtra("userId", 0); int userId = getIntent().getIntExtra("userId", 0);
int encId = getIntent().getIntExtra("encId", 0);
if (chatId != 0) { if (chatId != 0) {
TLRPC.Chat chat = MessagesController.Instance.chats.get(chatId); TLRPC.Chat chat = MessagesController.Instance.chats.get(chatId);
if (chat != null) { if (chat != null) {
@ -127,6 +155,12 @@ public class LaunchActivity extends PausableActivity {
NotificationCenter.Instance.postNotificationName(MessagesController.closeChats); NotificationCenter.Instance.postNotificationName(MessagesController.closeChats);
NotificationCenter.Instance.addToMemCache("push_user_id", userId); NotificationCenter.Instance.addToMemCache("push_user_id", userId);
} }
} else if (encId != 0) {
TLRPC.EncryptedChat chat = MessagesController.Instance.encryptedChats.get(encId);
if (chat != null) {
NotificationCenter.Instance.postNotificationName(MessagesController.closeChats);
NotificationCenter.Instance.addToMemCache("push_enc_id", encId);
}
} }
} }
} }

View file

@ -329,7 +329,10 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
@Override @Override
public void didReceivedNotification(int id, Object... args) { public void didReceivedNotification(int id, Object... args) {
if (id == MessagesController.updateInterfaces) { if (id == MessagesController.updateInterfaces) {
updateUserData(); int mask = (Integer)args[0];
if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0) {
updateUserData();
}
} else if (id == MessagesController.closeChats) { } else if (id == MessagesController.closeChats) {
removeSelfFromStack(); removeSelfFromStack();
} }

View file

@ -25,7 +25,6 @@ import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.TextView; import android.widget.TextView;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
import org.telegram.ui.Views.SlideView; import org.telegram.ui.Views.SlideView;

View file

@ -299,6 +299,10 @@ public class LoginActivityPhoneView extends SlideView implements AdapterView.OnI
@Override @Override
public void onNextPressed() { public void onNextPressed() {
if (codeField.length() == 0 || phoneField.length() == 0) {
delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.InvalidPhoneNumber));
return;
}
TLRPC.TL_auth_sendCode req = new TLRPC.TL_auth_sendCode(); TLRPC.TL_auth_sendCode req = new TLRPC.TL_auth_sendCode();
String phone = PhoneFormat.stripExceptNumbers("" + codeField.getText() + phoneField.getText()); String phone = PhoneFormat.stripExceptNumbers("" + codeField.getText() + phoneField.getText());
req.api_hash = ConnectionsManager.APP_HASH; req.api_hash = ConnectionsManager.APP_HASH;
@ -327,25 +331,31 @@ public class LoginActivityPhoneView extends SlideView implements AdapterView.OnI
Utilities.RunOnUIThread(new Runnable() { Utilities.RunOnUIThread(new Runnable() {
@Override @Override
public void run() { public void run() {
delegate.setPage(1, true, params, false); if (delegate != null) {
delegate.setPage(1, true, params, false);
}
} }
}); });
} else { } else {
if (error.text != null) { if (delegate != null) {
if (error.text.contains("PHONE_NUMBER_INVALID")) { if (error.text != null) {
delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.InvalidPhoneNumber)); if (error.text.contains("PHONE_NUMBER_INVALID")) {
} else if (error.text.contains("PHONE_CODE_EMPTY") || error.text.contains("PHONE_CODE_INVALID")) { delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.InvalidPhoneNumber));
delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.InvalidCode)); } else if (error.text.contains("PHONE_CODE_EMPTY") || error.text.contains("PHONE_CODE_INVALID")) {
} else if (error.text.contains("PHONE_CODE_EXPIRED")) { delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.InvalidCode));
delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.CodeExpired)); } else if (error.text.contains("PHONE_CODE_EXPIRED")) {
} else if (error.text.contains("FLOOD_WAIT")) { delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.CodeExpired));
delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.FloodWait)); } else if (error.text.contains("FLOOD_WAIT")) {
} else { delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.FloodWait));
delegate.needShowAlert(error.text); } else {
delegate.needShowAlert(error.text);
}
} }
} }
} }
delegate.needHideProgress(); if (delegate != null) {
delegate.needHideProgress();
}
} }
}, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors); }, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors);
} }

View file

@ -22,6 +22,7 @@ import android.widget.TextView;
import org.telegram.TL.TLObject; import org.telegram.TL.TLObject;
import org.telegram.TL.TLRPC; import org.telegram.TL.TLRPC;
import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage; import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.R; import org.telegram.messenger.R;
@ -191,7 +192,9 @@ public class LoginActivityRegisterView extends SlideView {
ConnectionsManager.Instance.performRpc(req, new RPCRequest.RPCRequestDelegate() { ConnectionsManager.Instance.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) {
delegate.needHideProgress(); if (delegate != null) {
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() { Utilities.RunOnUIThread(new Runnable() {
@ -211,23 +214,27 @@ public class LoginActivityRegisterView extends SlideView {
MessagesStorage.Instance.putUsersAndChats(users, null, true, true); MessagesStorage.Instance.putUsersAndChats(users, null, true, true);
//MessagesController.Instance.uploadAndApplyUserAvatar(avatarPhotoBig); //MessagesController.Instance.uploadAndApplyUserAvatar(avatarPhotoBig);
MessagesController.Instance.users.put(res.user.id, res.user); MessagesController.Instance.users.put(res.user.id, res.user);
MessagesController.Instance.checkAppAccount(); ContactsController.Instance.checkAppAccount();
delegate.needFinishActivity(); if (delegate != null) {
delegate.needFinishActivity();
}
} }
}); });
} else { } else {
if (error.text.contains("PHONE_NUMBER_INVALID")) { if (delegate != null) {
delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.InvalidPhoneNumber)); if (error.text.contains("PHONE_NUMBER_INVALID")) {
} else if (error.text.contains("PHONE_CODE_EMPTY") || error.text.contains("PHONE_CODE_INVALID")) { delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.InvalidPhoneNumber));
delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.InvalidCode)); } else if (error.text.contains("PHONE_CODE_EMPTY") || error.text.contains("PHONE_CODE_INVALID")) {
} else if (error.text.contains("PHONE_CODE_EXPIRED")) { delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.InvalidCode));
delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.CodeExpired)); } else if (error.text.contains("PHONE_CODE_EXPIRED")) {
} else if (error.text.contains("FIRSTNAME_INVALID")) { delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.CodeExpired));
delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.InvalidFirstName)); } else if (error.text.contains("FIRSTNAME_INVALID")) {
} else if (error.text.contains("LASTNAME_INVALID")) { delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.InvalidFirstName));
delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.InvalidLastName)); } else if (error.text.contains("LASTNAME_INVALID")) {
} else { delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.InvalidLastName));
delegate.needShowAlert(error.text); } else {
delegate.needShowAlert(error.text);
}
} }
} }
} }

View file

@ -24,6 +24,8 @@ import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.TL.TLObject; import org.telegram.TL.TLObject;
import org.telegram.TL.TLRPC; import org.telegram.TL.TLRPC;
import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage; import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.NotificationCenter;
@ -47,6 +49,7 @@ 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 int time = 60000; private int time = 60000;
private double lastCurrentTime; private double lastCurrentTime;
private boolean waitingForSms = false; private boolean waitingForSms = false;
@ -102,6 +105,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
@Override @Override
public void setParams(Bundle params) { public void setParams(Bundle params) {
codeField.setText(""); codeField.setText("");
Utilities.setWaitingForSms(true);
NotificationCenter.Instance.addObserver(this, 998); NotificationCenter.Instance.addObserver(this, 998);
currentParams = params; currentParams = params;
waitingForSms = true; waitingForSms = true;
@ -117,9 +121,15 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
codeField.requestFocus(); codeField.requestFocus();
time = 60000; time = 60000;
if (timeTimer != null) { try {
timeTimer.cancel(); synchronized(timerSync) {
timeTimer = null; if (timeTimer != null) {
timeTimer.cancel();
timeTimer = null;
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
} }
timeText.setText(String.format("%s 1:00", ApplicationLoader.applicationContext.getResources().getString(R.string.CallText))); timeText.setText(String.format("%s 1:00", ApplicationLoader.applicationContext.getResources().getString(R.string.CallText)));
lastCurrentTime = System.currentTimeMillis(); lastCurrentTime = System.currentTimeMillis();
@ -140,9 +150,11 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
timeText.setText(String.format("%s %d:%02d", ApplicationLoader.applicationContext.getResources().getString(R.string.CallText), minutes, seconds)); timeText.setText(String.format("%s %d:%02d", ApplicationLoader.applicationContext.getResources().getString(R.string.CallText), minutes, seconds));
} else { } else {
timeText.setText(ApplicationLoader.applicationContext.getResources().getString(R.string.Calling)); timeText.setText(ApplicationLoader.applicationContext.getResources().getString(R.string.Calling));
if (timeTimer != null) { synchronized(timerSync) {
timeTimer.cancel(); if (timeTimer != null) {
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;
@ -162,12 +174,25 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
@Override @Override
public void onNextPressed() { public void onNextPressed() {
waitingForSms = false; waitingForSms = false;
Utilities.setWaitingForSms(false);
NotificationCenter.Instance.removeObserver(this, 998); NotificationCenter.Instance.removeObserver(this, 998);
final TLRPC.TL_auth_signIn req = new TLRPC.TL_auth_signIn(); final TLRPC.TL_auth_signIn req = new TLRPC.TL_auth_signIn();
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;
delegate.needShowProgress(); try {
synchronized(timerSync) {
if (timeTimer != null) {
timeTimer.cancel();
timeTimer = null;
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
if (delegate != null) {
delegate.needShowProgress();
}
ConnectionsManager.Instance.performRpc(req, new RPCRequest.RPCRequestDelegate() { ConnectionsManager.Instance.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) {
@ -182,9 +207,15 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
if (delegate == null) { if (delegate == null) {
return; return;
} }
if (timeTimer != null) { try {
timeTimer.cancel(); synchronized(timerSync) {
timeTimer = null; if (timeTimer != null) {
timeTimer.cancel();
timeTimer = null;
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
} }
UserConfig.clearConfig(); UserConfig.clearConfig();
MessagesStorage.Instance.cleanUp(); MessagesStorage.Instance.cleanUp();
@ -198,8 +229,10 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
users.add(UserConfig.currentUser); users.add(UserConfig.currentUser);
MessagesStorage.Instance.putUsersAndChats(users, null, true, true); MessagesStorage.Instance.putUsersAndChats(users, null, true, true);
MessagesController.Instance.users.put(res.user.id, res.user); MessagesController.Instance.users.put(res.user.id, res.user);
MessagesController.Instance.checkAppAccount(); ContactsController.Instance.checkAppAccount();
delegate.needFinishActivity(); if (delegate != null) {
delegate.needFinishActivity();
}
} }
}); });
} else { } else {
@ -212,21 +245,67 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
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);
if (timeTimer != null) { try {
timeTimer.cancel(); synchronized(timerSync) {
timeTimer = null; if (timeTimer != null) {
timeTimer.cancel();
timeTimer = null;
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
} }
} }
}); });
} else { } else {
if (error.text.contains("PHONE_NUMBER_INVALID")) { if (timeTimer == null) {
delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.InvalidPhoneNumber)); timeTimer = new Timer();
} else if (error.text.contains("PHONE_CODE_EMPTY") || error.text.contains("PHONE_CODE_INVALID")) { timeTimer.schedule(new TimerTask() {
delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.InvalidCode)); @Override
} else if (error.text.contains("PHONE_CODE_EXPIRED")) { public void run() {
delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.CodeExpired)); double currentTime = System.currentTimeMillis();
} else { double diff = currentTime - lastCurrentTime;
delegate.needShowAlert(error.text); 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", ApplicationLoader.applicationContext.getResources().getString(R.string.CallText), minutes, seconds));
} else {
timeText.setText(ApplicationLoader.applicationContext.getResources().getString(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.Instance.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")) {
delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.InvalidPhoneNumber));
} else if (error.text.contains("PHONE_CODE_EMPTY") || error.text.contains("PHONE_CODE_INVALID")) {
delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.InvalidCode));
} else if (error.text.contains("PHONE_CODE_EXPIRED")) {
delegate.needShowAlert(ApplicationLoader.applicationContext.getString(R.string.CodeExpired));
} else {
delegate.needShowAlert(error.text);
}
} }
} }
} }
@ -236,11 +315,18 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
@Override @Override
public void onBackPressed() { public void onBackPressed() {
if (timeTimer != null) { try {
timeTimer.cancel(); synchronized(timerSync) {
timeTimer = null; if (timeTimer != null) {
timeTimer.cancel();
timeTimer = null;
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
} }
currentParams = null; currentParams = null;
Utilities.setWaitingForSms(false);
NotificationCenter.Instance.removeObserver(this, 998); NotificationCenter.Instance.removeObserver(this, 998);
waitingForSms = false; waitingForSms = false;
} }
@ -248,10 +334,17 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
@Override @Override
public void onDestroyActivity() { public void onDestroyActivity() {
super.onDestroyActivity(); super.onDestroyActivity();
Utilities.setWaitingForSms(false);
NotificationCenter.Instance.removeObserver(this, 998); NotificationCenter.Instance.removeObserver(this, 998);
if (timeTimer != null) { try {
timeTimer.cancel(); synchronized(timerSync) {
timeTimer = null; if (timeTimer != null) {
timeTimer.cancel();
timeTimer = null;
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
} }
waitingForSms = false; waitingForSms = false;
} }

View file

@ -11,15 +11,12 @@ package org.telegram.ui;
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.graphics.Typeface;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentActivity;
import android.support.v4.internal.view.SupportMenuItem; import android.support.v4.internal.view.SupportMenuItem;
import android.support.v4.view.MenuItemCompat; import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBar;
import android.support.v7.widget.SearchView; import android.support.v7.widget.SearchView;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.Menu; import android.view.Menu;
import android.view.MenuInflater; import android.view.MenuInflater;
@ -33,25 +30,22 @@ import android.widget.ImageView;
import android.widget.ListView; import android.widget.ListView;
import android.widget.TextView; import android.widget.TextView;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.TL.TLObject; import org.telegram.TL.TLObject;
import org.telegram.TL.TLRPC; import org.telegram.TL.TLRPC;
import org.telegram.messenger.Emoji; import org.telegram.messenger.ContactsController;
import org.telegram.messenger.FileLog; import org.telegram.messenger.FileLog;
import org.telegram.objects.MessageObject;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage; import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.NotificationCenter; 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.Views.BackupImageView; import org.telegram.ui.Cells.ChatOrUserCell;
import org.telegram.ui.Cells.DialogCell;
import org.telegram.ui.Views.BaseFragment; import org.telegram.ui.Views.BaseFragment;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Locale;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
@ -65,7 +59,6 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
private SearchView searchView; private SearchView searchView;
public int selectAlertString = 0; public int selectAlertString = 0;
private boolean serverOnly = false; private boolean serverOnly = false;
private boolean isRTL;
private static boolean dialogsLoaded = false; private static boolean dialogsLoaded = false;
private boolean searching = false; private boolean searching = false;
@ -91,7 +84,6 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
NotificationCenter.Instance.addObserver(this, 999); NotificationCenter.Instance.addObserver(this, 999);
NotificationCenter.Instance.addObserver(this, MessagesController.updateInterfaces); NotificationCenter.Instance.addObserver(this, MessagesController.updateInterfaces);
NotificationCenter.Instance.addObserver(this, MessagesController.reloadSearchResults); NotificationCenter.Instance.addObserver(this, MessagesController.reloadSearchResults);
NotificationCenter.Instance.addObserver(this, MessagesController.userPrintUpdateAll);
NotificationCenter.Instance.addObserver(this, MessagesController.encryptedChatUpdated); NotificationCenter.Instance.addObserver(this, MessagesController.encryptedChatUpdated);
NotificationCenter.Instance.addObserver(this, MessagesController.contactsDidLoaded); NotificationCenter.Instance.addObserver(this, MessagesController.contactsDidLoaded);
NotificationCenter.Instance.addObserver(this, 1234); NotificationCenter.Instance.addObserver(this, 1234);
@ -100,8 +92,8 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
serverOnly = getArguments().getBoolean("serverOnly", false); serverOnly = getArguments().getBoolean("serverOnly", false);
} }
if (!dialogsLoaded) { if (!dialogsLoaded) {
MessagesController.Instance.readContacts();
MessagesController.Instance.loadDialogs(0, 0, 100, true); MessagesController.Instance.loadDialogs(0, 0, 100, true);
ContactsController.Instance.checkAppAccount();
dialogsLoaded = true; dialogsLoaded = true;
} }
return true; return true;
@ -114,7 +106,6 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
NotificationCenter.Instance.removeObserver(this, 999); NotificationCenter.Instance.removeObserver(this, 999);
NotificationCenter.Instance.removeObserver(this, MessagesController.updateInterfaces); NotificationCenter.Instance.removeObserver(this, MessagesController.updateInterfaces);
NotificationCenter.Instance.removeObserver(this, MessagesController.reloadSearchResults); NotificationCenter.Instance.removeObserver(this, MessagesController.reloadSearchResults);
NotificationCenter.Instance.removeObserver(this, MessagesController.userPrintUpdateAll);
NotificationCenter.Instance.removeObserver(this, MessagesController.encryptedChatUpdated); NotificationCenter.Instance.removeObserver(this, MessagesController.encryptedChatUpdated);
NotificationCenter.Instance.removeObserver(this, MessagesController.contactsDidLoaded); NotificationCenter.Instance.removeObserver(this, MessagesController.contactsDidLoaded);
NotificationCenter.Instance.removeObserver(this, 1234); NotificationCenter.Instance.removeObserver(this, 1234);
@ -133,9 +124,6 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
fragmentView = inflater.inflate(R.layout.messages_list, container, false); fragmentView = inflater.inflate(R.layout.messages_list, container, false);
messagesListViewAdapter = new MessagesAdapter(parentActivity); messagesListViewAdapter = new MessagesAdapter(parentActivity);
Locale locale = Locale.getDefault();
String lang = locale.getLanguage();
isRTL = lang != null && lang.toLowerCase().equals("ar");
messagesListView = (ListView)fragmentView.findViewById(R.id.messages_list_view); messagesListView = (ListView)fragmentView.findViewById(R.id.messages_list_view);
messagesListView.setAdapter(messagesListViewAdapter); messagesListView.setAdapter(messagesListViewAdapter);
@ -248,7 +236,7 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
if (which == 0) { if (which == 0) {
MessagesController.Instance.deleteDialog(selectedDialog, 0, true); MessagesController.Instance.deleteDialog(selectedDialog, 0, true);
} else if (which == 1) { } else if (which == 1) {
MessagesController.Instance.deleteUserFromChat((int) -selectedDialog, UserConfig.clientUserId, null); MessagesController.Instance.deleteUserFromChat((int) -selectedDialog, MessagesController.Instance.users.get(UserConfig.clientUserId), null);
MessagesController.Instance.deleteDialog(selectedDialog, 0, false); MessagesController.Instance.deleteDialog(selectedDialog, 0, false);
} }
} }
@ -314,7 +302,7 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
actionBar.setDisplayShowCustomEnabled(false); actionBar.setDisplayShowCustomEnabled(false);
actionBar.setSubtitle(null); actionBar.setSubtitle(null);
actionBar.setCustomView(null); actionBar.setCustomView(null);
actionBar.setTitle(getStringEntry(R.string.AppName)); actionBar.setTitle(getStringEntry(R.string.SelectChat));
((ApplicationActivity)parentActivity).fixBackButton(); ((ApplicationActivity)parentActivity).fixBackButton();
} else { } else {
ImageView view = (ImageView)parentActivity.findViewById(16908332); ImageView view = (ImageView)parentActivity.findViewById(16908332);
@ -392,12 +380,10 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
} }
} else if (id == 999) { } else if (id == 999) {
if (messagesListView != null) { if (messagesListView != null) {
updateVisibleRows(); updateVisibleRows(0);
} }
} else if (id == MessagesController.updateInterfaces) { } else if (id == MessagesController.updateInterfaces) {
if (messagesListViewAdapter != null) { updateVisibleRows((Integer)args[0]);
messagesListViewAdapter.notifyDataSetChanged();
}
} else if (id == MessagesController.reloadSearchResults) { } else if (id == MessagesController.reloadSearchResults) {
int token = (Integer)args[0]; int token = (Integer)args[0];
if (token == activityToken) { if (token == activityToken) {
@ -405,32 +391,24 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
} }
} else if (id == 1234) { } else if (id == 1234) {
dialogsLoaded = false; dialogsLoaded = false;
} else if (id == MessagesController.userPrintUpdateAll) {
if (messagesListView != null) {
updateVisibleRows();
}
} else if (id == MessagesController.encryptedChatUpdated) { } else if (id == MessagesController.encryptedChatUpdated) {
if (messagesListView != null) { updateVisibleRows(0);
updateVisibleRows();
}
} else if (id == MessagesController.contactsDidLoaded) { } else if (id == MessagesController.contactsDidLoaded) {
if (messagesListView != null) { updateVisibleRows(0);
updateVisibleRows();
}
} }
} }
private void updateVisibleRows() { private void updateVisibleRows(int mask) {
if (searching && searchWas) { if (messagesListView == null) {
messagesListView.invalidate(); return;
} else { }
int count = messagesListView.getChildCount(); int count = messagesListView.getChildCount();
for (int a = 0; a < count; a++) { for (int a = 0; a < count; a++) {
View child = messagesListView.getChildAt(a); View child = messagesListView.getChildAt(a);
Object tag = child.getTag(); if (child instanceof DialogCell) {
if (tag instanceof MessagesListRowHolder) { ((DialogCell) child).update(mask);
((MessagesListRowHolder) tag).update(); } else if (child instanceof ChatOrUserCell) {
} ((ChatOrUserCell) child).update(mask);
} }
} }
} }
@ -452,15 +430,24 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
if (lower_part != 0) { if (lower_part != 0) {
if (lower_part > 0) { if (lower_part > 0) {
TLRPC.User user = MessagesController.Instance.users.get(lower_part); TLRPC.User user = MessagesController.Instance.users.get(lower_part);
if (user == null) {
return;
}
builder.setMessage(String.format(getStringEntry(selectAlertString), Utilities.formatName(user.first_name, user.last_name))); builder.setMessage(String.format(getStringEntry(selectAlertString), Utilities.formatName(user.first_name, user.last_name)));
} else if (lower_part < 0) { } else if (lower_part < 0) {
TLRPC.Chat chat = MessagesController.Instance.chats.get(-lower_part); TLRPC.Chat chat = MessagesController.Instance.chats.get(-lower_part);
if (chat == null) {
return;
}
builder.setMessage(String.format(getStringEntry(selectAlertString), chat.title)); builder.setMessage(String.format(getStringEntry(selectAlertString), chat.title));
} }
} else { } else {
int chat_id = (int)(dialog_id >> 32); int chat_id = (int)(dialog_id >> 32);
TLRPC.EncryptedChat chat = MessagesController.Instance.encryptedChats.get(chat_id); TLRPC.EncryptedChat chat = MessagesController.Instance.encryptedChats.get(chat_id);
TLRPC.User user = MessagesController.Instance.users.get(chat.user_id); TLRPC.User user = MessagesController.Instance.users.get(chat.user_id);
if (user == null) {
return;
}
builder.setMessage(String.format(getStringEntry(selectAlertString), Utilities.formatName(user.first_name, user.last_name))); builder.setMessage(String.format(getStringEntry(selectAlertString), Utilities.formatName(user.first_name, user.last_name)));
} }
builder.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() { builder.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
@ -740,29 +727,14 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
@Override @Override
public View getView(int i, View view, ViewGroup viewGroup) { public View getView(int i, View view, ViewGroup viewGroup) {
if (searching && searchWas) { if (searching && searchWas) {
int type = getItemViewType(i);
if (view == null) { if (view == null) {
LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = new ChatOrUserCell(mContext);
if (type == 2) {
view = li.inflate(R.layout.messages_search_user_layout, viewGroup, false);
} else {
view = li.inflate(R.layout.messages_search_chat_layout, viewGroup, false);
}
View v = view.findViewById(R.id.settings_row_divider);
v.setVisibility(View.VISIBLE);
view.setPadding(Utilities.dp(11), 0, Utilities.dp(11), 0);
}
MessagesListSearchRowHolder holder = (MessagesListSearchRowHolder)view.getTag();
if (holder == null) {
holder = new MessagesListSearchRowHolder(view);
view.setTag(holder);
} }
TLRPC.User user = null; TLRPC.User user = null;
TLRPC.Chat chat = null; TLRPC.Chat chat = null;
TLRPC.EncryptedChat encryptedChat = null; TLRPC.EncryptedChat encryptedChat = null;
TLObject obj = searchResult.get(i); TLObject obj = searchResult.get(i);
CharSequence name = searchResultNames.get(i);
if (obj instanceof TLRPC.User) { if (obj instanceof TLRPC.User) {
user = MessagesController.Instance.users.get(((TLRPC.User)obj).id); user = MessagesController.Instance.users.get(((TLRPC.User)obj).id);
} else if (obj instanceof TLRPC.Chat) { } else if (obj instanceof TLRPC.Chat) {
@ -772,57 +744,7 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
user = MessagesController.Instance.users.get(encryptedChat.user_id); user = MessagesController.Instance.users.get(encryptedChat.user_id);
} }
holder.nameTextView.setText(name); ((ChatOrUserCell)view).setData(user, chat, encryptedChat, searchResultNames.get(i), null);
if (encryptedChat != null) {
if (!isRTL) {
holder.nameTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_lock_green, 0, 0, 0);
} else {
holder.nameTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_lock_green, 0);
}
holder.nameTextView.setCompoundDrawablePadding(Utilities.dp(4));
} else {
holder.nameTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
holder.nameTextView.setCompoundDrawablePadding(0);
}
TLRPC.FileLocation photo = null;
int placeHolderId = 0;
if (user != null) {
if (user.photo != null) {
photo = user.photo.photo_small;
}
placeHolderId = Utilities.getUserAvatarForId(user.id);
} else if (chat != null) {
if (chat.photo != null) {
photo = chat.photo.photo_small;
}
placeHolderId = Utilities.getGroupAvatarForId(chat.id);
}
holder.avatarImage.setImage(photo, "50_50", placeHolderId);
if (user != null) {
if (user.status == null) {
holder.messageTextView.setTextColor(0xff808080);
holder.messageTextView.setText(getStringEntry(R.string.Offline));
} else {
int currentTime = ConnectionsManager.Instance.getCurrentTime();
if (user.status.expires > currentTime || user.status.was_online > currentTime) {
holder.messageTextView.setTextColor(0xff316f9f);
holder.messageTextView.setText(getStringEntry(R.string.Online));
} else {
if (user.status.was_online <= 10000 && user.status.expires <= 10000) {
holder.messageTextView.setText(getStringEntry(R.string.Invisible));
} else {
int value = user.status.was_online;
if (value == 0) {
value = user.status.expires;
}
holder.messageTextView.setText(getStringEntry(R.string.LastSeen) + " " + Utilities.formatDateOnline(value));
}
holder.messageTextView.setTextColor(0xff808080);
}
}
}
return view; return view;
} }
@ -836,21 +758,13 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
} }
if (view == null) { if (view == null) {
LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = new DialogCell(mContext);
view = li.inflate(R.layout.messages_list_row, viewGroup, false);
}
MessagesListRowHolder holder = (MessagesListRowHolder)view.getTag();
if (holder == null) {
holder = new MessagesListRowHolder(view);
view.setTag(holder);
} }
if (serverOnly) { if (serverOnly) {
holder.dialog = MessagesController.Instance.dialogsServerOnly.get(i); ((DialogCell)view).setDialog(MessagesController.Instance.dialogsServerOnly.get(i));
} else { } else {
holder.dialog = MessagesController.Instance.dialogs.get(i); ((DialogCell)view).setDialog(MessagesController.Instance.dialogs.get(i));
} }
holder.update();
return view; return view;
} }
@ -865,14 +779,8 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
return 3; return 3;
} }
} }
if (serverOnly) { if (serverOnly && i == MessagesController.Instance.dialogsServerOnly.size() || !serverOnly && i == MessagesController.Instance.dialogs.size()) {
if (i == MessagesController.Instance.dialogsServerOnly.size()) { return 1;
return 1;
}
} else {
if (i == MessagesController.Instance.dialogs.size()) {
return 1;
}
} }
return 0; return 0;
} }
@ -905,250 +813,4 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
return count == 0; return count == 0;
} }
} }
private class MessagesListSearchRowHolder {
public BackupImageView avatarImage;
public TextView messageTextView;
public TextView nameTextView;
public MessagesListSearchRowHolder(View view) {
messageTextView = (TextView)view.findViewById(R.id.messages_list_row_message);
nameTextView = (TextView)view.findViewById(R.id.messages_list_row_name);
avatarImage = (BackupImageView)view.findViewById(R.id.messages_list_row_avatar);
}
}
private class MessagesListRowHolder {
public ImageView errorImage;
public TextView messagesCountImage;
public BackupImageView avatarImage;
public TextView timeTextView;
public TextView messageTextView;
public TextView nameTextView;
public ImageView check1Image;
public ImageView check2Image;
public ImageView clockImage;
public TLRPC.TL_dialog dialog;
public MessagesListRowHolder(View view) {
messageTextView = (TextView)view.findViewById(R.id.messages_list_row_message);
nameTextView = (TextView)view.findViewById(R.id.messages_list_row_name);
if (nameTextView != null) {
Typeface typeface = Utilities.getTypeface("fonts/rmedium.ttf");
nameTextView.setTypeface(typeface);
}
timeTextView = (TextView)view.findViewById(R.id.messages_list_row_time);
avatarImage = (BackupImageView)view.findViewById(R.id.messages_list_row_avatar);
messagesCountImage = (TextView)view.findViewById(R.id.messages_list_row_badge);
errorImage = (ImageView)view.findViewById(R.id.messages_list_row_error);
check1Image = (ImageView)view.findViewById(R.id.messages_list_row_check_half);
check2Image = (ImageView)view.findViewById(R.id.messages_list_row_check);
clockImage = (ImageView)view.findViewById(R.id.messages_list_row_clock);
}
public void update() {
MessageObject message = MessagesController.Instance.dialogMessage.get(dialog.top_message);
TLRPC.User user = null;
TLRPC.Chat chat = null;
TLRPC.EncryptedChat encryptedChat = null;
int lower_id = (int)dialog.id;
if (lower_id != 0) {
if (lower_id < 0) {
chat = MessagesController.Instance.chats.get(-lower_id);
} else {
user = MessagesController.Instance.users.get(lower_id);
}
nameTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
nameTextView.setCompoundDrawablePadding(0);
} else {
encryptedChat = MessagesController.Instance.encryptedChats.get((int)(dialog.id >> 32));
if (encryptedChat != null) {
user = MessagesController.Instance.users.get(encryptedChat.user_id);
if (!isRTL) {
nameTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_lock_green, 0, 0, 0);
} else {
nameTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_lock_green, 0);
}
nameTextView.setCompoundDrawablePadding(Utilities.dp(4));
} else {
Log.e("test", "tda");
}
}
if (chat != null) {
nameTextView.setText(chat.title);
nameTextView.setTextColor(0xff000000);
} else if (user != null) {
if (user.id != 333000 && MessagesController.Instance.contactsDict.get(user.id) == null) {
if (MessagesController.Instance.contactsDict.size() == 0 && MessagesController.Instance.loadingContacts) {
nameTextView.setTextColor(0xff000000);
nameTextView.setText(Utilities.formatName(user.first_name, user.last_name));
} else {
if (user.phone != null && user.phone.length() != 0) {
nameTextView.setTextColor(0xff000000);
nameTextView.setText(PhoneFormat.Instance.format("+" + user.phone));
} else {
nameTextView.setTextColor(0xff316f9f);
nameTextView.setText(Utilities.formatName(user.first_name, user.last_name));
}
}
if (encryptedChat != null) {
nameTextView.setTextColor(0xff00a60e);
}
} else {
if (encryptedChat != null) {
nameTextView.setTextColor(0xff00a60e);
} else {
nameTextView.setTextColor(0xff000000);
}
nameTextView.setText(Utilities.formatName(user.first_name, user.last_name));
}
}
TLRPC.FileLocation photo = null;
int placeHolderId = 0;
if (user != null) {
if (user.photo != null) {
photo = user.photo.photo_small;
}
placeHolderId = Utilities.getUserAvatarForId(user.id);
} else if (chat != null) {
if (chat.photo != null) {
photo = chat.photo.photo_small;
}
placeHolderId = Utilities.getGroupAvatarForId(chat.id);
}
CharSequence printingString = MessagesController.Instance.printingStrings.get(dialog.id);
avatarImage.setImage(photo, "50_50", placeHolderId);
if (message == null) {
if (printingString != null) {
messageTextView.setText(printingString);
messageTextView.setTextColor(0xff316f9f);
} else {
if (encryptedChat != null) {
messageTextView.setTextColor(0xff316f9f);
if (encryptedChat instanceof TLRPC.TL_encryptedChatRequested) {
messageTextView.setText(getStringEntry(R.string.EncryptionProcessing));
} else if (encryptedChat instanceof TLRPC.TL_encryptedChatWaiting) {
messageTextView.setText(String.format(getStringEntry(R.string.AwaitingEncryption), user.first_name));
} else if (encryptedChat instanceof TLRPC.TL_encryptedChatDiscarded) {
messageTextView.setText(getStringEntry(R.string.EncryptionRejected));
} else if (encryptedChat instanceof TLRPC.TL_encryptedChat) {
if (encryptedChat.admin_id == UserConfig.clientUserId) {
if (user != null) {
messageTextView.setText(String.format(getStringEntry(R.string.EncryptedChatStartedOutgoing), user.first_name));
}
} else {
if (user != null) {
messageTextView.setText(String.format(getStringEntry(R.string.EncryptedChatStartedIncoming), user.first_name));
}
}
}
} else {
messageTextView.setText("");
}
}
if (dialog.last_message_date != 0) {
timeTextView.setText(Utilities.stringForMessageListDate(dialog.last_message_date));
} else {
timeTextView.setText("");
}
messagesCountImage.setVisibility(View.GONE);
check1Image.setVisibility(View.GONE);
check2Image.setVisibility(View.GONE);
errorImage.setVisibility(View.GONE);
clockImage.setVisibility(View.GONE);
} else {
TLRPC.User fromUser = MessagesController.Instance.users.get(message.messageOwner.from_id);
if (dialog.last_message_date != 0) {
timeTextView.setText(Utilities.stringForMessageListDate(dialog.last_message_date));
} else {
timeTextView.setText(Utilities.stringForMessageListDate(message.messageOwner.date));
}
if (printingString != null) {
messageTextView.setTextColor(0xff316f9f);
messageTextView.setText(printingString);
} else {
if (message.messageOwner instanceof TLRPC.TL_messageService) {
messageTextView.setText(message.messageText);
messageTextView.setTextColor(0xff316f9f);
} else {
if (chat != null) {
String name = "";
if (message.messageOwner.from_id == UserConfig.clientUserId) {
name = getStringEntry(R.string.FromYou);
} else {
if (fromUser != null) {
if (fromUser.first_name.length() > 0) {
name = fromUser.first_name;
} else {
name = fromUser.last_name;
}
}
}
if (message.messageOwner.media != null && !(message.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty)) {
messageTextView.setTextColor(0xff316f9f);
messageTextView.setText(message.messageText);
} else {
messageTextView.setText(Emoji.replaceEmoji(Html.fromHtml(String.format("<font color=#316f9f>%s:</font> <font color=#808080>%s</font>", name, message.messageOwner.message))));
}
} else {
messageTextView.setText(message.messageText);
if (message.messageOwner.media != null && !(message.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty)) {
messageTextView.setTextColor(0xff316f9f);
} else {
messageTextView.setTextColor(0xff808080);
}
}
}
}
if (dialog.unread_count != 0) {
messagesCountImage.setVisibility(View.VISIBLE);
messagesCountImage.setText(String.format("%d", dialog.unread_count));
} else {
messagesCountImage.setVisibility(View.GONE);
}
if (message.messageOwner.id < 0 && message.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SENT) {
if (MessagesController.Instance.sendingMessages.get(message.messageOwner.id) == null) {
message.messageOwner.send_state = MessagesController.MESSAGE_SEND_STATE_SEND_ERROR;
}
}
if (message.messageOwner.from_id == UserConfig.clientUserId) {
if (message.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENDING) {
check1Image.setVisibility(View.GONE);
check2Image.setVisibility(View.GONE);
clockImage.setVisibility(View.VISIBLE);
errorImage.setVisibility(View.GONE);
} else if (message.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SEND_ERROR) {
check1Image.setVisibility(View.GONE);
check2Image.setVisibility(View.GONE);
clockImage.setVisibility(View.GONE);
errorImage.setVisibility(View.VISIBLE);
messagesCountImage.setVisibility(View.GONE);
} else if (message.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENT) {
if (!message.messageOwner.unread) {
check1Image.setVisibility(View.VISIBLE);
check2Image.setVisibility(View.VISIBLE);
} else {
check1Image.setVisibility(View.GONE);
check2Image.setVisibility(View.VISIBLE);
}
clockImage.setVisibility(View.GONE);
errorImage.setVisibility(View.GONE);
}
} else {
check1Image.setVisibility(View.GONE);
check2Image.setVisibility(View.GONE);
errorImage.setVisibility(View.GONE);
clockImage.setVisibility(View.GONE);
}
}
}
}
} }

View file

@ -18,6 +18,7 @@ import android.graphics.Typeface;
import android.net.Uri; import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.View; import android.view.View;
@ -28,6 +29,7 @@ import android.widget.ImageButton;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.ListView; import android.widget.ListView;
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.TL.TLObject; import org.telegram.TL.TLObject;
@ -35,11 +37,13 @@ import org.telegram.TL.TLRPC;
import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLog; import org.telegram.messenger.FileLog;
import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.NotificationCenter; 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.UserConfig; import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
import org.telegram.objects.PhotoObject;
import org.telegram.ui.Views.AvatarUpdater; import org.telegram.ui.Views.AvatarUpdater;
import org.telegram.ui.Views.BackupImageView; import org.telegram.ui.Views.BackupImageView;
import org.telegram.ui.Views.BaseFragment; import org.telegram.ui.Views.BaseFragment;
@ -67,6 +71,12 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
int logoutRow; int logoutRow;
int sendLogsRow; int sendLogsRow;
int rowCount; int rowCount;
int messagesSectionRow;
int sendByEnterRow;
int terminateSessionsRow;
int photoDownloadSection;
int photoDownloadChatRow;
int photoDownloadPrivateRow;
@Override @Override
public boolean onFragmentCreate() { public boolean onFragmentCreate() {
@ -83,7 +93,46 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
ConnectionsManager.Instance.performRpc(req, new RPCRequest.RPCRequestDelegate() { ConnectionsManager.Instance.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) {
TLRPC.User user = MessagesController.Instance.users.get(UserConfig.clientUserId);
if (user == null) {
user = UserConfig.currentUser;
if (user == null) {
return;
}
MessagesController.Instance.users.put(user.id, user);
} else {
UserConfig.currentUser = user;
}
if (user == null) {
return;
}
TLRPC.TL_photos_photo photo = (TLRPC.TL_photos_photo)response;
ArrayList<TLRPC.PhotoSize> sizes = photo.photo.sizes;
TLRPC.PhotoSize smallSize = PhotoObject.getClosestPhotoSizeWithSize(sizes, 100, 100);
TLRPC.PhotoSize bigSize = PhotoObject.getClosestPhotoSizeWithSize(sizes, 1000, 1000);
user.photo = new TLRPC.TL_userProfilePhoto();
user.photo.photo_id = photo.photo.id;
if (smallSize != null) {
user.photo.photo_small = smallSize.location;
}
if (bigSize != null) {
user.photo.photo_big = bigSize.location;
} else if (smallSize != null) {
user.photo.photo_small = smallSize.location;
}
MessagesStorage.Instance.clearUserPhotos(user.id);
ArrayList<TLRPC.User> users = new ArrayList<TLRPC.User>();
users.add(user);
MessagesStorage.Instance.putUsersAndChats(users, null, false, true);
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
NotificationCenter.Instance.postNotificationName(MessagesController.updateInterfaces, MessagesController.UPDATE_MASK_ALL);
UserConfig.saveConfig(true);
}
});
}
} }
}, null, true, RPCRequest.RPCRequestClassGeneric); }, null, true, RPCRequest.RPCRequestClassGeneric);
} }
@ -96,11 +145,17 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
numberSectionRow = rowCount++; numberSectionRow = rowCount++;
numberRow = rowCount++; numberRow = rowCount++;
settingsSectionRow = rowCount++; settingsSectionRow = rowCount++;
textSizeRow = rowCount++;
enableAnimationsRow = rowCount++; enableAnimationsRow = rowCount++;
notificationRow = rowCount++; notificationRow = rowCount++;
blockedRow = rowCount++; blockedRow = rowCount++;
backgroundRow = rowCount++; backgroundRow = rowCount++;
terminateSessionsRow = rowCount++;
photoDownloadSection = rowCount++;
photoDownloadChatRow = rowCount++;
photoDownloadPrivateRow = rowCount++;
messagesSectionRow = rowCount++;
textSizeRow = rowCount++;
sendByEnterRow = rowCount++;
supportSectionRow = rowCount++; supportSectionRow = rowCount++;
if (ConnectionsManager.DEBUG_VERSION) { if (ConnectionsManager.DEBUG_VERSION) {
sendLogsRow = rowCount++; sendLogsRow = rowCount++;
@ -140,7 +195,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
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)}, 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)}, new DialogInterface.OnClickListener() {
@Override @Override
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit(); SharedPreferences.Editor editor = preferences.edit();
editor.putInt("fons_size", 12 + which); editor.putInt("fons_size", 12 + which);
editor.commit(); editor.commit();
@ -152,7 +207,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
builder.setNegativeButton(getStringEntry(R.string.Cancel), null); builder.setNegativeButton(getStringEntry(R.string.Cancel), null);
builder.show().setCanceledOnTouchOutside(true); builder.show().setCanceledOnTouchOutside(true);
} else if (i == enableAnimationsRow) { } else if (i == enableAnimationsRow) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
boolean animations = preferences.getBoolean("view_animations", true); boolean animations = preferences.getBoolean("view_animations", true);
SharedPreferences.Editor editor = preferences.edit(); SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("view_animations", !animations); editor.putBoolean("view_animations", !animations);
@ -174,6 +229,66 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
((ApplicationActivity)parentActivity).presentFragment(fragment, "chat" + Math.random(), false); ((ApplicationActivity)parentActivity).presentFragment(fragment, "chat" + Math.random(), false);
} else if (i == sendLogsRow) { } else if (i == sendLogsRow) {
sendLogs(); sendLogs();
} else if (i == sendByEnterRow) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
boolean send = preferences.getBoolean("send_by_enter", false);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("send_by_enter", !send);
editor.commit();
if (listView != null) {
listView.invalidateViews();
}
} else if (i == terminateSessionsRow) {
AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
builder.setMessage(getStringEntry(R.string.AreYouSure));
builder.setTitle(getStringEntry(R.string.AppName));
builder.setPositiveButton(getStringEntry(R.string.OK), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
TLRPC.TL_auth_resetAuthorizations req = new TLRPC.TL_auth_resetAuthorizations();
ConnectionsManager.Instance.performRpc(req, new RPCRequest.RPCRequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
ActionBarActivity inflaterActivity = parentActivity;
if (inflaterActivity == null) {
inflaterActivity = (ActionBarActivity)getActivity();
}
if (inflaterActivity == null) {
return;
}
if (error == null && response instanceof TLRPC.TL_boolTrue) {
Toast toast = Toast.makeText(inflaterActivity, R.string.TerminateAllSessions, Toast.LENGTH_SHORT);
toast.show();
} else {
Toast toast = Toast.makeText(inflaterActivity, R.string.UnknownError, Toast.LENGTH_SHORT);
toast.show();
}
UserConfig.registeredForPush = false;
MessagesController.Instance.registerForPush(UserConfig.pushString);
}
}, null, true, RPCRequest.RPCRequestClassGeneric);
}
});
builder.setNegativeButton(getStringEntry(R.string.Cancel), null);
builder.show().setCanceledOnTouchOutside(true);
} else if (i == photoDownloadChatRow) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
boolean value = preferences.getBoolean("photo_download_chat", true);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("photo_download_chat", !value);
editor.commit();
if (listView != null) {
listView.invalidateViews();
}
} else if (i == photoDownloadPrivateRow) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
boolean value = preferences.getBoolean("photo_download_user", true);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("photo_download_user", !value);
editor.commit();
if (listView != null) {
listView.invalidateViews();
}
} }
// else if (i == 6) { // else if (i == 6) {
// UserConfig.saveIncomingPhotos = !UserConfig.saveIncomingPhotos; // UserConfig.saveIncomingPhotos = !UserConfig.saveIncomingPhotos;
@ -209,8 +324,11 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
@Override @Override
public void didReceivedNotification(int id, Object... args) { public void didReceivedNotification(int id, Object... args) {
if (id == MessagesController.updateInterfaces) { if (id == MessagesController.updateInterfaces) {
if (listView != null) { int mask = (Integer)args[0];
listView.invalidateViews(); if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0) {
if (listView != null) {
listView.invalidateViews();
}
} }
} }
} }
@ -307,7 +425,9 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
@Override @Override
public boolean isEnabled(int i) { public boolean isEnabled(int i) {
return i == textSizeRow || i == enableAnimationsRow || i == blockedRow || i == notificationRow || i == backgroundRow || i == askQuestionRow || i == sendLogsRow; return i == textSizeRow || i == enableAnimationsRow || i == blockedRow || i == notificationRow || i == backgroundRow ||
i == askQuestionRow || i == sendLogsRow || i == sendByEnterRow || i == terminateSessionsRow || i == photoDownloadPrivateRow ||
i == photoDownloadChatRow;
} }
@Override @Override
@ -405,7 +525,30 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
ConnectionsManager.Instance.performRpc(req, new RPCRequest.RPCRequestDelegate() { ConnectionsManager.Instance.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) {
TLRPC.User user = MessagesController.Instance.users.get(UserConfig.clientUserId);
if (user == null) {
user = UserConfig.currentUser;
MessagesController.Instance.users.put(user.id, user);
} else {
UserConfig.currentUser = user;
}
if (user == null) {
return;
}
MessagesStorage.Instance.clearUserPhotos(user.id);
ArrayList<TLRPC.User> users = new ArrayList<TLRPC.User>();
users.add(user);
MessagesStorage.Instance.putUsersAndChats(users, null, false, true);
user.photo = (TLRPC.UserProfilePhoto)response;
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
NotificationCenter.Instance.postNotificationName(MessagesController.updateInterfaces, MessagesController.UPDATE_MASK_ALL);
UserConfig.saveConfig(true);
}
});
}
} }
}, null, true, RPCRequest.RPCRequestClassGeneric); }, null, true, RPCRequest.RPCRequestClassGeneric);
} }
@ -444,6 +587,10 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
textView.setText(getStringEntry(R.string.SETTINGS)); textView.setText(getStringEntry(R.string.SETTINGS));
} else if (i == supportSectionRow) { } else if (i == supportSectionRow) {
textView.setText(getStringEntry(R.string.Support)); textView.setText(getStringEntry(R.string.Support));
} else if (i == messagesSectionRow) {
textView.setText(getStringEntry(R.string.MessagesSettings));
} else if (i == photoDownloadSection) {
textView.setText(getStringEntry(R.string.AutomaticPhotoDownload));
} }
} else if (type == 2) { } else if (type == 2) {
if (view == null) { if (view == null) {
@ -468,13 +615,16 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
divider.setVisibility(backgroundRow != 0 ? View.VISIBLE : View.INVISIBLE); divider.setVisibility(backgroundRow != 0 ? View.VISIBLE : View.INVISIBLE);
} else if (i == backgroundRow) { } else if (i == backgroundRow) {
textView.setText(getStringEntry(R.string.ChatBackground)); textView.setText(getStringEntry(R.string.ChatBackground));
divider.setVisibility(View.INVISIBLE); divider.setVisibility(View.VISIBLE);
} else if (i == sendLogsRow) { } else if (i == sendLogsRow) {
textView.setText("Send Logs"); textView.setText("Send Logs");
divider.setVisibility(View.VISIBLE); divider.setVisibility(View.VISIBLE);
} else if (i == askQuestionRow) { } else if (i == askQuestionRow) {
textView.setText(getStringEntry(R.string.AskAQuestion)); textView.setText(getStringEntry(R.string.AskAQuestion));
divider.setVisibility(View.INVISIBLE); divider.setVisibility(View.INVISIBLE);
} else if (i == terminateSessionsRow) {
textView.setText(getStringEntry(R.string.TerminateAllSessions));
divider.setVisibility(View.INVISIBLE);
} }
} else if (type == 3) { } else if (type == 3) {
if (view == null) { if (view == null) {
@ -483,14 +633,40 @@ 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);
ImageView checkButton = (ImageView)view.findViewById(R.id.settings_row_check_button);
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
if (i == enableAnimationsRow) { if (i == enableAnimationsRow) {
textView.setText(getStringEntry(R.string.EnableAnimations)); textView.setText(getStringEntry(R.string.EnableAnimations));
divider.setVisibility(View.VISIBLE); divider.setVisibility(View.VISIBLE);
boolean enabled = preferences.getBoolean("view_animations", true);
ImageView checkButton = (ImageView)view.findViewById(R.id.settings_row_check_button); if (enabled) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); checkButton.setImageResource(R.drawable.btn_check_on);
boolean animations = preferences.getBoolean("view_animations", true); } else {
if (animations) { checkButton.setImageResource(R.drawable.btn_check_off);
}
} else if (i == sendByEnterRow) {
textView.setText(getStringEntry(R.string.SendByEnter));
divider.setVisibility(View.INVISIBLE);
boolean enabled = preferences.getBoolean("send_by_enter", false);
if (enabled) {
checkButton.setImageResource(R.drawable.btn_check_on);
} else {
checkButton.setImageResource(R.drawable.btn_check_off);
}
} else if (i == photoDownloadChatRow) {
textView.setText(getStringEntry(R.string.AutomaticPhotoDownloadGroups));
divider.setVisibility(View.VISIBLE);
boolean enabled = preferences.getBoolean("photo_download_chat", true);
if (enabled) {
checkButton.setImageResource(R.drawable.btn_check_on);
} else {
checkButton.setImageResource(R.drawable.btn_check_off);
}
} else if (i == photoDownloadPrivateRow) {
textView.setText(getStringEntry(R.string.AutomaticPhotoDownloadPrivateChats));
divider.setVisibility(View.INVISIBLE);
boolean enabled = preferences.getBoolean("photo_download_user", true);
if (enabled) {
checkButton.setImageResource(R.drawable.btn_check_on); checkButton.setImageResource(R.drawable.btn_check_on);
} else { } else {
checkButton.setImageResource(R.drawable.btn_check_off); checkButton.setImageResource(R.drawable.btn_check_off);
@ -541,7 +717,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
TextView detailTextView = (TextView)view.findViewById(R.id.settings_row_text_detail); 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 == textSizeRow) { if (i == textSizeRow) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
int size = preferences.getInt("fons_size", 16); int size = preferences.getInt("fons_size", 16);
detailTextView.setText(String.format("%d", size)); detailTextView.setText(String.format("%d", size));
textView.setText(ApplicationLoader.applicationContext.getString(R.string.TextSize)); textView.setText(ApplicationLoader.applicationContext.getString(R.string.TextSize));
@ -556,13 +732,13 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
public int getItemViewType(int i) { public int getItemViewType(int i) {
if (i == profileRow) { if (i == profileRow) {
return 0; return 0;
} else if (i == numberSectionRow || i == settingsSectionRow || i == supportSectionRow) { } else if (i == numberSectionRow || i == settingsSectionRow || i == supportSectionRow || i == messagesSectionRow || i == photoDownloadSection) {
return 1; return 1;
} else if (i == textSizeRow) { } else if (i == textSizeRow) {
return 5; return 5;
} else if (i == enableAnimationsRow) { } else if (i == enableAnimationsRow || i == sendByEnterRow || i == photoDownloadChatRow || i == photoDownloadPrivateRow) {
return 3; return 3;
} else if (i == numberRow || i == notificationRow || i == blockedRow || i == backgroundRow || i == askQuestionRow || i == sendLogsRow) { } else if (i == numberRow || i == notificationRow || i == blockedRow || i == backgroundRow || i == askQuestionRow || i == sendLogsRow || i == terminateSessionsRow) {
return 2; return 2;
} else if (i == logoutRow) { } else if (i == logoutRow) {
return 4; return 4;

View file

@ -13,7 +13,6 @@ import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.os.Bundle; import android.os.Bundle;
import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBar;
import android.text.Html;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.Menu; import android.view.Menu;
import android.view.MenuInflater; import android.view.MenuInflater;
@ -34,6 +33,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.Cells.ChatOrUserCell;
import org.telegram.ui.Views.BaseFragment; import org.telegram.ui.Views.BaseFragment;
import org.telegram.ui.Views.OnSwipeTouchListener; import org.telegram.ui.Views.OnSwipeTouchListener;
@ -118,14 +118,10 @@ public class SettingsBlockedUsers extends BaseFragment implements NotificationCe
if (i == 0) { if (i == 0) {
TLRPC.TL_contacts_unblock req = new TLRPC.TL_contacts_unblock(); TLRPC.TL_contacts_unblock req = new TLRPC.TL_contacts_unblock();
TLRPC.User user = MessagesController.Instance.users.get(selectedUserId); TLRPC.User user = MessagesController.Instance.users.get(selectedUserId);
if (user instanceof TLRPC.TL_userForeign || user instanceof TLRPC.TL_userRequest) { if (user == null) {
req.id = new TLRPC.TL_inputUserForeign(); return;
req.id.user_id = selectedUserId;
req.id.access_hash = user.access_hash;
} else {
req.id = new TLRPC.TL_inputUserContact();
req.id.user_id = selectedUserId;
} }
req.id = MessagesController.getInputUser(user);
TLRPC.TL_contactBlocked blocked = blockedContactsDict.get(selectedUserId); TLRPC.TL_contactBlocked blocked = blockedContactsDict.get(selectedUserId);
blockedContactsDict.remove(selectedUserId); blockedContactsDict.remove(selectedUserId);
blockedContacts.remove(blocked); blockedContacts.remove(blocked);
@ -229,8 +225,22 @@ public class SettingsBlockedUsers extends BaseFragment implements NotificationCe
@Override @Override
public void didReceivedNotification(int id, Object... args) { public void didReceivedNotification(int id, Object... args) {
if (id == MessagesController.updateInterfaces) { if (id == MessagesController.updateInterfaces) {
if (listView != null) { int mask = (Integer)args[0];
listView.invalidateViews(); if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0) {
updateVisibleRows(mask);
}
}
}
private void updateVisibleRows(int mask) {
if (listView == null) {
return;
}
int count = listView.getChildCount();
for (int a = 0; a < count; a++) {
View child = listView.getChildAt(a);
if (child instanceof ChatOrUserCell) {
((ChatOrUserCell) child).update(mask);
} }
} }
} }
@ -307,22 +317,14 @@ public class SettingsBlockedUsers extends BaseFragment implements NotificationCe
} }
@Override @Override
public void didSelectContact(int user_id) { public void didSelectContact(TLRPC.User user) {
if (blockedContactsDict.containsKey(user_id)) { if (user == null || blockedContactsDict.containsKey(user.id)) {
return; return;
} }
TLRPC.TL_contacts_block req = new TLRPC.TL_contacts_block(); TLRPC.TL_contacts_block req = new TLRPC.TL_contacts_block();
TLRPC.User user = MessagesController.Instance.users.get(selectedUserId); req.id = MessagesController.getInputUser(user);
if (user instanceof TLRPC.TL_userForeign || user instanceof TLRPC.TL_userRequest) {
req.id = new TLRPC.TL_inputUserForeign();
req.id.access_hash = user.access_hash;
req.id.user_id = user_id;
} else {
req.id = new TLRPC.TL_inputUserContact();
req.id.user_id = user_id;
}
TLRPC.TL_contactBlocked blocked = new TLRPC.TL_contactBlocked(); TLRPC.TL_contactBlocked blocked = new TLRPC.TL_contactBlocked();
blocked.user_id = user_id; blocked.user_id = user.id;
blocked.date = (int)(System.currentTimeMillis() / 1000); blocked.date = (int)(System.currentTimeMillis() / 1000);
blockedContactsDict.put(blocked.user_id, blocked); blockedContactsDict.put(blocked.user_id, blocked);
blockedContacts.add(blocked); blockedContacts.add(blocked);
@ -380,41 +382,13 @@ public class SettingsBlockedUsers extends BaseFragment implements NotificationCe
int type = getItemViewType(i); int type = getItemViewType(i);
if (type == 0) { if (type == 0) {
if (view == null) { if (view == null) {
LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = new ChatOrUserCell(mContext);
view = li.inflate(R.layout.messages_search_user_layout, viewGroup, false); ((ChatOrUserCell)view).useBoldFont = true;
((ChatOrUserCell)view).usePadding = false;
((ChatOrUserCell)view).useSeparator = true;
} }
ContactsActivity.ContactListRowHolder holder = (ContactsActivity.ContactListRowHolder)view.getTag();
if (holder == null) {
holder = new ContactsActivity.ContactListRowHolder(view);
view.setTag(holder);
}
View divider = view.findViewById(R.id.settings_row_divider);
divider.setVisibility(View.VISIBLE);
TLRPC.User user = MessagesController.Instance.users.get(blockedContacts.get(i).user_id); TLRPC.User user = MessagesController.Instance.users.get(blockedContacts.get(i).user_id);
((ChatOrUserCell)view).setData(user, null, null, null, user.phone != null && user.phone.length() != 0 ? PhoneFormat.Instance.format("+" + user.phone) : "Unknown");
TLRPC.FileLocation photo = null;
if (user.first_name.length() != 0 && user.last_name.length() != 0) {
holder.nameTextView.setText(Html.fromHtml(user.first_name + " <b>" + user.last_name + "</b>"));
} else if (user.first_name.length() != 0) {
holder.nameTextView.setText(Html.fromHtml("<b>" + user.first_name + "</b>"));
} else {
holder.nameTextView.setText(Html.fromHtml("<b>" + user.last_name + "</b>"));
}
if (user.photo != null) {
photo = user.photo.photo_small;
}
int placeHolderId = Utilities.getUserAvatarForId(user.id);
holder.avatarImage.setImage(photo, "50_50", placeHolderId);
holder.messageTextView.setTextColor(0xff808080);
if (user.phone != null && user.phone.length() != 0) {
holder.messageTextView.setText(PhoneFormat.Instance.format("+" + user.phone));
} else {
holder.messageTextView.setText("Unknown");
}
} else if (type == 1) { } else if (type == 1) {
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 file

@ -82,7 +82,7 @@ public class SettingsChangeNameActivity extends BaseFragment {
} }
}); });
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
boolean animations = preferences.getBoolean("view_animations", true); boolean animations = preferences.getBoolean("view_animations", true);
if (!animations) { if (!animations) {
firstNameField.requestFocus(); firstNameField.requestFocus();
@ -171,6 +171,9 @@ 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) {
return;
}
UserConfig.currentUser.first_name = req.first_name = firstNameField.getText().toString(); UserConfig.currentUser.first_name = req.first_name = firstNameField.getText().toString();
UserConfig.currentUser.last_name = req.last_name = lastNameField.getText().toString(); UserConfig.currentUser.last_name = req.last_name = lastNameField.getText().toString();
TLRPC.User user = MessagesController.Instance.users.get(UserConfig.clientUserId); TLRPC.User user = MessagesController.Instance.users.get(UserConfig.clientUserId);
@ -179,7 +182,7 @@ public class SettingsChangeNameActivity extends BaseFragment {
user.last_name = req.last_name; user.last_name = req.last_name;
} }
UserConfig.saveConfig(true); UserConfig.saveConfig(true);
NotificationCenter.Instance.postNotificationName(MessagesController.updateInterfaces, MessagesController.UPDATE_MASK_ALL); NotificationCenter.Instance.postNotificationName(MessagesController.updateInterfaces, MessagesController.UPDATE_MASK_NAME);
ConnectionsManager.Instance.performRpc(req, new RPCRequest.RPCRequestDelegate() { ConnectionsManager.Instance.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) {

View file

@ -34,6 +34,7 @@ import org.telegram.TL.TLObject;
import org.telegram.TL.TLRPC; import org.telegram.TL.TLRPC;
import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLog; import org.telegram.messenger.FileLog;
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;
@ -138,7 +139,7 @@ public class SettingsNotificationsActivity extends BaseFragment {
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
} }
} else if (i == 15) { } else if (i == 17) {
if (reseting) { if (reseting) {
return; return;
} }
@ -150,6 +151,7 @@ public class SettingsNotificationsActivity extends BaseFragment {
Utilities.RunOnUIThread(new Runnable() { Utilities.RunOnUIThread(new Runnable() {
@Override @Override
public void run() { public void run() {
MessagesController.Instance.enableJoined = true;
ActionBarActivity inflaterActivity = parentActivity; ActionBarActivity inflaterActivity = parentActivity;
if (inflaterActivity == null) { if (inflaterActivity == null) {
inflaterActivity = (ActionBarActivity)getActivity(); inflaterActivity = (ActionBarActivity)getActivity();
@ -190,6 +192,14 @@ public class SettingsNotificationsActivity extends BaseFragment {
editor.putBoolean("EnableInAppPreview", !enabled); editor.putBoolean("EnableInAppPreview", !enabled);
editor.commit(); editor.commit();
listView.invalidateViews(); listView.invalidateViews();
} else if (i == 15) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
boolean enabled = preferences.getBoolean("EnableContactJoined", true);
MessagesController.Instance.enableJoined = !enabled;
editor.putBoolean("EnableContactJoined", !enabled);
editor.commit();
listView.invalidateViews();
} }
} }
}); });
@ -318,12 +328,15 @@ public class SettingsNotificationsActivity extends BaseFragment {
public boolean isEnabled(int i) { public boolean isEnabled(int i) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
boolean enabledAll = preferences.getBoolean("EnableAll", true); boolean enabledAll = preferences.getBoolean("EnableAll", true);
return !(i != 1 && !enabledAll && i != 13) && (i > 0 && i < 5 || i > 5 && i < 10 || i > 10 && i < 14 || i == 15); if (i == 17 || i == 15) {
return true;
}
return !(i != 1 && !enabledAll && i != 13) && (i > 0 && i < 5 || i > 5 && i < 10 || i > 10 && i < 14);
} }
@Override @Override
public int getCount() { public int getCount() {
return 16; return 18;
} }
@Override @Override
@ -357,6 +370,8 @@ public class SettingsNotificationsActivity extends BaseFragment {
} else if (i == 10) { } else if (i == 10) {
textView.setText(getStringEntry(R.string.InAppNotifications)); textView.setText(getStringEntry(R.string.InAppNotifications));
} else if (i == 14) { } else if (i == 14) {
textView.setText(getStringEntry(R.string.Events));
} else if (i == 16) {
textView.setText(getStringEntry(R.string.Reset)); textView.setText(getStringEntry(R.string.Reset));
} }
} if (type == 1) { } if (type == 1) {
@ -408,13 +423,17 @@ public class SettingsNotificationsActivity extends BaseFragment {
enabled = preferences.getBoolean("EnableInAppPreview", true); enabled = preferences.getBoolean("EnableInAppPreview", true);
textView.setText(getStringEntry(R.string.InAppPreview)); textView.setText(getStringEntry(R.string.InAppPreview));
divider.setVisibility(View.INVISIBLE); divider.setVisibility(View.INVISIBLE);
} else if (i == 15) {
enabled = preferences.getBoolean("EnableContactJoined", true);
textView.setText(getStringEntry(R.string.ContactJoined));
divider.setVisibility(View.INVISIBLE);
} }
if (enabled) { if (enabled) {
checkButton.setImageResource(R.drawable.btn_check_on); checkButton.setImageResource(R.drawable.btn_check_on);
} else { } else {
checkButton.setImageResource(R.drawable.btn_check_off); checkButton.setImageResource(R.drawable.btn_check_off);
} }
if (i != 1 && !enabledAll) { if (i != 1 && !enabledAll && i != 15) {
view.setEnabled(false); view.setEnabled(false);
if(android.os.Build.VERSION.SDK_INT >= 11) { if(android.os.Build.VERSION.SDK_INT >= 11) {
checkButton.setAlpha(0.3f); checkButton.setAlpha(0.3f);
@ -455,12 +474,12 @@ public class SettingsNotificationsActivity extends BaseFragment {
} }
textView.setText(getStringEntry(R.string.Sound)); textView.setText(getStringEntry(R.string.Sound));
divider.setVisibility(View.INVISIBLE); divider.setVisibility(View.INVISIBLE);
} else if (i == 15) { } else if (i == 17) {
textView.setText(getStringEntry(R.string.ResetAllNotifications)); textView.setText(getStringEntry(R.string.ResetAllNotifications));
textViewDetail.setText(getStringEntry(R.string.UndoAllCustom)); textViewDetail.setText(getStringEntry(R.string.UndoAllCustom));
divider.setVisibility(View.INVISIBLE); divider.setVisibility(View.INVISIBLE);
} }
if (i != 15 && !enabledAll) { if (i != 17 && !enabledAll) {
view.setEnabled(false); view.setEnabled(false);
if(android.os.Build.VERSION.SDK_INT >= 11) { if(android.os.Build.VERSION.SDK_INT >= 11) {
textView.setAlpha(0.3f); textView.setAlpha(0.3f);
@ -482,9 +501,9 @@ public class SettingsNotificationsActivity extends BaseFragment {
@Override @Override
public int getItemViewType(int i) { public int getItemViewType(int i) {
if (i == 0 || i == 5 || i == 10 || i == 14) { if (i == 0 || i == 5 || i == 10 || i == 14 || i == 16) {
return 0; return 0;
} else if (i > 0 && i < 4 || i > 5 && i < 9 || i > 10 && i < 14) { } else if (i > 0 && i < 4 || i > 5 && i < 9 || i > 10 && i < 14 || i == 15) {
return 1; return 1;
} else { } else {
return 2; return 2;

View file

@ -73,7 +73,7 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica
NotificationCenter.Instance.addObserver(this, FileLoader.FileLoadProgressChanged); NotificationCenter.Instance.addObserver(this, FileLoader.FileLoadProgressChanged);
NotificationCenter.Instance.addObserver(this, MessagesStorage.wallpapersDidLoaded); NotificationCenter.Instance.addObserver(this, MessagesStorage.wallpapersDidLoaded);
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
selectedBackground = preferences.getInt("selectedBackground", 1000001); selectedBackground = preferences.getInt("selectedBackground", 1000001);
selectedColor = preferences.getInt("selectedColor", 0); selectedColor = preferences.getInt("selectedColor", 0);
MessagesStorage.Instance.getWallpapers(); MessagesStorage.Instance.getWallpapers();
@ -165,7 +165,7 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica
} }
if (done) { if (done) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit(); SharedPreferences.Editor editor = preferences.edit();
editor.putInt("selectedBackground", selectedBackground); editor.putInt("selectedBackground", selectedBackground);
editor.putInt("selectedColor", selectedColor); editor.putInt("selectedColor", selectedColor);

View file

@ -21,6 +21,7 @@ import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.provider.Settings; import android.provider.Settings;
import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.Menu; import android.view.Menu;
import android.view.MenuInflater; import android.view.MenuInflater;
@ -39,6 +40,7 @@ import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.TL.TLObject; import org.telegram.TL.TLObject;
import org.telegram.TL.TLRPC; import org.telegram.TL.TLRPC;
import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.FileLog; import org.telegram.messenger.FileLog;
import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage; import org.telegram.messenger.MessagesStorage;
@ -51,6 +53,8 @@ import org.telegram.ui.Views.BaseFragment;
import org.telegram.ui.Views.IdenticonView; import org.telegram.ui.Views.IdenticonView;
import org.telegram.ui.Views.OnSwipeTouchListener; import org.telegram.ui.Views.OnSwipeTouchListener;
import java.util.ArrayList;
public class UserProfileActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, MessagesActivity.MessagesActivityDelegate { public class UserProfileActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, MessagesActivity.MessagesActivityDelegate {
private ListView listView; private ListView listView;
private ListAdapter listAdapter; private ListAdapter listAdapter;
@ -104,7 +108,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
@Override @Override
public void onClick(View view) { public void onClick(View view) {
creatingChat = true; creatingChat = true;
MessagesController.Instance.startSecretChat(parentActivity, user_id); MessagesController.Instance.startSecretChat(parentActivity, MessagesController.Instance.users.get(user_id));
} }
}); });
if (dialog_id == 0) { if (dialog_id == 0) {
@ -282,8 +286,11 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
public void didReceivedNotification(int id, Object... args) { public void didReceivedNotification(int id, Object... args) {
if (id == MessagesController.updateInterfaces) { if (id == MessagesController.updateInterfaces) {
if (listView != null) { int mask = (Integer)args[0];
listView.invalidateViews(); if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0) {
if (listView != null) {
listView.invalidateViews();
}
} }
} else if (id == MessagesController.contactsDidLoaded) { } else if (id == MessagesController.contactsDidLoaded) {
if (parentActivity != null) { if (parentActivity != null) {
@ -409,16 +416,12 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
finishFragment(); finishFragment();
break; break;
case R.id.block_contact: { case R.id.block_contact: {
TLRPC.TL_contacts_block req = new TLRPC.TL_contacts_block();
TLRPC.User user = MessagesController.Instance.users.get(user_id); TLRPC.User user = MessagesController.Instance.users.get(user_id);
if (user instanceof TLRPC.TL_userForeign || user instanceof TLRPC.TL_userRequest) { if (user == null) {
req.id = new TLRPC.TL_inputUserForeign(); break;
req.id.access_hash = user.access_hash;
req.id.user_id = user_id;
} else {
req.id = new TLRPC.TL_inputUserContact();
req.id.user_id = user_id;
} }
TLRPC.TL_contacts_block req = new TLRPC.TL_contacts_block();
req.id = MessagesController.getInputUser(user);
TLRPC.TL_contactBlocked blocked = new TLRPC.TL_contactBlocked(); TLRPC.TL_contactBlocked blocked = new TLRPC.TL_contactBlocked();
blocked.user_id = user_id; blocked.user_id = user_id;
blocked.date = (int)(System.currentTimeMillis() / 1000); blocked.date = (int)(System.currentTimeMillis() / 1000);
@ -449,14 +452,51 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
((ApplicationActivity)parentActivity).presentFragment(fragment, "chat_select", false); ((ApplicationActivity)parentActivity).presentFragment(fragment, "chat_select", false);
break; break;
} }
case R.id.edit_contact: {
ContactAddActivity fragment = new ContactAddActivity();
Bundle args = new Bundle();
args.putInt("user_id", user_id);
fragment.setArguments(args);
((ApplicationActivity)parentActivity).presentFragment(fragment, "add_contact_" + user_id, false);
break;
}
case R.id.delete_contact: {
final TLRPC.User user = MessagesController.Instance.users.get(user_id);
if (user == null) {
break;
}
AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
builder.setMessage(getStringEntry(R.string.AreYouSure));
builder.setTitle(getStringEntry(R.string.AppName));
builder.setPositiveButton(getStringEntry(R.string.OK), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
TLRPC.TL_auth_resetAuthorizations req = new TLRPC.TL_auth_resetAuthorizations();
ConnectionsManager.Instance.performRpc(req, new RPCRequest.RPCRequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
ArrayList<TLRPC.User> arrayList = new ArrayList<TLRPC.User>();
arrayList.add(user);
ContactsController.Instance.deleteContact(arrayList);
}
}, null, true, RPCRequest.RPCRequestClassGeneric);
}
});
builder.setNegativeButton(getStringEntry(R.string.Cancel), null);
builder.show().setCanceledOnTouchOutside(true);
break;
}
} }
return true; return true;
} }
@Override @Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (MessagesController.Instance.contactsDict.get(user_id) == null) { if (ContactsController.Instance.contactsDict.get(user_id) == null) {
TLRPC.User user = MessagesController.Instance.users.get(user_id); TLRPC.User user = MessagesController.Instance.users.get(user_id);
if (user == null) {
return;
}
if (user.phone != null && user.phone.length() != 0) { if (user.phone != null && user.phone.length() != 0) {
inflater.inflate(R.menu.user_profile_menu, menu); inflater.inflate(R.menu.user_profile_menu, menu);
} else { } else {
@ -608,7 +648,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
if (value == 0) { if (value == 0) {
value = user.status.expires; value = user.status.expires;
} }
onlineText.setText(String.format("%s %s", getStringEntry(R.string.LastSeen), Utilities.formatDateOnline(value))); onlineText.setText(Utilities.formatDateOnline(value));
} }
} }
} }
@ -661,12 +701,19 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
} }
} else if (i == 0) { } else if (i == 0) {
ActionBarActivity inflaterActivity = parentActivity;
if (inflaterActivity == null) {
inflaterActivity = (ActionBarActivity)getActivity();
}
if (inflaterActivity == null) {
return;
}
int sdk = android.os.Build.VERSION.SDK_INT; int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) { if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager)parentActivity.getSystemService(Context.CLIPBOARD_SERVICE); android.text.ClipboardManager clipboard = (android.text.ClipboardManager)inflaterActivity.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(selectedPhone); clipboard.setText(selectedPhone);
} else { } else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager)parentActivity.getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipboardManager clipboard = (android.content.ClipboardManager)inflaterActivity.getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("label", selectedPhone); android.content.ClipData clip = android.content.ClipData.newPlainText("label", selectedPhone);
clipboard.setPrimaryClip(clip); clipboard.setPrimaryClip(clip);
} }

View file

@ -0,0 +1,169 @@
/*
* This is the source code of Telegram for Android v. 1.3.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.
*/
package org.telegram.ui.Views;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.View;
import org.telegram.TL.TLRPC;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.Utilities;
import java.lang.ref.WeakReference;
public class ImageReceiver {
private TLRPC.FileLocation last_path = null;
private String last_httpUrl = null;
private String last_filter = null;
private Drawable last_placeholder = null;
private int last_size = 0;
private String currentPath = null;
private boolean isPlaceholder = false;
private Drawable currentImage = null;
public Integer TAG = null;
public WeakReference<View> parentView = null;
public int imageX = 0, imageY = 0, imageW = 0, imageH = 0;
public void setImage(TLRPC.FileLocation path, String filter, Drawable placeholder) {
setImage(path, null, filter, placeholder, 0);
}
public void setImage(TLRPC.FileLocation path, String filter, Drawable placeholder, int size) {
setImage(path, null, filter, placeholder, size);
}
public void setImage(String path, String filter, Drawable placeholder) {
setImage(null, path, filter, placeholder, 0);
}
public void setImage(TLRPC.FileLocation path, String httpUrl, String filter, Drawable placeholder, int size) {
if ((path == null && httpUrl == null) || (path != null && !(path instanceof TLRPC.TL_fileLocation) && !(path instanceof TLRPC.TL_fileEncryptedLocation))) {
recycleBitmap(null);
currentPath = null;
isPlaceholder = true;
last_path = null;
last_httpUrl = null;
last_filter = null;
last_placeholder = placeholder;
last_size = 0;
currentImage = null;
FileLoader.Instance.cancelLoadingForImageView(this);
return;
}
String key;
if (path != null) {
key = path.volume_id + "_" + path.local_id;
} else {
key = Utilities.MD5(httpUrl);
}
if (filter != null) {
key += "@" + filter;
}
Bitmap img;
if (currentPath != null) {
if (currentPath.equals(key)) {
return;
} else {
img = FileLoader.Instance.getImageFromMemory(path, httpUrl, this, filter, true);
recycleBitmap(img);
}
} else {
img = FileLoader.Instance.getImageFromMemory(path, httpUrl, this, filter, true);
}
currentPath = key;
last_path = path;
last_httpUrl = httpUrl;
last_filter = filter;
last_placeholder = placeholder;
last_size = size;
if (img == null) {
isPlaceholder = true;
FileLoader.Instance.loadImage(path, httpUrl, this, filter, true, size);
} else {
setImageBitmap(img, currentPath);
}
}
public void setImageBitmap(Bitmap bitmap, String imgKey) {
if (currentPath == null || !imgKey.equals(currentPath)) {
return;
}
isPlaceholder = false;
FileLoader.Instance.incrementUseCount(currentPath);
currentImage = new BitmapDrawable(null, bitmap);
if (parentView.get() != null) {
if (imageW != 0) {
parentView.get().invalidate(imageX, imageY, imageX + imageW, imageY + imageH);
} else {
parentView.get().invalidate();
}
}
}
public void clearImage() {
recycleBitmap(null);
}
private void recycleBitmap(Bitmap newBitmap) {
if (currentImage == null || isPlaceholder) {
return;
}
if (currentImage instanceof BitmapDrawable) {
Bitmap bitmap = ((BitmapDrawable)currentImage).getBitmap();
if (bitmap != null && bitmap != newBitmap) {
if (currentPath != null) {
boolean canDelete = FileLoader.Instance.decrementUseCount(currentPath);
if (!FileLoader.Instance.isInCache(currentPath)) {
if (FileLoader.Instance.runtimeHack != null) {
FileLoader.Instance.runtimeHack.trackAlloc(bitmap.getRowBytes() * bitmap.getHeight());
}
if (canDelete) {
currentImage = null;
if (Build.VERSION.SDK_INT < 11) {
bitmap.recycle();
}
}
} else {
currentImage = null;
}
}
}
}
}
public void draw(Canvas canvas, int x, int y, int w, int h) {
try {
if (currentImage != null) {
currentImage.setBounds(x, y, x + w, y + h);
currentImage.draw(canvas);
} else if (last_placeholder != null) {
last_placeholder.setBounds(x, y, x + w, y + h);
last_placeholder.draw(canvas);
}
} catch (Exception e) {
if (currentPath != null) {
FileLoader.Instance.removeImage(currentPath);
currentPath = null;
}
setImage(last_path, last_httpUrl, last_filter, last_placeholder, last_size);
FileLog.e("tmessages", e);
}
}
@Override
protected void finalize() throws Throwable {
recycleBitmap(null);
super.finalize();
}
}

View file

@ -32,7 +32,6 @@ import org.telegram.messenger.Utilities;
import org.telegram.objects.MessageObject; import org.telegram.objects.MessageObject;
import org.telegram.ui.ApplicationLoader; import org.telegram.ui.ApplicationLoader;
import java.util.Locale;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
@ -52,7 +51,7 @@ public class NotificationView extends LinearLayout {
private int currentUserId = 0; private int currentUserId = 0;
private int currentEncId = 0; private int currentEncId = 0;
private boolean isVisible; private boolean isVisible;
private boolean isRTL = false; private final Integer timerSync = 1;
public NotificationView(Context context) { public NotificationView(Context context) {
super(context); super(context);
@ -78,9 +77,11 @@ public class NotificationView extends LinearLayout {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
try { try {
if (hideTimer != null) { synchronized (timerSync) {
hideTimer.cancel(); if (hideTimer != null) {
hideTimer = null; hideTimer.cancel();
hideTimer = null;
}
} }
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
@ -89,19 +90,15 @@ public class NotificationView extends LinearLayout {
} }
}); });
Locale locale = Locale.getDefault();
String lang = locale.getLanguage();
if (lang != null && lang.toLowerCase().equals("ar")) {
isRTL = true;
}
this.setOnClickListener(new OnClickListener() { this.setOnClickListener(new OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
try { try {
if (hideTimer != null) { synchronized (timerSync) {
hideTimer.cancel(); if (hideTimer != null) {
hideTimer = null; hideTimer.cancel();
hideTimer = null;
}
} }
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
@ -211,9 +208,11 @@ public class NotificationView extends LinearLayout {
avatarImage.setImage(photo, "50_50", Utilities.getUserAvatarForId(user.id)); avatarImage.setImage(photo, "50_50", Utilities.getUserAvatarForId(user.id));
try { try {
if (hideTimer != null) { synchronized (timerSync) {
hideTimer.cancel(); if (hideTimer != null) {
hideTimer = null; hideTimer.cancel();
hideTimer = null;
}
} }
hideTimer = new Timer(); hideTimer = new Timer();
hideTimer.schedule(new TimerTask() { hideTimer.schedule(new TimerTask() {
@ -226,8 +225,12 @@ public class NotificationView extends LinearLayout {
} }
}); });
try { try {
hideTimer.cancel(); synchronized (timerSync) {
hideTimer = null; if (hideTimer != null) {
hideTimer.cancel();
hideTimer = null;
}
}
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
} }
@ -251,9 +254,11 @@ public class NotificationView extends LinearLayout {
startAnimation(animHide); startAnimation(animHide);
} else { } else {
try { try {
if (hideTimer != null) { synchronized (timerSync) {
hideTimer.cancel(); if (hideTimer != null) {
hideTimer = null; hideTimer.cancel();
hideTimer = null;
}
} }
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
@ -300,7 +305,7 @@ public class NotificationView extends LinearLayout {
messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14); messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
nameTextView.setPadding(0, Utilities.dp(2), 0, 0); nameTextView.setPadding(0, Utilities.dp(2), 0, 0);
messageTextView.setPadding(0, Utilities.dp(18), 0, 0); messageTextView.setPadding(0, Utilities.dp(18), 0, 0);
if (isRTL) { if (Utilities.isRTL) {
params1.setMargins(Utilities.dp(40), 0, height + Utilities.dp(6), 0); params1.setMargins(Utilities.dp(40), 0, height + Utilities.dp(6), 0);
} else { } else {
params1.setMargins(height + Utilities.dp(6), 0, Utilities.dp(40), 0); params1.setMargins(height + Utilities.dp(6), 0, Utilities.dp(40), 0);
@ -310,7 +315,7 @@ public class NotificationView extends LinearLayout {
messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15); messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
nameTextView.setPadding(0, Utilities.dp(4), 0, 0); nameTextView.setPadding(0, Utilities.dp(4), 0, 0);
messageTextView.setPadding(0, Utilities.dp(24), 0, 0); messageTextView.setPadding(0, Utilities.dp(24), 0, 0);
if (isRTL) { if (Utilities.isRTL) {
params1.setMargins(Utilities.dp(40), 0, height + Utilities.dp(8), 0); params1.setMargins(Utilities.dp(40), 0, height + Utilities.dp(8), 0);
} else { } else {
params1.setMargins(height + Utilities.dp(8), 0, Utilities.dp(40), 0); params1.setMargins(height + Utilities.dp(8), 0, Utilities.dp(40), 0);

View file

@ -256,7 +256,7 @@ public class PagerSlidingTabStrip extends HorizontalScrollView {
}); });
tabsContainer.addView(tab); tabsContainer.addView(tab);
tab.setSelected(position == currentPosition);
} }
private void updateExpanded() { private void updateExpanded() {
@ -309,21 +309,6 @@ public class PagerSlidingTabStrip extends HorizontalScrollView {
int myWidth = getMeasuredWidth(); int myWidth = getMeasuredWidth();
tabsContainer.measure(MeasureSpec.EXACTLY | myWidth, heightMeasureSpec); tabsContainer.measure(MeasureSpec.EXACTLY | myWidth, heightMeasureSpec);
/*int childWidth = 0;
for (int i = 0; i < tabCount; i++) {
childWidth += tabsContainer.getChildAt(i).getMeasuredWidth();
}
if (!checkedTabWidths && childWidth > 0 && myWidth > 0) {
if (childWidth <= myWidth) {
for (int i = 0; i < tabCount; i++) {
tabsContainer.getChildAt(i).setLayoutParams(expandedTabLayoutParams);
}
}
checkedTabWidths = true;
}*/
} }
private void scrollToChild(int position, int offset) { private void scrollToChild(int position, int offset) {

View file

@ -94,6 +94,12 @@ public class TightTextView extends TextView {
} }
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
try {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
} catch (Exception e2) {
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec));
FileLog.e("tmessages", e2);
}
} }
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 952 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 967 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 709 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 715 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 464 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 475 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 812 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 848 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 688 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 722 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.7 KiB

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 343 B

After

Width:  |  Height:  |  Size: 296 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

View file

@ -0,0 +1,10 @@
<inset
xmlns:android="http://schemas.android.com/apk/res/android"
android:insetLeft="11dp"
android:insetRight="11dp">
<shape android:shape="rectangle">
<solid android:color="@color/divider"/>
</shape>
</inset>

View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/photocancel_pressed"
android:state_pressed="true" />
<item android:drawable="@drawable/photocancel" />
</selector>

View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/photoload_pressed"
android:state_pressed="true" />
<item android:drawable="@drawable/photoload" />
</selector>

View file

@ -2,13 +2,13 @@
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:layout_gravity="top"> android:layout_gravity="top">
<LinearLayout <LinearLayout
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical"> android:orientation="vertical">
<LinearLayout <LinearLayout
@ -97,7 +97,8 @@
android:paddingRight="15dp" android:paddingRight="15dp"
android:gravity="right" android:gravity="right"
android:textCursorDrawable="@null" android:textCursorDrawable="@null"
android:textColor="#000000"/> android:textColor="#000000"
android:layout_marginBottom="16dp"/>
</LinearLayout> </LinearLayout>

View file

@ -11,6 +11,8 @@
android:layout_alignParentBottom="true" android:layout_alignParentBottom="true"
android:clipToPadding="false" android:clipToPadding="false"
android:fadingEdge="none" android:fadingEdge="none"
android:divider="@drawable/messages_list_divider"
android:dividerHeight="1px"
android:fadingEdgeLength="0dp" android:fadingEdgeLength="0dp"
android:verticalScrollbarPosition="left"/> android:verticalScrollbarPosition="left"/>
@ -37,6 +39,7 @@
android:textColor="#959595" android:textColor="#959595"
android:text="@string/NoChats" android:text="@string/NoChats"
android:textSize="24dp" android:textSize="24dp"
android:gravity="center"
android:id="@+id/list_empty_view_text1"/> android:id="@+id/list_empty_view_text1"/>
<TextView android:layout_width="wrap_content" <TextView android:layout_width="wrap_content"

View file

@ -1,141 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="70dp"
android:paddingTop="8dp"
android:paddingLeft="11dp"
android:paddingRight="11dp"
android:layout_gravity="top">
<org.telegram.ui.Views.BackupImageView
android:layout_width="54dp"
android:layout_height="54dp"
android:id="@+id/messages_list_row_avatar"
android:contentDescription=""
android:layout_gravity="right"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/messages_list_row_name_layout"
android:orientation="horizontal"
android:layout_marginRight="66dp"
android:layout_gravity="top">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/messages_list_row_time"
android:textSize="14dp"
android:layout_marginTop="-2dp"
android:textColor="#9e9e9e"
android:lines="1"/>
<FrameLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginLeft="2dp"
android:layout_gravity="top">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/msg_clock"
android:id="@+id/messages_list_row_clock"
android:visibility="gone"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/dialogs_check"
android:id="@+id/messages_list_row_check"
android:visibility="gone"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/dialogs_halfcheck"
android:paddingLeft="5dp"
android:id="@+id/messages_list_row_check_half"
android:visibility="gone"/>
</FrameLayout>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/messages_list_row_name"
android:textSize="19dp"
android:textColor="#222222"
android:layout_marginLeft="3dp"
android:ellipsize="end"
android:layout_weight="1"
android:singleLine="false"
android:scrollHorizontally="true"
android:gravity="right"
android:maxLines="1"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="24dp"
android:orientation="horizontal"
android:layout_marginTop="28dp"
android:layout_marginRight="66dp"
android:layout_gravity="top">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/dialogs_warning"
android:layout_marginRight="8dp"
android:layout_gravity="center"
android:visibility="gone"
android:id="@+id/messages_list_row_error"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/messages_list_row_badge"
android:textSize="13dp"
android:gravity="center"
android:lines="1"
android:layout_gravity="center"
android:textColor="#ffffff"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:background="@drawable/dialogs_badge"
android:visibility="visible"
android:layout_marginLeft="8dp"/>
<FrameLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/messages_list_row_message"
android:textSize="16dp"
android:lines="1"
android:ellipsize="end"
android:textColor="#808080"
android:gravity="right"
android:layout_gravity="right"
android:layout_marginTop="2dp"/>
</FrameLayout>
</LinearLayout>
<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

@ -1,36 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="64dp"
android:layout_gravity="top">
<org.telegram.ui.Views.BackupImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="@+id/messages_list_row_avatar"
android:contentDescription=""
android:layout_marginTop="7dp"
android:layout_gravity="top|right"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/messages_list_row_name"
android:textSize="18dp"
android:layout_marginRight="61dp"
android:ellipsize="end"
android:maxLines="1"
android:textColor="#333333"
android:gravity="right"
android:layout_gravity="center_vertical|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

@ -1,51 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="64dp"
android:layout_gravity="top">
<org.telegram.ui.Views.BackupImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="@+id/messages_list_row_avatar"
android:contentDescription=""
android:layout_marginTop="7dp"
android:layout_gravity="top|right"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/messages_list_row_name"
android:textSize="18dp"
android:layout_marginRight="61dp"
android:ellipsize="end"
android:layout_marginTop="10dp"
android:maxLines="1"
android:gravity="right"
android:textColor="#333333"
android:layout_gravity="top|right"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/messages_list_row_message"
android:textSize="15dp"
android:maxLines="1"
android:ellipsize="end"
android:textColor="#999999"
android:layout_marginRight="61dp"
android:layout_marginTop="34dp"
android:gravity="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"
android:visibility="gone"/>
</FrameLayout>

View file

@ -18,7 +18,7 @@
android:id="@+id/settings_row_text" android:id="@+id/settings_row_text"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="fill_parent" android:layout_height="fill_parent"
android:layout_marginLeft="8dp" android:layout_marginLeft="104dp"
android:layout_marginRight="8dp" android:layout_marginRight="8dp"
android:gravity="center_vertical|right" android:gravity="center_vertical|right"
android:layout_gravity="top|right"/> android:layout_gravity="top|right"/>

View file

@ -18,7 +18,7 @@
android:id="@+id/settings_row_text" android:id="@+id/settings_row_text"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="fill_parent" android:layout_height="fill_parent"
android:layout_marginLeft="8dp" android:layout_marginLeft="104dp"
android:layout_marginRight="8dp" android:layout_marginRight="8dp"
android:gravity="center_vertical|right" android:gravity="center_vertical|right"
android:layout_gravity="top|right"/> android:layout_gravity="top|right"/>

View file

@ -40,8 +40,6 @@
android:id="@+id/chat_time_layout" android:id="@+id/chat_time_layout"
android:paddingLeft="3dp" android:paddingLeft="3dp"
android:paddingRight="3dp" android:paddingRight="3dp"
android:paddingBottom="1dp"
android:paddingTop="1dp"
android:layout_marginRight="8dp" android:layout_marginRight="8dp"
android:layout_marginBottom="8dp" android:layout_marginBottom="8dp"
android:layout_gravity="right|bottom" android:layout_gravity="right|bottom"

View file

@ -36,47 +36,78 @@
android:minWidth="100dp" android:minWidth="100dp"
android:id="@+id/chat_photo_image"/> android:id="@+id/chat_photo_image"/>
<LinearLayout <org.telegram.ui.Views.FrameLayoutFixed
android:layout_width="wrap_content" android:layout_height="40dp"
android:layout_height="16dp" android:layout_width="40dp"
android:id="@+id/chat_time_layout" android:id="@+id/chat_view_action_layout"
android:paddingLeft="3dp" android:layout_gravity="center"
android:paddingRight="3dp" android:visibility="visible">
android:paddingBottom="1dp"
android:paddingTop="1dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:layout_gravity="right|bottom"
android:background="@drawable/phototime">
<TextView <ImageView
android:layout_height="wrap_content" android:layout_width="40dp"
android:layout_height="40dp"
android:scaleType="centerInside"
android:id="@+id/chat_view_action_cancel_button"
android:src="@drawable/photo_download_states"
android:layout_gravity="center"
android:clickable="true"/>
</org.telegram.ui.Views.FrameLayoutFixed>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="16dp"
android:orientation="horizontal"
android:layout_marginLeft="10dp"
android:layout_marginBottom="10dp"
android:layout_marginRight="10dp"
android:layout_gravity="right|bottom"
android:gravity="right">
<org.telegram.ui.Views.FrameLayoutFixed
android:layout_width="0dp"
android:layout_height="16dp"
android:paddingLeft="6dp"
android:paddingRight="6dp"
android:paddingTop="1dp"
android:layout_marginRight="4dp"
android:background="@drawable/phototime"
android:id="@+id/photo_progress"
android:layout_weight="1">
<ProgressBar
android:layout_width="fill_parent"
android:layout_height="3dp"
android:layout_gravity="right|center_vertical"
android:progressDrawable="@drawable/photo_progress_chat"
style="?android:attr/progressBarStyleHorizontal"
android:progress="50"
android:id="@+id/chat_view_action_progress"
android:max="100"/>
</org.telegram.ui.Views.FrameLayoutFixed>
<LinearLayout
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:textColor="#ffffff" android:layout_height="16dp"
android:textSize="12dp" android:id="@+id/chat_time_layout"
android:layout_gravity="bottom" android:paddingLeft="3dp"
android:layout_marginBottom="1dp" android:paddingRight="3dp"
android:id="@+id/chat_time_text"/> android:background="@drawable/phototime">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textColor="#ffffff"
android:textSize="12dp"
android:layout_gravity="bottom"
android:layout_marginBottom="1dp"
android:id="@+id/chat_time_text"/>
</LinearLayout>
</LinearLayout> </LinearLayout>
</org.telegram.ui.Views.FrameLayoutFixed> </org.telegram.ui.Views.FrameLayoutFixed>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/ViewPhoto"
android:textColor="#54759e"
android:background="@drawable/chat_incoming_media_states"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:textStyle="bold"
android:id="@+id/chat_view_action_button"
android:textSize="14dp"
android:layout_gravity="center"
android:descendantFocusability="blocksDescendants"
android:clickable="true"
android:gravity="center"
android:layout_marginLeft="10dp"/>
</LinearLayout> </LinearLayout>

View file

@ -72,8 +72,6 @@
android:id="@+id/chat_time_layout" android:id="@+id/chat_time_layout"
android:paddingLeft="3dp" android:paddingLeft="3dp"
android:paddingRight="3dp" android:paddingRight="3dp"
android:paddingBottom="1dp"
android:paddingTop="1dp"
android:layout_marginRight="8dp" android:layout_marginRight="8dp"
android:layout_marginBottom="8dp" android:layout_marginBottom="8dp"
android:layout_gravity="right|bottom" android:layout_gravity="right|bottom"

View file

@ -33,8 +33,6 @@
android:id="@+id/chat_time_layout" android:id="@+id/chat_time_layout"
android:paddingLeft="3dp" android:paddingLeft="3dp"
android:paddingRight="3dp" android:paddingRight="3dp"
android:paddingBottom="1dp"
android:paddingTop="1dp"
android:layout_marginRight="8dp" android:layout_marginRight="8dp"
android:layout_marginBottom="8dp" android:layout_marginBottom="8dp"
android:layout_gravity="right|bottom" android:layout_gravity="right|bottom"

View file

@ -26,47 +26,78 @@
android:minWidth="100dp" android:minWidth="100dp"
android:id="@+id/chat_photo_image"/> android:id="@+id/chat_photo_image"/>
<LinearLayout <org.telegram.ui.Views.FrameLayoutFixed
android:layout_width="wrap_content" android:layout_height="40dp"
android:layout_height="16dp" android:layout_width="40dp"
android:id="@+id/chat_time_layout" android:id="@+id/chat_view_action_layout"
android:paddingLeft="3dp" android:layout_gravity="center"
android:paddingRight="3dp" android:visibility="visible">
android:paddingBottom="1dp"
android:paddingTop="1dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:layout_gravity="right|bottom"
android:background="@drawable/phototime">
<TextView <ImageView
android:layout_height="wrap_content" android:layout_width="40dp"
android:layout_height="40dp"
android:scaleType="centerInside"
android:id="@+id/chat_view_action_cancel_button"
android:src="@drawable/photo_download_states"
android:layout_gravity="center"
android:clickable="true"/>
</org.telegram.ui.Views.FrameLayoutFixed>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="16dp"
android:orientation="horizontal"
android:layout_marginLeft="10dp"
android:layout_marginBottom="10dp"
android:layout_marginRight="10dp"
android:layout_gravity="right|bottom"
android:gravity="right">
<org.telegram.ui.Views.FrameLayoutFixed
android:layout_width="0dp"
android:layout_height="16dp"
android:paddingLeft="6dp"
android:paddingRight="6dp"
android:paddingTop="1dp"
android:layout_marginRight="4dp"
android:background="@drawable/phototime"
android:id="@+id/photo_progress"
android:layout_weight="1">
<ProgressBar
android:layout_width="fill_parent"
android:layout_height="3dp"
android:layout_gravity="right|center_vertical"
android:progressDrawable="@drawable/photo_progress_chat"
style="?android:attr/progressBarStyleHorizontal"
android:progress="50"
android:id="@+id/chat_view_action_progress"
android:max="100"/>
</org.telegram.ui.Views.FrameLayoutFixed>
<LinearLayout
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:textColor="#ffffff" android:layout_height="16dp"
android:textSize="12dp" android:id="@+id/chat_time_layout"
android:layout_gravity="bottom" android:paddingLeft="3dp"
android:layout_marginBottom="1dp" android:paddingRight="3dp"
android:id="@+id/chat_time_text"/> android:background="@drawable/phototime">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textColor="#ffffff"
android:textSize="12dp"
android:layout_gravity="bottom"
android:layout_marginBottom="1dp"
android:id="@+id/chat_time_text"/>
</LinearLayout>
</LinearLayout> </LinearLayout>
</org.telegram.ui.Views.FrameLayoutFixed> </org.telegram.ui.Views.FrameLayoutFixed>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/ViewPhoto"
android:textColor="#54759e"
android:background="@drawable/chat_incoming_media_states"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:gravity="center"
android:layout_gravity="center"
android:textStyle="bold"
android:id="@+id/chat_view_action_button"
android:textSize="14dp"
android:layout_marginLeft="10dp"
android:descendantFocusability="blocksDescendants"
android:clickable="true"/>
</LinearLayout> </LinearLayout>

View file

@ -63,8 +63,6 @@
android:id="@+id/chat_time_layout" android:id="@+id/chat_time_layout"
android:paddingLeft="3dp" android:paddingLeft="3dp"
android:paddingRight="3dp" android:paddingRight="3dp"
android:paddingBottom="1dp"
android:paddingTop="1dp"
android:layout_marginRight="8dp" android:layout_marginRight="8dp"
android:layout_marginBottom="8dp" android:layout_marginBottom="8dp"
android:layout_gravity="right|bottom" android:layout_gravity="right|bottom"

View file

@ -51,8 +51,6 @@
android:id="@+id/chat_time_layout" android:id="@+id/chat_time_layout"
android:paddingLeft="3dp" android:paddingLeft="3dp"
android:paddingRight="3dp" android:paddingRight="3dp"
android:paddingBottom="1dp"
android:paddingTop="1dp"
android:layout_marginRight="8dp" android:layout_marginRight="8dp"
android:layout_marginBottom="8dp" android:layout_marginBottom="8dp"
android:layout_gravity="right|bottom" android:layout_gravity="right|bottom"

View file

@ -9,56 +9,6 @@
android:paddingBottom="1dp" android:paddingBottom="1dp"
android:paddingTop="1dp"> android:paddingTop="1dp">
<org.telegram.ui.Views.FrameLayoutFixed
android:layout_height="wrap_content"
android:layout_width="140dp"
android:layout_marginRight="10dp"
android:id="@+id/chat_view_action_layout"
android:layout_gravity="center"
android:visibility="gone">
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:scaleType="centerInside"
android:layout_marginLeft="4dp"
android:id="@+id/chat_view_action_cancel_button"
android:src="@drawable/ic_msg_btn_cross_custom"
android:layout_gravity="left|center"
android:clickable="true"/>
<ProgressBar
android:layout_width="fill_parent"
android:layout_height="3dp"
android:layout_gravity="right|center_vertical"
android:progressDrawable="@drawable/photo_progress_chat"
style="?android:attr/progressBarStyleHorizontal"
android:progress="50"
android:layout_marginLeft="36dp"
android:layout_marginRight="12dp"
android:id="@+id/chat_view_action_progress"
android:max="100"/>
</org.telegram.ui.Views.FrameLayoutFixed>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/ViewPhoto"
android:textColor="#54759e"
android:background="@drawable/chat_incoming_media_states"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:id="@+id/chat_view_action_button"
android:textSize="14dp"
android:layout_marginRight="10dp"
android:descendantFocusability="blocksDescendants"
android:clickable="true"
android:gravity="center"
android:textStyle="bold"
android:layout_gravity="center"
android:visibility="gone"/>
<org.telegram.ui.Views.FrameLayoutFixed <org.telegram.ui.Views.FrameLayoutFixed
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
@ -67,8 +17,8 @@
android:addStatesFromChildren="true"> android:addStatesFromChildren="true">
<org.telegram.ui.Views.BackupImageView <org.telegram.ui.Views.BackupImageView
android:layout_height="wrap_content" android:layout_height="100dp"
android:layout_width="wrap_content" android:layout_width="100dp"
android:layout_margin="6dp" android:layout_margin="6dp"
android:layout_gravity="top|left" android:layout_gravity="top|left"
android:scaleType="centerCrop" android:scaleType="centerCrop"
@ -76,47 +26,95 @@
android:minWidth="100dp" android:minWidth="100dp"
android:id="@+id/chat_photo_image"/> android:id="@+id/chat_photo_image"/>
<org.telegram.ui.Views.FrameLayoutFixed
android:layout_height="40dp"
android:layout_width="40dp"
android:id="@+id/chat_view_action_layout"
android:layout_gravity="center"
android:visibility="visible">
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:scaleType="centerInside"
android:id="@+id/chat_view_action_cancel_button"
android:src="@drawable/photo_download_cancel_states"
android:layout_gravity="center"
android:clickable="true"/>
</org.telegram.ui.Views.FrameLayoutFixed>
<LinearLayout <LinearLayout
android:layout_width="wrap_content" android:layout_width="fill_parent"
android:layout_height="16dp" android:layout_height="16dp"
android:id="@+id/chat_time_layout" android:orientation="horizontal"
android:paddingLeft="3dp" android:layout_marginLeft="10dp"
android:paddingRight="3dp" android:layout_marginBottom="10dp"
android:paddingBottom="1dp" android:layout_marginRight="10dp"
android:paddingTop="1dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:layout_gravity="right|bottom" android:layout_gravity="right|bottom"
android:background="@drawable/phototime"> android:gravity="right">
<TextView <org.telegram.ui.Views.FrameLayoutFixed
android:layout_height="wrap_content" android:layout_width="0dp"
android:layout_width="wrap_content" android:layout_height="16dp"
android:textColor="#ffffff" android:paddingLeft="6dp"
android:textSize="12dp" android:paddingRight="6dp"
android:layout_gravity="bottom" android:paddingTop="1dp"
android:layout_marginBottom="1dp" android:layout_marginRight="4dp"
android:id="@+id/chat_time_text"/> android:background="@drawable/phototime"
android:id="@+id/photo_progress"
android:layout_weight="1">
<ImageView <ProgressBar
android:layout_width="wrap_content" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_height="3dp"
android:src="@drawable/msg_check_w" android:layout_gravity="right|center_vertical"
android:layout_marginTop="1dp" android:progressDrawable="@drawable/photo_progress_chat"
android:layout_marginLeft="3dp" style="?android:attr/progressBarStyleHorizontal"
android:layout_marginRight="-8dp" android:progress="50"
android:id="@+id/chat_row_check" android:id="@+id/chat_view_action_progress"
android:visibility="visible" android:max="100"/>
android:layout_gravity="top"/>
<ImageView </org.telegram.ui.Views.FrameLayoutFixed>
<LinearLayout
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="16dp"
android:layout_marginTop="1dp" android:id="@+id/chat_time_layout"
android:id="@+id/chat_row_halfcheck" android:paddingLeft="3dp"
android:visibility="visible" android:paddingRight="3dp"
android:src="@drawable/msg_halfcheck_w" android:background="@drawable/phototime">
android:layout_gravity="top"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textColor="#ffffff"
android:textSize="12dp"
android:layout_gravity="bottom"
android:layout_marginBottom="1dp"
android:id="@+id/chat_time_text"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/msg_check_w"
android:layout_marginTop="2dp"
android:layout_marginLeft="3dp"
android:layout_marginRight="-8dp"
android:id="@+id/chat_row_check"
android:visibility="visible"
android:layout_gravity="top"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:id="@+id/chat_row_halfcheck"
android:visibility="visible"
android:src="@drawable/msg_halfcheck_w"
android:layout_gravity="top"/>
</LinearLayout>
</LinearLayout> </LinearLayout>

View file

@ -113,8 +113,6 @@
android:id="@+id/chat_time_layout" android:id="@+id/chat_time_layout"
android:paddingLeft="3dp" android:paddingLeft="3dp"
android:paddingRight="3dp" android:paddingRight="3dp"
android:paddingBottom="1dp"
android:paddingTop="1dp"
android:layout_marginRight="8dp" android:layout_marginRight="8dp"
android:layout_marginBottom="8dp" android:layout_marginBottom="8dp"
android:layout_gravity="right|bottom" android:layout_gravity="right|bottom"

View file

@ -2,14 +2,14 @@
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:layout_gravity="top"> android:layout_gravity="top">
<LinearLayout <LinearLayout
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:orientation="vertical"> android:orientation="vertical"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<LinearLayout <LinearLayout
android:gravity="center_vertical" android:gravity="center_vertical"
@ -90,7 +90,8 @@
android:paddingLeft="15dp" android:paddingLeft="15dp"
android:paddingRight="15dp" android:paddingRight="15dp"
android:textCursorDrawable="@null" android:textCursorDrawable="@null"
android:textColor="#000000"/> android:textColor="#000000"
android:layout_marginBottom="16dp"/>
</LinearLayout> </LinearLayout>

View file

@ -12,8 +12,8 @@
android:clipToPadding="false" android:clipToPadding="false"
android:fadingEdge="none" android:fadingEdge="none"
android:fadingEdgeLength="0dp" android:fadingEdgeLength="0dp"
android:divider="@null" android:divider="@drawable/messages_list_divider"
android:dividerHeight="0dp" android:dividerHeight="1px"
android:animationCache="false"/> android:animationCache="false"/>
<TextView android:layout_width="match_parent" <TextView android:layout_width="match_parent"
@ -34,10 +34,12 @@
android:gravity="center" android:gravity="center"
android:visibility="gone"> android:visibility="gone">
<TextView android:layout_width="wrap_content" <TextView
android:layout_width="wrap_content"
android:layout_height="match_parent" android:layout_height="match_parent"
android:textColor="#959595" android:textColor="#959595"
android:text="@string/NoChats" android:text="@string/NoChats"
android:gravity="center"
android:textSize="24dp" android:textSize="24dp"
android:id="@+id/list_empty_view_text1"/> android:id="@+id/list_empty_view_text1"/>

View file

@ -1,139 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="70dp"
android:paddingTop="8dp"
android:paddingLeft="11dp"
android:paddingRight="11dp"
android:layout_gravity="top">
<org.telegram.ui.Views.BackupImageView
android:layout_width="54dp"
android:layout_height="54dp"
android:id="@+id/messages_list_row_avatar"
android:contentDescription=""/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/messages_list_row_name_layout"
android:orientation="horizontal"
android:layout_marginLeft="66dp"
android:layout_gravity="top">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/messages_list_row_name"
android:textSize="19dp"
android:layout_marginRight="3dp"
android:ellipsize="end"
android:layout_weight="1"
android:singleLine="false"
android:scrollHorizontally="true"
android:gravity="left"
android:textColor="#222222"
android:maxLines="1"/>
<FrameLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginRight="2dp"
android:layout_gravity="top">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/msg_clock"
android:id="@+id/messages_list_row_clock"
android:visibility="gone"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/dialogs_check"
android:id="@+id/messages_list_row_check"
android:visibility="gone"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/dialogs_halfcheck"
android:paddingLeft="5dp"
android:id="@+id/messages_list_row_check_half"
android:visibility="gone"/>
</FrameLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/messages_list_row_time"
android:textSize="14dp"
android:layout_marginTop="-2dp"
android:textColor="#9e9e9e"
android:lines="1"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="24dp"
android:orientation="horizontal"
android:layout_marginTop="28dp"
android:layout_marginLeft="66dp"
android:layout_gravity="top">
<FrameLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/messages_list_row_message"
android:textSize="16dp"
android:lines="1"
android:ellipsize="end"
android:textColor="#808080"
android:gravity="left"
android:layout_marginTop="2dp"/>
</FrameLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/messages_list_row_badge"
android:textSize="13dp"
android:gravity="center"
android:lines="1"
android:layout_gravity="center"
android:textColor="#ffffff"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:background="@drawable/dialogs_badge"
android:visibility="visible"
android:layout_marginLeft="8dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/dialogs_warning"
android:layout_marginLeft="8dp"
android:layout_gravity="center"
android:visibility="gone"
android:id="@+id/messages_list_row_error"/>
</LinearLayout>
<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>

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