Merge branch 'dev'

This commit is contained in:
DrKLO 2014-07-21 01:54:18 +04:00
commit 331a0bb77e
150 changed files with 8591 additions and 4224 deletions

View File

@ -3,10 +3,10 @@ buildscript {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.11.+'
classpath 'com.android.tools.build:gradle:0.12.+'
}
}
apply plugin: 'android'
apply plugin: 'com.android.application'
repositories {
mavenCentral()
@ -20,13 +20,15 @@ dependencies {
compile 'com.android.support:support-v4:19.0.+'
compile 'com.google.android.gms:play-services:4.1.+'
compile 'net.hockeyapp.android:HockeySDK:3.0.1'
compile 'com.googlecode.mp4parser:isoparser:1.0.+'
}
android {
compileSdkVersion 19
buildToolsVersion '19.1.0'
aaptOptions.useAaptPngCruncher = true
useAaptPngCruncher = true
useOldManifestMerger true
signingConfigs {
debug {
@ -81,7 +83,7 @@ android {
defaultConfig {
minSdkVersion 8
targetSdkVersion 19
versionCode 267
versionName "1.5.7"
versionCode 288
versionName "1.6.1"
}
}

View File

@ -33,7 +33,7 @@
<activity android:name="net.hockeyapp.android.UpdateActivity" />
<receiver
android:name="org.telegram.messenger.GcmBroadcastReceiver"
android:name="org.telegram.android.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />

View File

@ -33,7 +33,7 @@
<activity android:name="net.hockeyapp.android.UpdateActivity" />
<receiver
android:name="org.telegram.messenger.GcmBroadcastReceiver"
android:name="org.telegram.android.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />

View File

@ -234,6 +234,7 @@ LOCAL_SRC_FILES += \
./audio.c \
./gif.c \
./utils.c \
./image.c
./image.c \
./fake.c
include $(BUILD_SHARED_LIBRARY)

View File

@ -504,7 +504,7 @@ int writeFrame(uint8_t *framePcmBytes, unsigned int frameByteCount) {
return 1;
}
JNIEXPORT int Java_org_telegram_messenger_MediaController_startRecord(JNIEnv *env, jclass class, jstring path) {
JNIEXPORT int Java_org_telegram_android_MediaController_startRecord(JNIEnv *env, jclass class, jstring path) {
const char *pathStr = (*env)->GetStringUTFChars(env, path, 0);
int result = initRecorder(pathStr);
@ -516,12 +516,12 @@ JNIEXPORT int Java_org_telegram_messenger_MediaController_startRecord(JNIEnv *en
return result;
}
JNIEXPORT int Java_org_telegram_messenger_MediaController_writeFrame(JNIEnv *env, jclass class, jobject frame, jint len) {
JNIEXPORT int Java_org_telegram_android_MediaController_writeFrame(JNIEnv *env, jclass class, jobject frame, jint len) {
jbyte *frameBytes = (*env)->GetDirectBufferAddress(env, frame);
return writeFrame(frameBytes, len);
}
JNIEXPORT void Java_org_telegram_messenger_MediaController_stopRecord(JNIEnv *env, jclass class) {
JNIEXPORT void Java_org_telegram_android_MediaController_stopRecord(JNIEnv *env, jclass class) {
cleanupRecorder();
}
@ -618,22 +618,22 @@ void fillBuffer(uint8_t *buffer, int capacity, int *args) {
}
}
JNIEXPORT jlong Java_org_telegram_messenger_MediaController_getTotalPcmDuration(JNIEnv *env, jclass class) {
JNIEXPORT jlong Java_org_telegram_android_MediaController_getTotalPcmDuration(JNIEnv *env, jclass class) {
return _totalPcmDuration;
}
JNIEXPORT void Java_org_telegram_messenger_MediaController_readOpusFile(JNIEnv *env, jclass class, jobject buffer, jint capacity, jintArray args) {
JNIEXPORT void Java_org_telegram_android_MediaController_readOpusFile(JNIEnv *env, jclass class, jobject buffer, jint capacity, jintArray args) {
jint *argsArr = (*env)->GetIntArrayElements(env, args, 0);
jbyte *bufferBytes = (*env)->GetDirectBufferAddress(env, buffer);
fillBuffer(bufferBytes, capacity, argsArr);
(*env)->ReleaseIntArrayElements(env, args, argsArr, 0);
}
JNIEXPORT int Java_org_telegram_messenger_MediaController_seekOpusFile(JNIEnv *env, jclass class, jfloat position) {
JNIEXPORT int Java_org_telegram_android_MediaController_seekOpusFile(JNIEnv *env, jclass class, jfloat position) {
return seekPlayer(position);
}
JNIEXPORT int Java_org_telegram_messenger_MediaController_openOpusFile(JNIEnv *env, jclass class, jstring path) {
JNIEXPORT int Java_org_telegram_android_MediaController_openOpusFile(JNIEnv *env, jclass class, jstring path) {
const char *pathStr = (*env)->GetStringUTFChars(env, path, 0);
int result = initPlayer(pathStr);
@ -645,11 +645,11 @@ JNIEXPORT int Java_org_telegram_messenger_MediaController_openOpusFile(JNIEnv *e
return result;
}
JNIEXPORT void Java_org_telegram_messenger_MediaController_closeOpusFile(JNIEnv *env, jclass class) {
JNIEXPORT void Java_org_telegram_android_MediaController_closeOpusFile(JNIEnv *env, jclass class) {
cleanupPlayer();
}
JNIEXPORT int Java_org_telegram_messenger_MediaController_isOpusFile(JNIEnv *env, jclass class, jstring path) {
JNIEXPORT int Java_org_telegram_android_MediaController_isOpusFile(JNIEnv *env, jclass class, jstring path) {
const char *pathStr = (*env)->GetStringUTFChars(env, path, 0);
int result = 0;

6
TMessagesProj/jni/fake.c Normal file
View File

@ -0,0 +1,6 @@
#include <stdio.h>
void fakeFunction() {
printf("some androids has buggy native loader, so i should check size of libs in java to know that native library is correct. So each changed native library should has diffrent size in different app versions. This function will increase lib size for few bytes :)");
printf("bla blablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablabla");
}

View File

@ -30,67 +30,21 @@ void JNI_OnUnload(JavaVM *vm, void *reserved) {
gifOnJNIUnload(vm, reserved);
}
JNIEXPORT jbyteArray Java_org_telegram_messenger_Utilities_aesIgeEncryption(JNIEnv *env, jclass class, jbyteArray _what, jbyteArray _key, jbyteArray _iv, jboolean encrypt, jboolean changeIv, jint l) {
unsigned char *what = (unsigned char *)(*env)->GetByteArrayElements(env, _what, NULL);
unsigned char *key = (unsigned char *)(*env)->GetByteArrayElements(env, _key, NULL);
unsigned char *__iv = (unsigned char *)(*env)->GetByteArrayElements(env, _iv, NULL);
unsigned char *iv = 0;
if (!changeIv) {
iv = (unsigned char *)malloc((*env)->GetArrayLength(env, _iv));
memcpy(iv, __iv, (*env)->GetArrayLength(env, _iv));
} else {
iv = __iv;
}
int len = l == 0 ? (*env)->GetArrayLength(env, _what) : l;
AES_KEY akey;
if (!encrypt) {
AES_set_decrypt_key(key, (*env)->GetArrayLength(env, _key) * 8, &akey);
AES_ige_encrypt(what, what, len, &akey, iv, AES_DECRYPT);
} else {
AES_set_encrypt_key(key, (*env)->GetArrayLength(env, _key) * 8, &akey);
AES_ige_encrypt(what, what, len, &akey, iv, AES_ENCRYPT);
}
(*env)->ReleaseByteArrayElements(env, _what, what, 0);
(*env)->ReleaseByteArrayElements(env, _key, key, JNI_ABORT);
if (!changeIv) {
(*env)->ReleaseByteArrayElements(env, _iv, __iv, JNI_ABORT);
free(iv);
} else {
(*env)->ReleaseByteArrayElements(env, _iv, __iv, 0);
}
return _what;
}
JNIEXPORT void Java_org_telegram_messenger_Utilities_aesIgeEncryption2(JNIEnv *env, jclass class, jobject _what, jbyteArray _key, jbyteArray _iv, jboolean encrypt, jboolean changeIv, jint l) {
jbyte *what = (*env)->GetDirectBufferAddress(env, _what);
unsigned char *key = (unsigned char *)(*env)->GetByteArrayElements(env, _key, NULL);
unsigned char *__iv = (unsigned char *)(*env)->GetByteArrayElements(env, _iv, NULL);
unsigned char *iv = 0;
if (!changeIv) {
iv = (unsigned char *)malloc((*env)->GetArrayLength(env, _iv));
memcpy(iv, __iv, (*env)->GetArrayLength(env, _iv));
} else {
iv = __iv;
}
JNIEXPORT void Java_org_telegram_messenger_Utilities_aesIgeEncryption(JNIEnv *env, jclass class, jobject buffer, jbyteArray key, jbyteArray iv, jboolean encrypt, int offset, int length) {
jbyte *what = (*env)->GetDirectBufferAddress(env, buffer) + offset;
unsigned char *keyBuff = (unsigned char *)(*env)->GetByteArrayElements(env, key, NULL);
unsigned char *ivBuff = (unsigned char *)(*env)->GetByteArrayElements(env, iv, NULL);
AES_KEY akey;
if (!encrypt) {
AES_set_decrypt_key(key, (*env)->GetArrayLength(env, _key) * 8, &akey);
AES_ige_encrypt(what, what, l, &akey, iv, AES_DECRYPT);
AES_set_decrypt_key(keyBuff, 32 * 8, &akey);
AES_ige_encrypt(what, what, length, &akey, ivBuff, AES_DECRYPT);
} else {
AES_set_encrypt_key(key, (*env)->GetArrayLength(env, _key) * 8, &akey);
AES_ige_encrypt(what, what, l, &akey, iv, AES_ENCRYPT);
}
(*env)->ReleaseByteArrayElements(env, _key, key, JNI_ABORT);
if (!changeIv) {
(*env)->ReleaseByteArrayElements(env, _iv, __iv, JNI_ABORT);
free(iv);
} else {
(*env)->ReleaseByteArrayElements(env, _iv, __iv, 0);
AES_set_encrypt_key(keyBuff, 32 * 8, &akey);
AES_ige_encrypt(what, what, length, &akey, ivBuff, AES_ENCRYPT);
}
(*env)->ReleaseByteArrayElements(env, key, keyBuff, JNI_ABORT);
(*env)->ReleaseByteArrayElements(env, iv, ivBuff, 0);
}
uint64_t gcd(uint64_t a, uint64_t b){

View File

@ -48,7 +48,7 @@ jstring Java_org_telegram_SQLite_SQLiteCursor_columnStringValue(JNIEnv *env, job
}
jbyteArray Java_org_telegram_SQLite_SQLiteCursor_columnByteArrayValue(JNIEnv *env, jobject object, int statementHandle, int columnIndex) {
sqlite3_stmt *handle = (sqlite3_stmt *)statementHandle;
sqlite3_stmt *handle = (sqlite3_stmt *)statementHandle;
void *buf = sqlite3_column_blob(handle, columnIndex);
int length = sqlite3_column_bytes(handle, columnIndex);
if (buf != 0 && length > 0) {
@ -58,3 +58,22 @@ jbyteArray Java_org_telegram_SQLite_SQLiteCursor_columnByteArrayValue(JNIEnv *en
}
return 0;
}
int Java_org_telegram_SQLite_SQLiteCursor_columnByteArrayLength(JNIEnv *env, jobject object, int statementHandle, int columnIndex) {
return sqlite3_column_bytes((sqlite3_stmt *)statementHandle, columnIndex);
}
int Java_org_telegram_SQLite_SQLiteCursor_columnByteBufferValue(JNIEnv *env, jobject object, int statementHandle, int columnIndex, jobject buffer) {
if (!buffer) {
return 0;
}
sqlite3_stmt *handle = (sqlite3_stmt *)statementHandle;
void *buf = sqlite3_column_blob(handle, columnIndex);
int length = sqlite3_column_bytes(handle, columnIndex);
if (buf != 0 && length > 0) {
jbyte *byteBuff = (*env)->GetDirectBufferAddress(env, buffer);
memcpy(byteBuff, buf, length);
return length;
}
return 0;
}

View File

@ -62,20 +62,14 @@ void Java_org_telegram_SQLite_SQLitePreparedStatement_finalize(JNIEnv *env, jobj
}
}
void Java_org_telegram_SQLite_SQLitePreparedStatement_bindByteArray(JNIEnv *env, jobject object, int statementHandle, int index, jbyteArray value) {
void Java_org_telegram_SQLite_SQLitePreparedStatement_bindByteBuffer(JNIEnv *env, jobject object, int statementHandle, int index, jobject value, int length) {
sqlite3_stmt *handle = (sqlite3_stmt *)statementHandle;
const void *buf = (*env)->GetByteArrayElements(env, value, 0);
int length = (*env)->GetArrayLength(env, value);
jbyte *buf = (*env)->GetDirectBufferAddress(env, value);
int errcode = sqlite3_bind_blob(handle, index, buf, length, SQLITE_STATIC);
if (SQLITE_OK != errcode) {
throw_sqlite3_exception(env, sqlite3_db_handle(handle), errcode);
}
if (buf != 0) {
(*env)->ReleaseByteArrayElements(env, value, buf, 0);
}
}
void Java_org_telegram_SQLite_SQLitePreparedStatement_bindString(JNIEnv *env, jobject object, int statementHandle, int index, jstring value) {

View File

@ -58,6 +58,7 @@
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.MULTIWINDOW_LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND"/>
@ -100,14 +101,23 @@
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:screenOrientation="portrait">
</activity>
<activity
android:name="org.telegram.ui.PopupNotificationActivity"
android:configChanges="keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:excludeFromRecents="true"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize|stateHidden"
android:taskAffinity=""
android:theme="@style/Theme.TMessages.PopupNotification">
</activity>
<receiver android:name="org.telegram.messenger.SmsListener">
<receiver android:name="org.telegram.android.SmsListener">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<service android:name="org.telegram.messenger.AuthenticatorService"
<service android:name="org.telegram.android.AuthenticatorService"
android:exported="true">
<intent-filter>
<action android:name="android.accounts.AccountAuthenticator"/>
@ -116,7 +126,7 @@
android:resource="@xml/auth"/>
</service>
<service android:name="org.telegram.messenger.ContactsSyncAdapterService"
<service android:name="org.telegram.android.ContactsSyncAdapterService"
android:exported="true">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
@ -127,15 +137,22 @@
android:resource="@xml/contacts" />
</service>
<service android:name="org.telegram.messenger.NotificationsService" android:enabled="true"/>
<service android:name="org.telegram.android.NotificationsService" android:enabled="true"/>
<receiver android:name="org.telegram.messenger.AppStartReceiver" android:enabled="true">
<receiver android:name="org.telegram.android.AppStartReceiver" android:enabled="true">
<intent-filter>
<action android:name="org.telegram.start" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<uses-library android:name="com.sec.android.app.multiwindow" android:required="false" />
<meta-data android:name="com.sec.android.support.multiwindow" android:value="true" />
<meta-data android:name="com.sec.android.multiwindow.DEFAULT_SIZE_W" android:value="632dp" />
<meta-data android:name="com.sec.android.multiwindow.DEFAULT_SIZE_H" android:value="598dp" />
<meta-data android:name="com.sec.android.multiwindow.MINIMUM_SIZE_W" android:value="632dp" />
<meta-data android:name="com.sec.android.multiwindow.MINIMUM_SIZE_H" android:value="598dp" />
</application>
</manifest>

View File

@ -10,6 +10,8 @@ package org.telegram.SQLite;
import org.telegram.messenger.FileLog;
import java.nio.ByteBuffer;
public class SQLiteCursor {
public static final int FIELD_TYPE_INT = 1;
@ -55,28 +57,21 @@ public class SQLiteCursor {
return columnByteArrayValue(preparedStatement.getStatementHandle(), columnIndex);
}
public int byteArrayLength(int columnIndex) throws SQLiteException {
checkRow();
return columnByteArrayLength(preparedStatement.getStatementHandle(), columnIndex);
}
public int byteBufferValue(int columnIndex, ByteBuffer buffer) throws SQLiteException {
checkRow();
return columnByteBufferValue(preparedStatement.getStatementHandle(), columnIndex, buffer);
}
public int getTypeOf(int columnIndex) throws SQLiteException {
checkRow();
return columnType(preparedStatement.getStatementHandle(), columnIndex);
}
public Object objectValue(int columnIndex) throws SQLiteException {
checkRow();
int type = columnType(preparedStatement.getStatementHandle(), columnIndex);
switch (type) {
case FIELD_TYPE_INT:
return intValue(columnIndex);
case FIELD_TYPE_BYTEARRAY:
return byteArrayValue(columnIndex);
case FIELD_TYPE_FLOAT:
return doubleValue(columnIndex);
case FIELD_TYPE_STRING:
return stringValue(columnIndex);
}
return null;
}
public boolean next() throws SQLiteException {
int res = preparedStatement.step(preparedStatement.getStatementHandle());
if(res == -1) {
@ -122,4 +117,6 @@ public class SQLiteCursor {
native double columnDoubleValue(int statementHandle, int columnIndex);
native String columnStringValue(int statementHandle, int columnIndex);
native byte[] columnByteArrayValue(int statementHandle, int columnIndex);
native int columnByteArrayLength(int statementHandle, int columnIndex);
native int columnByteBufferValue(int statementHandle, int columnIndex, ByteBuffer buffer);
}

View File

@ -10,6 +10,8 @@ package org.telegram.SQLite;
import org.telegram.messenger.FileLog;
import java.nio.ByteBuffer;
public class SQLitePreparedStatement {
private boolean isFinalized = false;
private int sqliteStatementHandle;
@ -26,35 +28,34 @@ public class SQLitePreparedStatement {
sqliteStatementHandle = prepare(db.getSQLiteHandle(), sql);
}
public SQLiteCursor query(Object[] args) throws SQLiteException {
if (args == null || args.length != queryArgsCount) {
throw new IllegalArgumentException();
}
checkFinalized();
public SQLiteCursor query(Object[] args) throws SQLiteException {
if (args == null || args.length != queryArgsCount) {
throw new IllegalArgumentException();
}
reset(sqliteStatementHandle);
checkFinalized();
int i = 1;
for (Object obj : args) {
if (obj == null) {
bindNull(sqliteStatementHandle, i);
} else if (obj instanceof Integer) {
bindInt(sqliteStatementHandle, i, (Integer)obj);
} else if (obj instanceof Double) {
bindDouble(sqliteStatementHandle, i, (Double)obj);
} else if (obj instanceof String) {
bindString(sqliteStatementHandle, i, (String)obj);
} else if (obj instanceof byte[]) {
bindByteArray(sqliteStatementHandle, i, (byte[])obj);
} else {
throw new IllegalArgumentException();
}
i++;
}
reset(sqliteStatementHandle);
return new SQLiteCursor(this);
}
int i = 1;
for (Object obj : args) {
if (obj == null) {
bindNull(sqliteStatementHandle, i);
} else if (obj instanceof Integer) {
bindInt(sqliteStatementHandle, i, (Integer)obj);
} else if (obj instanceof Double) {
bindDouble(sqliteStatementHandle, i, (Double)obj);
} else if (obj instanceof String) {
bindString(sqliteStatementHandle, i, (String)obj);
} else {
throw new IllegalArgumentException();
}
i++;
}
return new SQLiteCursor(this);
}
public int step() throws SQLiteException {
return step(sqliteStatementHandle);
@ -102,8 +103,8 @@ public class SQLitePreparedStatement {
bindDouble(sqliteStatementHandle, index, value);
}
public void bindByteArray(int index, byte[] value) throws SQLiteException {
bindByteArray(sqliteStatementHandle, index, value);
public void bindByteBuffer(int index, ByteBuffer value) throws SQLiteException {
bindByteBuffer(sqliteStatementHandle, index, value, value.limit());
}
public void bindString(int index, String value) throws SQLiteException {
@ -114,7 +115,7 @@ public class SQLitePreparedStatement {
bindLong(sqliteStatementHandle, index, value);
}
native void bindByteArray(int statementHandle, int index, byte[] value) throws SQLiteException;
native void bindByteBuffer(int statementHandle, int index, ByteBuffer value, int length) throws SQLiteException;
native void bindString(int statementHandle, int index, String value) throws SQLiteException;
native void bindInt(int statementHandle, int index, int value) throws SQLiteException;
native void bindLong(int statementHandle, int index, long value) throws SQLiteException;

View File

@ -0,0 +1,224 @@
/*
* This is the source code of Telegram for Android v. 1.4.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2014.
*/
package org.telegram.android;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Point;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Environment;
import android.view.Display;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import org.telegram.messenger.FileLog;
import org.telegram.ui.ApplicationLoader;
import java.io.File;
import java.util.Hashtable;
public class AndroidUtilities {
private static final Hashtable<String, Typeface> typefaceCache = new Hashtable<String, Typeface>();
private static int prevOrientation = -10;
private static boolean waitingForSms = false;
private static final Integer smsLock = 2;
public static int externalCacheNotAvailableState = 0;
public static int statusBarHeight = 0;
public static float density = 1;
public static Point displaySize = new Point();
static {
density = ApplicationLoader.applicationContext.getResources().getDisplayMetrics().density;
checkDisplaySize();
}
public static void lockOrientation(Activity activity) {
if (prevOrientation != -10) {
return;
}
try {
prevOrientation = activity.getRequestedOrientation();
WindowManager manager = (WindowManager)activity.getSystemService(Activity.WINDOW_SERVICE);
if (manager != null && manager.getDefaultDisplay() != null) {
int rotation = manager.getDefaultDisplay().getRotation();
int orientation = activity.getResources().getConfiguration().orientation;
if (rotation == Surface.ROTATION_270) {
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
if (Build.VERSION.SDK_INT >= 9) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
} else if (rotation == Surface.ROTATION_90) {
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
if (Build.VERSION.SDK_INT >= 9) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
} else if (rotation == Surface.ROTATION_0) {
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
} else {
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (Build.VERSION.SDK_INT >= 9) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
} else {
if (Build.VERSION.SDK_INT >= 9) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
public static void unlockOrientation(Activity activity) {
try {
if (prevOrientation != -10) {
activity.setRequestedOrientation(prevOrientation);
prevOrientation = -10;
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
public static Typeface getTypeface(String assetPath) {
synchronized (typefaceCache) {
if (!typefaceCache.containsKey(assetPath)) {
try {
Typeface t = Typeface.createFromAsset(ApplicationLoader.applicationContext.getAssets(), assetPath);
typefaceCache.put(assetPath, t);
} catch (Exception e) {
FileLog.e("Typefaces", "Could not get typeface '" + assetPath + "' because " + e.getMessage());
return null;
}
}
return typefaceCache.get(assetPath);
}
}
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 void showKeyboard(View view) {
if (view == null) {
return;
}
InputMethodManager inputManager = (InputMethodManager)view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
((InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(view, 0);
}
public static boolean isKeyboardShowed(View view) {
if (view == null) {
return false;
}
InputMethodManager inputManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
return inputManager.isActive(view);
}
public static void hideKeyboard(View view) {
if (view == null) {
return;
}
InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (!imm.isActive()) {
return;
}
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
public static File getCacheDir() {
if (externalCacheNotAvailableState == 1 || externalCacheNotAvailableState == 0 && Environment.getExternalStorageState().startsWith(Environment.MEDIA_MOUNTED)) {
externalCacheNotAvailableState = 1;
try {
File file = ApplicationLoader.applicationContext.getExternalCacheDir();
if (file != null) {
return file;
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
externalCacheNotAvailableState = 2;
try {
File file = ApplicationLoader.applicationContext.getCacheDir();
if (file != null) {
return file;
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
return new File("");
}
public static int dp(int value) {
return (int)(Math.max(1, density * value));
}
public static int dpf(float value) {
return (int)Math.ceil(density * value);
}
public static void checkDisplaySize() {
try {
WindowManager manager = (WindowManager)ApplicationLoader.applicationContext.getSystemService(Context.WINDOW_SERVICE);
if (manager != null) {
Display display = manager.getDefaultDisplay();
if (display != null) {
if(android.os.Build.VERSION.SDK_INT < 13) {
displaySize.set(display.getWidth(), display.getHeight());
} else {
display.getSize(displaySize);
}
FileLog.e("tmessages", "display size = " + displaySize.x + " " + displaySize.y);
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
}

View File

@ -6,12 +6,13 @@
* Copyright Nikolai Kudashov, 2013-2014.
*/
package org.telegram.messenger;
package org.telegram.android;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import org.telegram.messenger.Utilities;
import org.telegram.ui.ApplicationLoader;
public class AppStartReceiver extends BroadcastReceiver {

View File

@ -6,7 +6,7 @@
* Copyright Nikolai Kudashov, 2013.
*/
package org.telegram.messenger;
package org.telegram.android;
import android.accounts.AbstractAccountAuthenticator;
import android.accounts.Account;

View File

@ -6,7 +6,7 @@
* Copyright Nikolai Kudashov, 2013.
*/
package org.telegram.messenger;
package org.telegram.android;
import android.accounts.Account;
import android.accounts.AccountManager;
@ -20,6 +20,16 @@ import android.provider.ContactsContract;
import android.util.SparseArray;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.BuildVars;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.RPCRequest;
import org.telegram.messenger.TLObject;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
import org.telegram.ui.ApplicationLoader;
import java.util.ArrayList;
@ -151,6 +161,18 @@ public class ContactsController {
}
}
public void deleteAllAppAccounts() {
try {
AccountManager am = AccountManager.get(ApplicationLoader.applicationContext);
Account[] accounts = am.getAccountsByType("org.telegram.account");
for (Account c : accounts) {
am.removeAccount(c, null, null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void checkContacts() {
Utilities.globalQueue.postRunnable(new Runnable() {
@Override
@ -720,7 +742,7 @@ public class ContactsController {
});
}
}
}, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassCanCompress);
}, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassCanCompress);
}
} else {
Utilities.stageQueue.postRunnable(new Runnable() {
@ -815,7 +837,7 @@ public class ContactsController {
processLoadedContacts(res.contacts, res.users, 0);
}
}
}, null, true, RPCRequest.RPCRequestClassGeneric);
}, true, RPCRequest.RPCRequestClassGeneric);
}
}
@ -1540,7 +1562,7 @@ public class ContactsController {
}
});
}
}, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassCanCompress);
}, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassCanCompress);
}
public void deleteContact(final ArrayList<TLRPC.User> users) {
@ -1607,6 +1629,6 @@ public class ContactsController {
}
});
}
}, null, true, RPCRequest.RPCRequestClassGeneric);
}, true, RPCRequest.RPCRequestClassGeneric);
}
}

View File

@ -6,7 +6,7 @@
* Copyright Nikolai Kudashov, 2013.
*/
package org.telegram.messenger;
package org.telegram.android;
import android.accounts.Account;
import android.accounts.OperationCanceledException;
@ -19,6 +19,8 @@ import android.content.SyncResult;
import android.os.Bundle;
import android.os.IBinder;
import org.telegram.messenger.FileLog;
public class ContactsSyncAdapterService extends Service {
private static SyncAdapterImpl sSyncAdapter = null;

View File

@ -6,7 +6,7 @@
* Copyright Nikolai Kudashov, 2013.
*/
package org.telegram.messenger;
package org.telegram.android;
import java.io.File;
import java.io.InputStream;
@ -26,6 +26,9 @@ import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.Utilities;
import org.telegram.ui.ApplicationLoader;
public class Emoji {
@ -202,17 +205,17 @@ public class Emoji {
0x00000000D83DDD34L, 0x00000000D83DDD35L, 0x00000000D83DDD3BL, 0x00000000D83DDD36L, 0x00000000D83DDD37L, 0x00000000D83DDD38L, 0x00000000D83DDD39L}};
static {
if (Utilities.density <= 1.0f) {
if (AndroidUtilities.density <= 1.0f) {
emojiFullSize = 30;
} else if (Utilities.density <= 1.5f) {
} else if (AndroidUtilities.density <= 1.5f) {
emojiFullSize = 45;
} else if (Utilities.density <= 2.0f) {
} else if (AndroidUtilities.density <= 2.0f) {
emojiFullSize = 60;
} else {
emojiFullSize = 90;
}
drawImgSize = Utilities.dp(20);
bigImgSize = Utilities.dp(30);
drawImgSize = AndroidUtilities.dp(20);
bigImgSize = AndroidUtilities.dp(30);
for (int j = 1; j < data.length; j++) {
for (int i = 0; i < data[j].length; i++) {
@ -228,13 +231,13 @@ public class Emoji {
try {
float scale = 1.0f;
int imageResize = 1;
if (Utilities.density <= 1.0f) {
if (AndroidUtilities.density <= 1.0f) {
scale = 2.0f;
imageResize = 2;
} else if (Utilities.density <= 1.5f) {
} else if (AndroidUtilities.density <= 1.5f) {
scale = 3.0f;
imageResize = 2;
} else if (Utilities.density <= 2.0f) {
} else if (AndroidUtilities.density <= 2.0f) {
scale = 2.0f;
} else {
scale = 3.0f;
@ -466,7 +469,7 @@ public class Emoji {
public static class EmojiSpan extends ImageSpan {
private Paint.FontMetricsInt fontMetrics = null;
int size = Utilities.dp(20);
int size = AndroidUtilities.dp(20);
public EmojiSpan(Drawable d, int verticalAlignment, int s, Paint.FontMetricsInt original) {
super(d, verticalAlignment);
@ -474,7 +477,7 @@ public class Emoji {
if (original != null) {
size = Math.abs(fontMetrics.descent) + Math.abs(fontMetrics.ascent);
if (size == 0) {
size = Utilities.dp(20);
size = AndroidUtilities.dp(20);
}
}
}
@ -488,8 +491,8 @@ public class Emoji {
if (fontMetrics == null) {
int sz = super.getSize(paint, text, start, end, fm);
int offset = Utilities.dp(8);
int w = Utilities.dp(10);
int offset = AndroidUtilities.dp(8);
int w = AndroidUtilities.dp(10);
fm.top = -w - offset;
fm.bottom = w - offset;
fm.ascent = -w - offset;

View File

@ -5,7 +5,7 @@
*
* Copyright Nikolai Kudashov, 2013.
*/
package org.telegram.messenger;
package org.telegram.android;
import java.io.IOException;
import java.io.ObjectInputStream;

View File

@ -6,7 +6,7 @@
* Copyright Nikolai Kudashov, 2013.
*/
package org.telegram.messenger;
package org.telegram.android;
import android.app.Activity;
import android.content.BroadcastReceiver;
@ -14,6 +14,9 @@ import android.content.Context;
import android.content.Intent;
import org.json.JSONObject;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.Utilities;
import org.telegram.ui.ApplicationLoader;
public class GcmBroadcastReceiver extends BroadcastReceiver {

View File

@ -6,7 +6,7 @@
* Copyright Nikolai Kudashov, 2013-2014.
*/
package org.telegram.messenger;
package org.telegram.android;
import android.app.Activity;
import android.content.BroadcastReceiver;
@ -18,6 +18,11 @@ import android.content.res.Configuration;
import android.text.format.DateFormat;
import android.util.Xml;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.R;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.Utilities;
import org.telegram.ui.ApplicationLoader;
import org.xmlpull.v1.XmlPullParser;
@ -34,6 +39,13 @@ import java.util.TimeZone;
public class LocaleController {
static final int QUANTITY_OTHER = 0x0000;
static final int QUANTITY_ZERO = 0x0001;
static final int QUANTITY_ONE = 0x0002;
static final int QUANTITY_TWO = 0x0004;
static final int QUANTITY_FEW = 0x0008;
static final int QUANTITY_MANY = 0x0010;
public static boolean isRTL = false;
private static boolean is24HourFormat = false;
public static FastDateFormat formatterDay;
@ -44,8 +56,11 @@ public class LocaleController {
public static FastDateFormat chatDate;
public static FastDateFormat chatFullDate;
private HashMap<String, PluralRules> allRules = new HashMap<String, PluralRules>();
private Locale currentLocale;
private Locale systemDefaultLocale;
private PluralRules currentPluralRules;
private LocaleInfo currentLocaleInfo;
private LocaleInfo defaultLocalInfo;
private HashMap<String, String> localeValues = new HashMap<String, String>();
@ -113,6 +128,30 @@ public class LocaleController {
}
public LocaleController() {
addRules(new String[]{"bem", "brx", "da", "de", "el", "en", "eo", "es", "et", "fi", "fo", "gl", "he", "iw", "it", "nb",
"nl", "nn", "no", "sv", "af", "bg", "bn", "ca", "eu", "fur", "fy", "gu", "ha", "is", "ku",
"lb", "ml", "mr", "nah", "ne", "om", "or", "pa", "pap", "ps", "so", "sq", "sw", "ta", "te",
"tk", "ur", "zu", "mn", "gsw", "chr", "rm", "pt"}, new PluralRules_One());
addRules(new String[]{"cs", "sk"}, new PluralRules_Czech());
addRules(new String[]{"ff", "fr", "kab"}, new PluralRules_French());
addRules(new String[]{"hr", "ru", "sr", "uk", "be", "bs", "sh"}, new PluralRules_Balkan());
addRules(new String[]{"lv"}, new PluralRules_Latvian());
addRules(new String[]{"lt"}, new PluralRules_Lithuanian());
addRules(new String[]{"pl"}, new PluralRules_Polish());
addRules(new String[]{"ro", "mo"}, new PluralRules_Romanian());
addRules(new String[]{"sl"}, new PluralRules_Slovenian());
addRules(new String[]{"ar"}, new PluralRules_Arabic());
addRules(new String[]{"mk"}, new PluralRules_Macedonian());
addRules(new String[]{"cy"}, new PluralRules_Welsh());
addRules(new String[]{"br"}, new PluralRules_Breton());
addRules(new String[]{"lag"}, new PluralRules_Langi());
addRules(new String[]{"shi"}, new PluralRules_Tachelhit());
addRules(new String[]{"mt"}, new PluralRules_Maltese());
addRules(new String[]{"ga", "se", "sma", "smi", "smj", "smn", "sms"}, new PluralRules_Two());
addRules(new String[]{"ak", "am", "bh", "fil", "tl", "guw", "hi", "ln", "mg", "nso", "ti", "wa"}, new PluralRules_Zero());
addRules(new String[]{"az", "bm", "fa", "ig", "hu", "ja", "kde", "kea", "ko", "my", "ses", "sg", "to",
"tr", "vi", "wo", "yo", "zh", "bo", "dz", "id", "jv", "ka", "km", "kn", "ms", "th"}, new PluralRules_None());
LocaleInfo localeInfo = new LocaleInfo();
localeInfo.name = "English";
localeInfo.nameEnglish = "English";
@ -215,6 +254,9 @@ public class LocaleController {
if (currentInfo == null && systemDefaultLocale.getLanguage() != null) {
currentInfo = languagesDict.get(systemDefaultLocale.getLanguage());
}
if (currentInfo == null) {
currentInfo = languagesDict.get(getLocaleString(systemDefaultLocale));
}
if (currentInfo == null) {
currentInfo = languagesDict.get("en");
}
@ -231,6 +273,52 @@ public class LocaleController {
}
}
private void addRules(String[] languages, PluralRules rules) {
for (String language : languages) {
allRules.put(language, rules);
}
}
private String stringForQuantity(int quantity) {
switch (quantity) {
case QUANTITY_ZERO:
return "zero";
case QUANTITY_ONE:
return "one";
case QUANTITY_TWO:
return "two";
case QUANTITY_FEW:
return "few";
case QUANTITY_MANY:
return "many";
default:
return "other";
}
}
private String getLocaleString(Locale locale) {
if (locale == null) {
return "";
}
String languageCode = locale.getLanguage();
String countryCode = locale.getCountry();
String variantCode = locale.getVariant();
if (languageCode.length() == 0 && countryCode.length() == 0) {
return "";
}
StringBuilder result = new StringBuilder(11);
result.append(languageCode);
if (countryCode.length() > 0 || variantCode.length() > 0) {
result.append('_');
}
result.append(countryCode);
if (variantCode.length() > 0) {
result.append('_');
}
result.append(variantCode);
return result.toString();
}
public boolean applyLanguageFile(File file) {
try {
HashMap<String, String> stringMap = getLocaleFileStrings(file);
@ -430,6 +518,7 @@ public class LocaleController {
}
currentLocale = newLocale;
currentLocaleInfo = localeInfo;
currentPluralRules = allRules.get(currentLocale.getLanguage());
changingConfiguration = true;
Locale.setDefault(currentLocale);
android.content.res.Configuration config = new android.content.res.Configuration();
@ -460,6 +549,16 @@ public class LocaleController {
return value;
}
public static String formatPluralString(String key, int plural) {
if (key == null || key.length() == 0 || getInstance().currentPluralRules == null) {
return "LOC_ERR:" + key;
}
String param = getInstance().stringForQuantity(getInstance().currentPluralRules.quantityForNumber(plural));
param = key + "_" + param;
int resourceId = ApplicationLoader.applicationContext.getResources().getIdentifier(param, "string", ApplicationLoader.applicationContext.getPackageName());
return formatString(param, resourceId, plural);
}
public static String formatString(String key, int res, Object... args) {
String value = getInstance().localeValues.get(key);
if (value == null) {
@ -509,6 +608,7 @@ public class LocaleController {
recreateFormatters();
}
currentLocale = newLocale;
currentPluralRules = allRules.get(currentLocale.getLanguage());
}
}
}
@ -645,4 +745,253 @@ public class LocaleController {
}
}
}
abstract public static class PluralRules {
abstract int quantityForNumber(int n);
}
public static class PluralRules_Zero extends PluralRules {
public int quantityForNumber(int count) {
if (count == 0 || count == 1) {
return QUANTITY_ONE;
} else {
return QUANTITY_OTHER;
}
}
}
public static class PluralRules_Welsh extends PluralRules {
public int quantityForNumber(int count) {
if (count == 0) {
return QUANTITY_ZERO;
} else if (count == 1) {
return QUANTITY_ONE;
} else if (count == 2) {
return QUANTITY_TWO;
} else if (count == 3) {
return QUANTITY_FEW;
} else if (count == 6) {
return QUANTITY_MANY;
} else {
return QUANTITY_OTHER;
}
}
}
public static class PluralRules_Two extends PluralRules {
public int quantityForNumber(int count) {
if (count == 1) {
return QUANTITY_ONE;
} else if (count == 2) {
return QUANTITY_TWO;
} else {
return QUANTITY_OTHER;
}
}
}
public static class PluralRules_Tachelhit extends PluralRules {
public int quantityForNumber(int count) {
if (count >= 0 && count <= 1) {
return QUANTITY_ONE;
} else if (count >= 2 && count <= 10) {
return QUANTITY_FEW;
} else {
return QUANTITY_OTHER;
}
}
}
public static class PluralRules_Slovenian extends PluralRules {
public int quantityForNumber(int count) {
int rem100 = count % 100;
if (rem100 == 1) {
return QUANTITY_ONE;
} else if (rem100 == 2) {
return QUANTITY_TWO;
} else if (rem100 >= 3 && rem100 <= 4) {
return QUANTITY_FEW;
} else {
return QUANTITY_OTHER;
}
}
}
public static class PluralRules_Romanian extends PluralRules {
public int quantityForNumber(int count) {
int rem100 = count % 100;
if (count == 1) {
return QUANTITY_ONE;
} else if ((count == 0 || (rem100 >= 1 && rem100 <= 19))) {
return QUANTITY_FEW;
} else {
return QUANTITY_OTHER;
}
}
}
public static class PluralRules_Polish extends PluralRules {
public int quantityForNumber(int count) {
int rem100 = count % 100;
int rem10 = count % 10;
if (count == 1) {
return QUANTITY_ONE;
} else if (rem10 >= 2 && rem10 <= 4 && !(rem100 >= 12 && rem100 <= 14) && !(rem100 >= 22 && rem100 <= 24)) {
return QUANTITY_FEW;
} else {
return QUANTITY_OTHER;
}
}
}
public static class PluralRules_One extends PluralRules {
public int quantityForNumber(int count) {
return count == 1 ? QUANTITY_ONE : QUANTITY_OTHER;
}
}
public static class PluralRules_None extends PluralRules {
public int quantityForNumber(int count) {
return QUANTITY_OTHER;
}
}
public static class PluralRules_Maltese extends PluralRules {
public int quantityForNumber(int count) {
int rem100 = count % 100;
if (count == 1) {
return QUANTITY_ONE;
} else if (count == 0 || (rem100 >= 2 && rem100 <= 10)) {
return QUANTITY_FEW;
} else if (rem100 >= 11 && rem100 <= 19) {
return QUANTITY_MANY;
} else {
return QUANTITY_OTHER;
}
}
}
public static class PluralRules_Macedonian extends PluralRules {
public int quantityForNumber(int count) {
if (count % 10 == 1 && count != 11) {
return QUANTITY_ONE;
} else {
return QUANTITY_OTHER;
}
}
}
public static class PluralRules_Lithuanian extends PluralRules {
public int quantityForNumber(int count) {
int rem100 = count % 100;
int rem10 = count % 10;
if (rem10 == 1 && !(rem100 >= 11 && rem100 <= 19)) {
return QUANTITY_ONE;
} else if (rem10 >= 2 && rem10 <= 9 && !(rem100 >= 11 && rem100 <= 19)) {
return QUANTITY_FEW;
} else {
return QUANTITY_OTHER;
}
}
}
public static class PluralRules_Latvian extends PluralRules {
public int quantityForNumber(int count) {
if (count == 0) {
return QUANTITY_ZERO;
} else if (count % 10 == 1 && count % 100 != 11) {
return QUANTITY_ONE;
} else {
return QUANTITY_OTHER;
}
}
}
public static class PluralRules_Langi extends PluralRules {
public int quantityForNumber(int count) {
if (count == 0) {
return QUANTITY_ZERO;
} else if (count > 0 && count < 2) {
return QUANTITY_ONE;
} else {
return QUANTITY_OTHER;
}
}
}
public static class PluralRules_French extends PluralRules {
public int quantityForNumber(int count) {
if (count >= 0 && count < 2) {
return QUANTITY_ONE;
} else {
return QUANTITY_OTHER;
}
}
}
public static class PluralRules_Czech extends PluralRules {
public int quantityForNumber(int count) {
if (count == 1) {
return QUANTITY_ONE;
} else if (count >= 2 && count <= 4) {
return QUANTITY_FEW;
} else {
return QUANTITY_OTHER;
}
}
}
public static class PluralRules_Breton extends PluralRules {
public int quantityForNumber(int count) {
if (count == 0) {
return QUANTITY_ZERO;
} else if (count == 1) {
return QUANTITY_ONE;
} else if (count == 2) {
return QUANTITY_TWO;
} else if (count == 3) {
return QUANTITY_FEW;
} else if (count == 6) {
return QUANTITY_MANY;
} else {
return QUANTITY_OTHER;
}
}
}
public static class PluralRules_Balkan extends PluralRules {
public int quantityForNumber(int count) {
int rem100 = count % 100;
int rem10 = count % 10;
if (rem10 == 1 && rem100 != 11) {
return QUANTITY_ONE;
} else if (rem10 >= 2 && rem10 <= 4 && !(rem100 >= 12 && rem100 <= 14)) {
return QUANTITY_FEW;
} else if ((rem10 == 0 || (rem10 >= 5 && rem10 <= 9) || (rem100 >= 11 && rem100 <= 14))) {
return QUANTITY_MANY;
} else {
return QUANTITY_OTHER;
}
}
}
public static class PluralRules_Arabic extends PluralRules {
public int quantityForNumber(int count) {
int rem100 = count % 100;
if (count == 0) {
return QUANTITY_ZERO;
} else if (count == 1) {
return QUANTITY_ONE;
} else if (count == 2) {
return QUANTITY_TWO;
} else if (rem100 >= 3 && rem100 <= 10) {
return QUANTITY_FEW;
} else if (rem100 >= 11 && rem100 <= 99) {
return QUANTITY_MANY;
} else {
return QUANTITY_OTHER;
}
}
}
}

View File

@ -6,7 +6,7 @@
* Copyright Nikolai Kudashov, 2013-2014.
*/
package org.telegram.messenger;
package org.telegram.android;
import android.app.ProgressDialog;
import android.content.Context;
@ -18,7 +18,6 @@ import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.audiofx.AutomaticGainControl;
import android.net.Uri;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
@ -26,6 +25,15 @@ import android.os.Vibrator;
import android.provider.MediaStore;
import android.view.View;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.DispatchQueue;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
import org.telegram.objects.MessageObject;
import org.telegram.ui.ApplicationLoader;
import org.telegram.ui.Cells.ChatMediaCell;
@ -129,6 +137,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
public final static int recordStopped = 50006;
public final static int screenshotTook = 50007;
public final static int albumsDidLoaded = 50008;
public final static int audioDidSent = 50009;
private HashMap<String, ArrayList<WeakReference<FileDownloadProgressListener>>> loadingFileObservers = new HashMap<String, ArrayList<WeakReference<FileDownloadProgressListener>>>();
private HashMap<Integer, String> observersByTag = new HashMap<Integer, String>();
@ -155,7 +164,6 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
private final Integer progressTimerSync = 1;
private AudioRecord audioRecorder = null;
private Object audioGainObj = null;
private TLRPC.TL_audio recordingAudio = null;
private File recordingAudioFile = null;
private long recordStartTime;
@ -497,7 +505,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
Thread.sleep(1000);
}
if (bitmapRegionDecoder != null) {
Bitmap bitmap = bitmapRegionDecoder.decodeRegion(new Rect(0, 0, Utilities.dp(44), Utilities.dp(44)), null);
Bitmap bitmap = bitmapRegionDecoder.decodeRegion(new Rect(0, 0, AndroidUtilities.dp(44), AndroidUtilities.dp(44)), null);
int w = bitmap.getWidth();
int h = bitmap.getHeight();
for (int y = 0; y < h; y++) {
@ -869,7 +877,9 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
if (currentTotalPcmDuration * progress == currentTotalPcmDuration) {
return;
}
audioTrackPlayer.pause();
if (!isPaused) {
audioTrackPlayer.pause();
}
audioTrackPlayer.flush();
fileDecodingQueue.postRunnable(new Runnable() {
@Override
@ -882,14 +892,15 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
ignoreFirstProgress = 3;
//audioTrackPlayer.setNotificationMarkerPosition((int)(currentTotalPcmDuration * (1 - playingMessageObject.audioProgress)));
lastPlayPcm = (long)(currentTotalPcmDuration * progress);
if (audioTrackPlayer != null) {
audioTrackPlayer.play();
if (!isPaused) {
ignoreFirstProgress = 3;
lastPlayPcm = (long) (currentTotalPcmDuration * progress);
if (audioTrackPlayer != null) {
audioTrackPlayer.play();
}
lastProgress = (int) (currentTotalPcmDuration / 48.0f * progress);
checkPlayerQueue();
}
lastProgress = (int)(currentTotalPcmDuration / 48.0f * progress);
checkPlayerQueue();
}
});
}
@ -926,7 +937,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
return true;
}
clenupPlayer(true);
final File cacheFile = new File(Utilities.getCacheDir(), messageObject.getFileName());
final File cacheFile = new File(AndroidUtilities.getCacheDir(), messageObject.getFileName());
if (isOpusFile(cacheFile.getAbsolutePath()) == 1) {
synchronized (playerObjectSync) {
@ -1144,10 +1155,11 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
recordingAudio.dc_id = Integer.MIN_VALUE;
recordingAudio.id = UserConfig.lastLocalId;
recordingAudio.user_id = UserConfig.getClientUserId();
recordingAudio.mime_type = "audio/ogg";
UserConfig.lastLocalId--;
UserConfig.saveConfig(false);
recordingAudioFile = new File(Utilities.getCacheDir(), MessageObject.getAttachFileName(recordingAudio));
recordingAudioFile = new File(AndroidUtilities.getCacheDir(), MessageObject.getAttachFileName(recordingAudio));
try {
if (startRecord(recordingAudioFile.getAbsolutePath()) == 0) {
@ -1165,31 +1177,6 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
recordDialogId = dialog_id;
fileBuffer.rewind();
if (android.os.Build.VERSION.SDK_INT >= 16) {
File f = new File("/vendor/lib/libaudioeffect_jni.so");
File f2 = new File("/system/lib/libaudioeffect_jni.so");
if (f.exists() || f2.exists()) {
AutomaticGainControl agc = null;
try {
if (AutomaticGainControl.isAvailable()) {
agc = AutomaticGainControl.create(audioRecorder.getAudioSessionId());
agc.setEnabled(true);
audioGainObj = agc;
}
} catch (Exception e) {
try {
if (agc != null) {
agc.release();
agc = null;
}
} catch (Exception e2) {
FileLog.e("tmessages", e2);
}
FileLog.e("tmessages", e);
}
}
}
audioRecorder.startRecording();
} catch (Exception e) {
FileLog.e("tmessages", e);
@ -1204,18 +1191,6 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
FileLog.e("tmessages", e2);
}
if (android.os.Build.VERSION.SDK_INT >= 16 && audioGainObj != null) {
AutomaticGainControl agc = (AutomaticGainControl)audioGainObj;
try {
if (agc != null) {
agc.release();
agc = null;
}
} catch (Exception e2) {
FileLog.e("tmessages", e2);
}
}
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
@ -1257,6 +1232,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
} else {
recordingAudioFileToSend.delete();
}
NotificationCenter.getInstance().postNotificationName(audioDidSent);
}
});
}
@ -1267,17 +1243,6 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
audioRecorder.release();
audioRecorder = null;
}
if (android.os.Build.VERSION.SDK_INT >= 16 && audioGainObj != null) {
AutomaticGainControl agc = (AutomaticGainControl)audioGainObj;
try {
if (agc != null) {
agc.release();
agc = null;
}
} catch (Exception e2) {
FileLog.e("tmessages", e2);
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
@ -1292,7 +1257,6 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
if (audioRecorder == null) {
return;
}
//recordTimeCount = System.currentTimeMillis() - recordStartTime;
try {
sendAfterDone = send;
audioRecorder.stop();
@ -1334,7 +1298,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
}
}
if (file == null) {
file = new File(Utilities.getCacheDir(), path);
file = new File(AndroidUtilities.getCacheDir(), path);
}
final File sourceFile = file;
@ -1466,7 +1430,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
}
}
if (cacheFile == null) {
cacheFile = new File(Utilities.getCacheDir(), messageObject.getFileName());
cacheFile = new File(AndroidUtilities.getCacheDir(), messageObject.getFileName());
}
try {
currentGifDrawable = new GifDrawable(cacheFile);
@ -1545,7 +1509,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
UserConfig.lastLocalId--;
parcelFD = ApplicationLoader.applicationContext.getContentResolver().openFileDescriptor(uri, "r");
input = new FileInputStream(parcelFD.getFileDescriptor());
File f = new File(Utilities.getCacheDir(), String.format(Locale.US, "%d.%s", id, ext));
File f = new File(AndroidUtilities.getCacheDir(), String.format(Locale.US, "%d.%s", id, ext));
output = new FileOutputStream(f);
input.getChannel().transferTo(0, input.getChannel().size(), output.getChannel());
UserConfig.saveConfig(false);

View File

@ -6,12 +6,14 @@
* Copyright Nikolai Kudashov, 2013-2014.
*/
package org.telegram.messenger;
package org.telegram.android;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.os.Build;
import org.telegram.messenger.FileLog;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
@ -22,9 +24,9 @@ import java.util.zip.ZipFile;
public class NativeLoader {
private static final long sizes[] = new long[] {
795280, //armeabi
844452, //armeabi-v7a
1242164, //x86
799376, //armeabi
848548, //armeabi-v7a
1246260, //x86
0, //mips
};

View File

@ -0,0 +1,672 @@
/*
* This is the source code of Telegram for Android v. 1.4.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2014.
*/
package org.telegram.android;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;
import org.json.JSONArray;
import org.json.JSONObject;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
import org.telegram.objects.MessageObject;
import org.telegram.ui.ApplicationLoader;
import org.telegram.ui.LaunchActivity;
import org.telegram.ui.PopupNotificationActivity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class NotificationsController {
private ArrayList<MessageObject> pushMessages = new ArrayList<MessageObject>();
private HashMap<Integer, MessageObject> pushMessagesDict = new HashMap<Integer, MessageObject>();
private NotificationManager notificationManager = null;
private HashMap<Long, Integer> pushDialogs = new HashMap<Long, Integer>();
public ArrayList<MessageObject> popupMessages = new ArrayList<MessageObject>();
private long openned_dialog_id = 0;
private int total_unread_count = 0;
private boolean notifyCheck = false;
public static final int pushMessagesUpdated = 27;
private static volatile NotificationsController Instance = null;
public static NotificationsController getInstance() {
NotificationsController localInstance = Instance;
if (localInstance == null) {
synchronized (MessagesController.class) {
localInstance = Instance;
if (localInstance == null) {
Instance = localInstance = new NotificationsController();
}
}
}
return localInstance;
}
public NotificationsController() {
notificationManager = (NotificationManager)ApplicationLoader.applicationContext.getSystemService(Context.NOTIFICATION_SERVICE);
}
public void cleanup() {
openned_dialog_id = 0;
total_unread_count = 0;
pushMessages.clear();
pushMessagesDict.clear();
pushDialogs.clear();
popupMessages.clear();
notifyCheck = false;
}
public void setOpennedDialogId(long dialog_id) {
openned_dialog_id = dialog_id;
}
private String getStringForMessage(MessageObject messageObject) {
long dialog_id = messageObject.messageOwner.dialog_id;
int chat_id = messageObject.messageOwner.to_id.chat_id;
int user_id = messageObject.messageOwner.to_id.user_id;
if (user_id == 0) {
user_id = messageObject.messageOwner.from_id;
} else if (user_id == UserConfig.getClientUserId()) {
user_id = messageObject.messageOwner.from_id;
}
if (dialog_id == 0) {
if (chat_id != 0) {
dialog_id = -chat_id;
} else if (user_id != 0) {
dialog_id = user_id;
}
}
TLRPC.User user = MessagesController.getInstance().users.get(user_id);
if (user == null) {
return null;
}
TLRPC.Chat chat = null;
if (chat_id != 0) {
chat = MessagesController.getInstance().chats.get(chat_id);
if (chat == null) {
return null;
}
}
String msg = null;
if ((int)dialog_id != 0) {
if (chat_id == 0 && user_id != 0) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
if (preferences.getBoolean("EnablePreviewAll", true)) {
if (messageObject.messageOwner instanceof TLRPC.TL_messageService) {
if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionUserJoined) {
msg = LocaleController.formatString("NotificationContactJoined", R.string.NotificationContactJoined, Utilities.formatName(user.first_name, user.last_name));
} else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) {
msg = LocaleController.formatString("NotificationContactNewPhoto", R.string.NotificationContactNewPhoto, Utilities.formatName(user.first_name, user.last_name));
} else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionLoginUnknownLocation) {
String date = String.format("%s %s %s", LocaleController.formatterYear.format(((long)messageObject.messageOwner.date) * 1000), LocaleController.getString("OtherAt", R.string.OtherAt), LocaleController.formatterDay.format(((long)messageObject.messageOwner.date) * 1000));
msg = LocaleController.formatString("NotificationUnrecognizedDevice", R.string.NotificationUnrecognizedDevice, UserConfig.getCurrentUser().first_name, date, messageObject.messageOwner.action.title, messageObject.messageOwner.action.address);
}
} else {
if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty) {
if (messageObject.messageOwner.message != null && messageObject.messageOwner.message.length() != 0) {
msg = LocaleController.formatString("NotificationMessageText", R.string.NotificationMessageText, Utilities.formatName(user.first_name, user.last_name), messageObject.messageOwner.message);
} else {
msg = LocaleController.formatString("NotificationMessageNoText", R.string.NotificationMessageNoText, Utilities.formatName(user.first_name, user.last_name));
}
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
msg = LocaleController.formatString("NotificationMessagePhoto", R.string.NotificationMessagePhoto, Utilities.formatName(user.first_name, user.last_name));
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) {
msg = LocaleController.formatString("NotificationMessageVideo", R.string.NotificationMessageVideo, Utilities.formatName(user.first_name, user.last_name));
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) {
msg = LocaleController.formatString("NotificationMessageContact", R.string.NotificationMessageContact, Utilities.formatName(user.first_name, user.last_name));
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo) {
msg = LocaleController.formatString("NotificationMessageMap", R.string.NotificationMessageMap, Utilities.formatName(user.first_name, user.last_name));
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
msg = LocaleController.formatString("NotificationMessageDocument", R.string.NotificationMessageDocument, Utilities.formatName(user.first_name, user.last_name));
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaAudio) {
msg = LocaleController.formatString("NotificationMessageAudio", R.string.NotificationMessageAudio, Utilities.formatName(user.first_name, user.last_name));
}
}
} else {
msg = LocaleController.formatString("NotificationMessageNoText", R.string.NotificationMessageNoText, Utilities.formatName(user.first_name, user.last_name));
}
} else if (chat_id != 0) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
if (preferences.getBoolean("EnablePreviewGroup", true)) {
if (messageObject.messageOwner instanceof TLRPC.TL_messageService) {
if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatAddUser) {
if (messageObject.messageOwner.action.user_id == UserConfig.getClientUserId()) {
msg = LocaleController.formatString("NotificationInvitedToGroup", R.string.NotificationInvitedToGroup, Utilities.formatName(user.first_name, user.last_name), chat.title);
} else {
TLRPC.User u2 = MessagesController.getInstance().users.get(messageObject.messageOwner.action.user_id);
if (u2 == null) {
return null;
}
msg = LocaleController.formatString("NotificationGroupAddMember", R.string.NotificationGroupAddMember, Utilities.formatName(user.first_name, user.last_name), chat.title, Utilities.formatName(u2.first_name, u2.last_name));
}
} else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatEditTitle) {
msg = LocaleController.formatString("NotificationEditedGroupName", R.string.NotificationEditedGroupName, Utilities.formatName(user.first_name, user.last_name), messageObject.messageOwner.action.title);
} else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatEditPhoto || messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatDeletePhoto) {
msg = LocaleController.formatString("NotificationEditedGroupPhoto", R.string.NotificationEditedGroupPhoto, Utilities.formatName(user.first_name, user.last_name), chat.title);
} else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatDeleteUser) {
if (messageObject.messageOwner.action.user_id == UserConfig.getClientUserId()) {
msg = LocaleController.formatString("NotificationGroupKickYou", R.string.NotificationGroupKickYou, Utilities.formatName(user.first_name, user.last_name), chat.title);
} else if (messageObject.messageOwner.action.user_id == user.id) {
msg = LocaleController.formatString("NotificationGroupLeftMember", R.string.NotificationGroupLeftMember, Utilities.formatName(user.first_name, user.last_name), chat.title);
} else {
TLRPC.User u2 = MessagesController.getInstance().users.get(messageObject.messageOwner.action.user_id);
if (u2 == null) {
return null;
}
msg = LocaleController.formatString("NotificationGroupKickMember", R.string.NotificationGroupKickMember, Utilities.formatName(user.first_name, user.last_name), chat.title, Utilities.formatName(u2.first_name, u2.last_name));
}
}
} else {
if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty) {
if (messageObject.messageOwner.message != null && messageObject.messageOwner.message.length() != 0) {
msg = LocaleController.formatString("NotificationMessageGroupText", R.string.NotificationMessageGroupText, Utilities.formatName(user.first_name, user.last_name), chat.title, messageObject.messageOwner.message);
} else {
msg = LocaleController.formatString("NotificationMessageGroupNoText", R.string.NotificationMessageGroupNoText, Utilities.formatName(user.first_name, user.last_name), chat.title);
}
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
msg = LocaleController.formatString("NotificationMessageGroupPhoto", R.string.NotificationMessageGroupPhoto, Utilities.formatName(user.first_name, user.last_name), chat.title);
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) {
msg = LocaleController.formatString("NotificationMessageGroupVideo", R.string.NotificationMessageGroupVideo, Utilities.formatName(user.first_name, user.last_name), chat.title);
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) {
msg = LocaleController.formatString("NotificationMessageGroupContact", R.string.NotificationMessageGroupContact, Utilities.formatName(user.first_name, user.last_name), chat.title);
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo) {
msg = LocaleController.formatString("NotificationMessageGroupMap", R.string.NotificationMessageGroupMap, Utilities.formatName(user.first_name, user.last_name), chat.title);
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
msg = LocaleController.formatString("NotificationMessageGroupDocument", R.string.NotificationMessageGroupDocument, Utilities.formatName(user.first_name, user.last_name), chat.title);
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaAudio) {
msg = LocaleController.formatString("NotificationMessageGroupAudio", R.string.NotificationMessageGroupAudio, Utilities.formatName(user.first_name, user.last_name), chat.title);
}
}
} else {
msg = LocaleController.formatString("NotificationMessageGroupNoText", R.string.NotificationMessageGroupNoText, Utilities.formatName(user.first_name, user.last_name), chat.title);
}
}
} else {
msg = LocaleController.getString("YouHaveNewMessage", R.string.YouHaveNewMessage);
}
return msg;
}
private void showOrUpdateNotification(boolean notifyAboutLast) {
if (!UserConfig.isClientActivated() || pushMessages.isEmpty()) {
dismissNotification();
return;
}
try {
ConnectionsManager.getInstance().resumeNetworkMaybe();
MessageObject lastMessageObject = pushMessages.get(0);
long dialog_id = lastMessageObject.getDialogId();
int chat_id = lastMessageObject.messageOwner.to_id.chat_id;
int user_id = lastMessageObject.messageOwner.to_id.user_id;
if (user_id == 0) {
user_id = lastMessageObject.messageOwner.from_id;
} else if (user_id == UserConfig.getClientUserId()) {
user_id = lastMessageObject.messageOwner.from_id;
}
TLRPC.User user = MessagesController.getInstance().users.get(user_id);
TLRPC.Chat chat = null;
if (chat_id != 0) {
chat = MessagesController.getInstance().chats.get(chat_id);
}
TLRPC.FileLocation photoPath = null;
boolean notifyDisabled = false;
boolean needVibrate = false;
String choosenSoundPath = null;
int ledColor = 0xff00ff00;
boolean inAppSounds = false;
boolean inAppVibrate = false;
boolean inAppPreview = false;
int vibrate_override = 0;
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
int notify_override = preferences.getInt("notify2_" + dialog_id, 0);
if (!notifyAboutLast || notify_override == 2 || (!preferences.getBoolean("EnableAll", true) || chat_id != 0 && !preferences.getBoolean("EnableGroup", true)) && notify_override == 0) {
notifyDisabled = true;
}
String defaultPath = Settings.System.DEFAULT_NOTIFICATION_URI.getPath();
if (!notifyDisabled) {
inAppSounds = preferences.getBoolean("EnableInAppSounds", true);
inAppVibrate = preferences.getBoolean("EnableInAppVibrate", true);
inAppPreview = preferences.getBoolean("EnableInAppPreview", true);
vibrate_override = preferences.getInt("vibrate_" + dialog_id, 0);
choosenSoundPath = preferences.getString("sound_path_" + dialog_id, null);
if (chat_id != 0) {
if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) {
choosenSoundPath = null;
} else if (choosenSoundPath == null) {
choosenSoundPath = preferences.getString("GroupSoundPath", defaultPath);
}
needVibrate = preferences.getBoolean("EnableVibrateGroup", true);
ledColor = preferences.getInt("GroupLed", 0xff00ff00);
} else if (user_id != 0) {
if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) {
choosenSoundPath = null;
} else if (choosenSoundPath == null) {
choosenSoundPath = preferences.getString("GlobalSoundPath", defaultPath);
}
needVibrate = preferences.getBoolean("EnableVibrateAll", true);
ledColor = preferences.getInt("MessagesLed", 0xff00ff00);
}
if (preferences.contains("color_" + dialog_id)) {
ledColor = preferences.getInt("color_" + dialog_id, 0);
}
if (!needVibrate && vibrate_override == 1) {
needVibrate = true;
} else if (needVibrate && vibrate_override == 2) {
needVibrate = false;
}
if (!ApplicationLoader.mainInterfacePaused) {
if (!inAppSounds) {
choosenSoundPath = null;
}
if (!inAppVibrate) {
needVibrate = false;
}
}
}
Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE);
intent.setFlags(32768);
if ((int)dialog_id != 0) {
if (chat_id != 0) {
intent.putExtra("chatId", chat_id);
} else if (user_id != 0) {
intent.putExtra("userId", user_id);
}
if (pushDialogs.size() == 1) {
if (chat != null) {
if (chat.photo != null && chat.photo.photo_small != null && chat.photo.photo_small.volume_id != 0 && chat.photo.photo_small.local_id != 0) {
photoPath = chat.photo.photo_small;
}
} else {
if (user.photo != null && user.photo.photo_small != null && user.photo.photo_small.volume_id != 0 && user.photo.photo_small.local_id != 0) {
photoPath = user.photo.photo_small;
}
}
}
} else {
intent.putExtra("encId", (int)(dialog_id >> 32));
}
PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_ONE_SHOT);
String name = null;
boolean replace = true;
if ((int)dialog_id == 0 || pushDialogs.size() > 1) {
name = LocaleController.getString("AppName", R.string.AppName);
replace = false;
} else {
if (chat != null) {
name = chat.title;
} else {
name = Utilities.formatName(user.first_name, user.last_name);
}
}
String detailText = null;
if (pushDialogs.size() == 1) {
detailText = LocaleController.formatPluralString("NewMessages", total_unread_count);
} else {
detailText = String.format("%s %s", LocaleController.formatPluralString("NewMessages", total_unread_count), LocaleController.formatPluralString("FromContacts", pushDialogs.size()));
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ApplicationLoader.applicationContext)
.setContentTitle(name)
.setSmallIcon(R.drawable.notification)
.setAutoCancel(true)
.setContentText(detailText)
.setContentIntent(contentIntent);
String lastMessage = null;
if (pushMessages.size() == 1) {
String message = lastMessage = getStringForMessage(pushMessages.get(0));
if (message == null) {
return;
}
if (replace) {
if (chat != null) {
message = message.replace(" @ " + name, "");
} else {
message = message.replace(name + ": ", "").replace(name + " ", "");
}
}
mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(message));
} else {
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle(name);
int count = Math.min(10, pushMessages.size());
for (int i = 0; i < count; i++) {
String message = getStringForMessage(pushMessages.get(i));
if (message == null) {
continue;
}
if (i == 0) {
lastMessage = message;
}
if (pushDialogs.size() == 1) {
if (replace) {
if (chat != null) {
message = message.replace(" @ " + name, "");
} else {
message = message.replace(name + ": ", "").replace(name + " ", "");
}
}
}
inboxStyle.addLine(message);
}
inboxStyle.setSummaryText(detailText);
mBuilder.setStyle(inboxStyle);
}
if (photoPath != null) {
Bitmap img = FileLoader.getInstance().getImageFromMemory(photoPath, null, null, "50_50", false);
if (img != null) {
mBuilder.setLargeIcon(img);
}
}
if (!notifyDisabled) {
if (ApplicationLoader.mainInterfacePaused || inAppPreview) {
mBuilder.setTicker(lastMessage);
}
if (choosenSoundPath != null && !choosenSoundPath.equals("NoSound")) {
if (choosenSoundPath.equals(defaultPath)) {
mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI, AudioManager.STREAM_NOTIFICATION);
} else {
mBuilder.setSound(Uri.parse(choosenSoundPath), AudioManager.STREAM_NOTIFICATION);
}
}
if (ledColor != 0) {
mBuilder.setLights(ledColor, 1000, 1000);
}
if (needVibrate) {
mBuilder.setVibrate(new long[]{0, 100, 0, 100});
}
} else {
mBuilder.setVibrate(new long[]{0, 0});
}
notificationManager.notify(1, mBuilder.build());
if (preferences.getBoolean("EnablePebbleNotifications", false)) {
sendAlertToPebble(lastMessage);
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
private void dismissNotification() {
try {
notificationManager.cancel(1);
pushMessages.clear();
pushMessagesDict.clear();
NotificationCenter.getInstance().postNotificationName(pushMessagesUpdated);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
private void sendAlertToPebble(String message) {
try {
final Intent i = new Intent("com.getpebble.action.SEND_NOTIFICATION");
final HashMap<String, String> data = new HashMap<String, String>();
data.put("title", LocaleController.getString("AppName", R.string.AppName));
data.put("body", message);
final JSONObject jsonData = new JSONObject(data);
final String notificationData = new JSONArray().put(jsonData).toString();
i.putExtra("messageType", "PEBBLE_ALERT");
i.putExtra("sender", LocaleController.formatString("AppName", R.string.AppName));
i.putExtra("notificationData", notificationData);
ApplicationLoader.applicationContext.sendBroadcast(i);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
public void processReadMessages(ArrayList<Integer> readMessages, long dialog_id, int max_date, int max_id) {
int oldCount = popupMessages.size();
int oldCount2 = pushMessages.size();
if (readMessages != null) {
for (Integer id : readMessages) {
MessageObject messageObject = pushMessagesDict.get(id);
if (messageObject != null) {
pushMessages.remove(messageObject);
popupMessages.remove(messageObject);
pushMessagesDict.remove(id);
}
}
}
if (dialog_id != 0 && (max_id != 0 || max_date != 0)) {
for (int a = 0; a < pushMessages.size(); a++) {
MessageObject messageObject = pushMessages.get(a);
if (messageObject.getDialogId() == dialog_id) {
boolean remove = false;
if (max_date != 0) {
if (messageObject.messageOwner.date <= max_date) {
remove = true;
}
} else {
if (messageObject.messageOwner.id <= max_id) {
remove = true;
}
}
if (remove) {
pushMessages.remove(a);
popupMessages.remove(messageObject);
pushMessagesDict.remove(messageObject.messageOwner.id);
a--;
}
}
}
}
if (oldCount != popupMessages.size()) {
NotificationCenter.getInstance().postNotificationName(pushMessagesUpdated);
}
// if (readMessages != null || oldCount2 != pushMessages.size() || readMessages == null && dialog_id == 0) {
// showOrUpdateNotification(notifyCheck);
// }
}
public void processNewMessages(ArrayList<MessageObject> messageObjects, boolean isLast) {
if (messageObjects.isEmpty()) {
return;
}
boolean added = false;
int oldCount = popupMessages.size();
HashMap<Long, Boolean> settingsCache = new HashMap<Long, Boolean>();
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
int popup = 0;
for (MessageObject messageObject : messageObjects) {
if (pushMessagesDict.containsKey(messageObject.messageOwner.id)) {
continue;
}
long dialog_id = messageObject.getDialogId();
if (dialog_id == openned_dialog_id && ApplicationLoader.isScreenOn) {
continue;
}
added = true;
Boolean value = settingsCache.get(dialog_id);
boolean isChat = (int)dialog_id < 0;
popup = preferences.getInt(isChat ? "popupGroup" : "popupAll", 0);
if (value == null) {
int notify_override = preferences.getInt("notify2_" + dialog_id, 0);
value = !(notify_override == 2 || (!preferences.getBoolean("EnableAll", true) || isChat && !preferences.getBoolean("EnableGroup", true)) && notify_override == 0);
settingsCache.put(dialog_id, value);
}
if (value) {
if (popup != 0) {
popupMessages.add(0, messageObject);
}
pushMessagesDict.put(messageObject.messageOwner.id, messageObject);
pushMessages.add(0, messageObject);
}
}
if (added) {
notifyCheck = isLast;
}
if (!popupMessages.isEmpty() && oldCount != popupMessages.size()) {
if (ApplicationLoader.mainInterfacePaused || !ApplicationLoader.isScreenOn) {
MessageObject messageObject = messageObjects.get(0);
if (popup == 3 || popup == 1 && ApplicationLoader.isScreenOn || popup == 2 && !ApplicationLoader.isScreenOn) {
Intent popupIntent = new Intent(ApplicationLoader.applicationContext, PopupNotificationActivity.class);
popupIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_NO_USER_ACTION | Intent.FLAG_FROM_BACKGROUND);
ApplicationLoader.applicationContext.startActivity(popupIntent);
}
}
}
}
public void processDialogsUpdateRead(final HashMap<Long, Integer> dialogsToUpdate, boolean replace) {
int old_unread_count = total_unread_count;
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
for (HashMap.Entry<Long, Integer> entry : dialogsToUpdate.entrySet()) {
long dialog_id = entry.getKey();
int notify_override = preferences.getInt("notify2_" + dialog_id, 0);
boolean isChat = (int)dialog_id < 0;
Integer currentCount = pushDialogs.get(dialog_id);
if (!(notify_override == 2 || (!preferences.getBoolean("EnableAll", true) || isChat && !preferences.getBoolean("EnableGroup", true)) && notify_override == 0)) {
Integer newCount = entry.getValue();
if (replace) {
if (currentCount != null) {
total_unread_count -= currentCount;
}
if (newCount == 0) {
pushDialogs.remove(dialog_id);
} else {
total_unread_count += newCount;
pushDialogs.put(dialog_id, newCount);
}
} else {
if (currentCount == null) {
currentCount = 0;
}
currentCount += newCount;
total_unread_count += newCount;
pushDialogs.put(dialog_id, currentCount);
}
}
}
if (old_unread_count != total_unread_count) {
showOrUpdateNotification(notifyCheck);
notifyCheck = false;
}
if (preferences.getBoolean("badgeNumber", true)) {
setBadge(ApplicationLoader.applicationContext, total_unread_count);
}
}
public void processLoadedUnreadMessages(HashMap<Long, Integer> dialogs) {
pushDialogs.clear();
total_unread_count = 0;
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
String dialogsToLoad = "";
for (HashMap.Entry<Long, Integer> entry : dialogs.entrySet()) {
long dialog_id = entry.getKey();
int notify_override = preferences.getInt("notify2_" + dialog_id, 0);
boolean isChat = (int)dialog_id < 0;
if (!(notify_override == 2 || (!preferences.getBoolean("EnableAll", true) || isChat && !preferences.getBoolean("EnableGroup", true)) && notify_override == 0)) {
pushDialogs.put(dialog_id, entry.getValue());
total_unread_count += entry.getValue();
if (dialogsToLoad.length() != 0) {
dialogsToLoad += ",";
}
dialogsToLoad += "" + dialog_id;
}
}
if (total_unread_count == 0) {
pushMessages.clear();
pushMessagesDict.clear();
popupMessages.clear();
showOrUpdateNotification(false);
NotificationCenter.getInstance().postNotificationName(pushMessagesUpdated);
}
if (preferences.getBoolean("badgeNumber", true)) {
setBadge(ApplicationLoader.applicationContext, total_unread_count);
}
}
public void setBadgeEnabled(boolean enabled) {
setBadge(ApplicationLoader.applicationContext, enabled ? total_unread_count : 0);
}
private void setBadge(Context context, int count) {
try {
String launcherClassName = getLauncherClassName(context);
if (launcherClassName == null) {
return;
}
Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
intent.putExtra("badge_count", count);
intent.putExtra("badge_count_package_name", context.getPackageName());
intent.putExtra("badge_count_class_name", launcherClassName);
context.sendBroadcast(intent);
} catch (Throwable e) {
FileLog.e("tmessages", e);
}
}
public static String getLauncherClassName(Context context) {
try {
PackageManager pm = context.getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resolveInfos) {
String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
if (pkgName.equalsIgnoreCase(context.getPackageName())) {
return resolveInfo.activityInfo.name;
}
}
} catch (Throwable e) {
FileLog.e("tmessages", e);
}
return null;
}
}

View File

@ -6,13 +6,14 @@
* Copyright Nikolai Kudashov, 2013-2014.
*/
package org.telegram.messenger;
package org.telegram.android;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import org.telegram.messenger.FileLog;
import org.telegram.ui.ApplicationLoader;
public class NotificationsService extends Service {

View File

@ -6,12 +6,14 @@
* Copyright Nikolai Kudashov, 2013-2014.
*/
package org.telegram.messenger;
package org.telegram.android;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLog;
import org.telegram.ui.ApplicationLoader;
public class ScreenReceiver extends BroadcastReceiver {
@ -19,13 +21,11 @@ public class ScreenReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
FileLog.e("tmessages", "screen off");
if (ConnectionsManager.lastPauseTime == 0) {
ConnectionsManager.lastPauseTime = System.currentTimeMillis();
}
ConnectionsManager.getInstance().setAppPaused(true, true);
ApplicationLoader.isScreenOn = false;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
FileLog.e("tmessages", "screen on");
ConnectionsManager.resetLastPauseTime();
ConnectionsManager.getInstance().setAppPaused(false, true);
ApplicationLoader.isScreenOn = true;
}
}

View File

@ -6,7 +6,7 @@
* Copyright Nikolai Kudashov, 2013.
*/
package org.telegram.messenger;
package org.telegram.android;
import android.content.BroadcastReceiver;
import android.content.Context;
@ -15,6 +15,9 @@ import android.content.SharedPreferences;
import android.os.Bundle;
import android.telephony.SmsMessage;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.NotificationCenter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -25,7 +28,7 @@ public class SmsListener extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
if (!Utilities.isWaitingForSms()) {
if (!AndroidUtilities.isWaitingForSms()) {
return;
}
Bundle bundle = intent.getExtras();

View File

@ -25,6 +25,4 @@ public class Action {
public void cancel() {
}
public int state;
}

View File

@ -18,6 +18,8 @@ public class BuffersStorage {
private final ArrayList<ByteBufferDesc> freeBuffers16384;
private final ArrayList<ByteBufferDesc> freeBuffers32768;
private final ArrayList<ByteBufferDesc> freeBuffersBig;
private boolean isThreadSafe;
private final static Integer sync = 1;
private static volatile BuffersStorage Instance = null;
public static BuffersStorage getInstance() {
@ -26,14 +28,15 @@ public class BuffersStorage {
synchronized (BuffersStorage.class) {
localInstance = Instance;
if (localInstance == null) {
Instance = localInstance = new BuffersStorage();
Instance = localInstance = new BuffersStorage(true);
}
}
}
return localInstance;
}
public BuffersStorage() {
public BuffersStorage(boolean threadSafe) {
isThreadSafe = threadSafe;
freeBuffers128 = new ArrayList<ByteBufferDesc>();
freeBuffers1024 = new ArrayList<ByteBufferDesc>();
freeBuffers4096 = new ArrayList<ByteBufferDesc>();
@ -44,91 +47,58 @@ public class BuffersStorage {
for (int a = 0; a < 5; a++) {
freeBuffers128.add(new ByteBufferDesc(128));
}
// for (int a = 0; a < 5; a++) {
// freeBuffers1024.add(new ByteBufferDesc(1024 + 200));
// }
// for (int a = 0; a < 2; a++) {
// freeBuffers4096.add(new ByteBufferDesc(4096 + 200));
// }
// for (int a = 0; a < 2; a++) {
// freeBuffers16384.add(new ByteBufferDesc(16384 + 200));
// }
// for (int a = 0; a < 2; a++) {
// freeBuffers32768.add(new ByteBufferDesc(40000));
// }
}
public ByteBufferDesc getFreeBuffer(int size) {
if (size <= 0) {
return null;
}
int byteCount = 0;
ArrayList<ByteBufferDesc> arrayToGetFrom = null;
ByteBufferDesc buffer = null;
if (size <= 128) {
synchronized (freeBuffers128) {
if (freeBuffers128.size() > 0) {
buffer = freeBuffers128.get(0);
freeBuffers128.remove(0);
}
}
if (buffer == null) {
buffer = new ByteBufferDesc(128);
FileLog.e("tmessages", "create new 128 buffer");
}
arrayToGetFrom = freeBuffers128;
byteCount = 128;
} else if (size <= 1024 + 200) {
synchronized (freeBuffers1024) {
if (freeBuffers1024.size() > 0) {
buffer = freeBuffers1024.get(0);
freeBuffers1024.remove(0);
}
}
if (buffer == null) {
buffer = new ByteBufferDesc(1024 + 200);
FileLog.e("tmessages", "create new 1024 buffer");
}
arrayToGetFrom = freeBuffers1024;
byteCount = 1024 + 200;
} else if (size <= 4096 + 200) {
synchronized (freeBuffers4096) {
if (freeBuffers4096.size() > 0) {
buffer = freeBuffers4096.get(0);
freeBuffers4096.remove(0);
}
}
if (buffer == null) {
buffer = new ByteBufferDesc(4096 + 200);
FileLog.e("tmessages", "create new 4096 buffer");
}
arrayToGetFrom = freeBuffers4096;
byteCount = 4096 + 200;
} else if (size <= 16384 + 200) {
synchronized (freeBuffers16384) {
if (freeBuffers16384.size() > 0) {
buffer = freeBuffers16384.get(0);
freeBuffers16384.remove(0);
}
}
if (buffer == null) {
buffer = new ByteBufferDesc(16384 + 200);
FileLog.e("tmessages", "create new 16384 buffer");
}
arrayToGetFrom = freeBuffers16384;
byteCount = 16384 + 200;
} else if (size <= 40000) {
synchronized (freeBuffers32768) {
if (freeBuffers32768.size() > 0) {
buffer = freeBuffers32768.get(0);
freeBuffers32768.remove(0);
}
}
if (buffer == null) {
buffer = new ByteBufferDesc(40000);
FileLog.e("tmessages", "create new 40000 buffer");
}
arrayToGetFrom = freeBuffers32768;
byteCount = 40000;
} else if (size <= 280000) {
synchronized (freeBuffersBig) {
if (freeBuffersBig.size() > 0) {
buffer = freeBuffersBig.get(0);
freeBuffersBig.remove(0);
}
}
if (buffer == null) {
buffer = new ByteBufferDesc(280000);
FileLog.e("tmessages", "create new big buffer");
}
arrayToGetFrom = freeBuffersBig;
byteCount = 280000;
} else {
buffer = new ByteBufferDesc(size);
}
if (arrayToGetFrom != null) {
if (isThreadSafe) {
synchronized (sync) {
if (arrayToGetFrom.size() > 0) {
buffer = arrayToGetFrom.get(0);
arrayToGetFrom.remove(0);
}
}
} else {
if (arrayToGetFrom.size() > 0) {
buffer = arrayToGetFrom.get(0);
arrayToGetFrom.remove(0);
}
}
if (buffer == null) {
buffer = new ByteBufferDesc(byteCount);
FileLog.e("tmessages", "create new " + byteCount + " buffer");
}
}
buffer.buffer.limit(size).rewind();
return buffer;
}
@ -137,40 +107,34 @@ public class BuffersStorage {
if (buffer == null) {
return;
}
int maxCount = 10;
ArrayList<ByteBufferDesc> arrayToReuse = null;
if (buffer.buffer.capacity() == 128) {
synchronized (freeBuffers128) {
if (freeBuffers128.size() < 10) {
freeBuffers128.add(buffer);
}
}
arrayToReuse = freeBuffers128;
} else if (buffer.buffer.capacity() == 1024 + 200) {
synchronized (freeBuffers1024) {
if (freeBuffers1024.size() < 10) {
freeBuffers1024.add(buffer);
}
}
} else if (buffer.buffer.capacity() == 4096 + 200) {
synchronized (freeBuffers4096) {
if (freeBuffers4096.size() < 10) {
freeBuffers4096.add(buffer);
}
}
arrayToReuse = freeBuffers1024;
} if (buffer.buffer.capacity() == 4096 + 200) {
arrayToReuse = freeBuffers4096;
} else if (buffer.buffer.capacity() == 16384 + 200) {
synchronized (freeBuffers16384) {
if (freeBuffers16384.size() < 10) {
freeBuffers16384.add(buffer);
}
}
arrayToReuse = freeBuffers16384;
} else if (buffer.buffer.capacity() == 40000) {
synchronized (freeBuffers32768) {
if (freeBuffers32768.size() < 10) {
freeBuffers32768.add(buffer);
}
}
arrayToReuse = freeBuffers32768;
} else if (buffer.buffer.capacity() == 280000) {
synchronized (freeBuffersBig) {
if (freeBuffersBig.size() < 4) {
freeBuffersBig.add(buffer);
arrayToReuse = freeBuffersBig;
maxCount = 10;
}
if (arrayToReuse != null) {
if (isThreadSafe) {
synchronized (sync) {
if (arrayToReuse.size() < maxCount) {
arrayToReuse.add(buffer);
} else {
FileLog.e("tmessages", "too more");
}
}
} else {
if (arrayToReuse.size() < maxCount) {
arrayToReuse.add(buffer);
}
}
}

View File

@ -25,6 +25,11 @@ public class ByteBufferDesc extends AbsSerializedData {
justCalc = calculate;
}
public ByteBufferDesc(byte[] bytes) {
buffer = ByteBuffer.wrap(bytes);
buffer.order(ByteOrder.LITTLE_ENDIAN);
}
public int position() {
return buffer.position();
}
@ -397,11 +402,13 @@ public class ByteBufferDesc extends AbsSerializedData {
sl = 4;
}
ByteBufferDesc b = BuffersStorage.getInstance().getFreeBuffer(l);
int old = buffer.limit();
buffer.limit(buffer.position() + l);
b.buffer.put(buffer);
buffer.limit(old);
b.buffer.position(0);
if (b != null) {
int old = buffer.limit();
buffer.limit(buffer.position() + l);
b.buffer.put(buffer);
buffer.limit(old);
b.buffer.position(0);
}
int i = sl;
while((l + i) % 4 != 0) {
buffer.get();

View File

@ -74,6 +74,9 @@ public class ConnectionContext extends PyroClientAdapter {
}
public void addMessageToConfirm(long messageId) {
if (messagesIdsForConfirmation.contains(messageId)) {
return;
}
messagesIdsForConfirmation.add(messageId);
}

View File

@ -35,7 +35,7 @@ public class Datacenter {
private volatile int currentAddressNum = 0;
public TcpConnection connection;
private ArrayList<TcpConnection> downloadConnections = new ArrayList<TcpConnection>();
private TcpConnection downloadConnection;
private TcpConnection uploadConnection;
public TcpConnection pushConnection;
@ -327,7 +327,7 @@ public class Datacenter {
if (uploadConnection != null) {
uploadConnection.suspendConnection(true);
}
for (TcpConnection downloadConnection : downloadConnections) {
if (downloadConnection != null) {
downloadConnection.suspendConnection(true);
}
}
@ -339,7 +339,7 @@ public class Datacenter {
if (uploadConnection != null) {
sessions.add(uploadConnection.getSissionId());
}
for (TcpConnection downloadConnection : downloadConnections) {
if (downloadConnection != null) {
sessions.add(downloadConnection.getSissionId());
}
}
@ -351,26 +351,21 @@ public class Datacenter {
if (uploadConnection != null) {
uploadConnection.recreateSession();
}
for (TcpConnection downloadConnection : downloadConnections) {
if (downloadConnection != null) {
downloadConnection.recreateSession();
}
}
public TcpConnection getDownloadConnection(int num, TcpConnection.TcpConnectionDelegate delegate) {
if (num >= 0 && authKey != null) {
TcpConnection downloadConnection = null;
if (num < downloadConnections.size()) {
downloadConnection = downloadConnections.get(num);
} else {
public TcpConnection getDownloadConnection(TcpConnection.TcpConnectionDelegate delegate) {
if (authKey != null) {
if (downloadConnection == null) {
downloadConnection = new TcpConnection(datacenterId);
downloadConnection.delegate = delegate;
downloadConnection.transportRequestClass = RPCRequest.RPCRequestClassDownloadMedia;
downloadConnections.add(downloadConnection);
}
downloadConnection.connect();
return downloadConnection;
}
return null;
return downloadConnection;
}
public TcpConnection getUploadConnection(TcpConnection.TcpConnectionDelegate delegate) {

View File

@ -41,6 +41,24 @@ public class DispatchQueue extends Thread {
}
}
public void cancelRunnable(Runnable runnable) {
if (handler == null) {
synchronized (handlerSyncObject) {
if (handler == null) {
try {
handlerSyncObject.wait();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
if (handler != null) {
handler.removeCallbacks(runnable);
}
}
public void postRunnable(Runnable runnable) {
postRunnable(runnable, 0);
}

View File

@ -54,7 +54,7 @@ public class ExportAuthorizationAction extends Action {
}
}
}
}, null, true, RPCRequest.RPCRequestClassGeneric);
});
}
void beginImport() {

View File

@ -10,9 +10,9 @@ package org.telegram.messenger;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.provider.MediaStore;
import org.telegram.android.AndroidUtilities;
import org.telegram.ui.ApplicationLoader;
import java.io.RandomAccessFile;
@ -22,10 +22,19 @@ import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLConnection;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Scanner;
public class FileLoadOperation {
private int downloadChunkSize = 1024 * 256;
private static class RequestInfo {
private long requestToken = 0;
private int offset = 0;
private TLRPC.TL_upload_file response = null;
}
private final static int downloadChunkSize = 1024 * 32;
private final static int maxDownloadRequests = 3;
public int datacenter_id;
public TLRPC.InputFileLocation location;
@ -37,14 +46,10 @@ public class FileLoadOperation {
public String filter;
private byte[] key;
private byte[] iv;
private long requestToken = 0;
private long requestToken2 = 0;
private int requestProgress = 0;
private int requestProgress2 = 0;
private int nextDownloadOffset = 0;
private TLRPC.TL_upload_file delayedRes = null;
private int delayedResOffset = 0;
private int delayedResTokenNum = 0;
private ArrayList<RequestInfo> requestInfos = new ArrayList<RequestInfo>(maxDownloadRequests);
private ArrayList<RequestInfo> delayedRequestInfos = new ArrayList<RequestInfo>(maxDownloadRequests - 1);
private File cacheFileTemp;
private File cacheFileFinal;
@ -56,7 +61,7 @@ public class FileLoadOperation {
public boolean needBitmapCreate = true;
private InputStream httpConnectionStream;
private RandomAccessFile fileOutputStream;
RandomAccessFile fiv;
private RandomAccessFile fiv;
public static interface FileLoadOperationDelegate {
public abstract void didFinishLoadingFile(FileLoadOperation operation);
@ -214,7 +219,7 @@ public class FileLoadOperation {
if (isLocalFile) {
cacheFileFinal = new File(fileNameFinal);
} else {
cacheFileFinal = new File(Utilities.getCacheDir(), fileNameFinal);
cacheFileFinal = new File(AndroidUtilities.getCacheDir(), fileNameFinal);
}
final boolean dontDelete = isLocalFile;
final Long mediaIdFinal = mediaId;
@ -245,8 +250,8 @@ public class FileLoadOperation {
float h_filter = 0;
if (filter != null) {
String args[] = filter.split("_");
w_filter = Float.parseFloat(args[0]) * Utilities.density;
h_filter = Float.parseFloat(args[1]) * Utilities.density;
w_filter = Float.parseFloat(args[0]) * AndroidUtilities.density;
h_filter = Float.parseFloat(args[1]) * AndroidUtilities.density;
opts.inJustDecodeBounds = true;
if (mediaIdFinal != null) {
@ -289,11 +294,9 @@ public class FileLoadOperation {
float bitmapH = image.getHeight();
if (bitmapW != w_filter && bitmapW > w_filter) {
float scaleFactor = bitmapW / w_filter;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(image, (int)w_filter, (int)(bitmapH / scaleFactor), false);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(image, (int)w_filter, (int)(bitmapH / scaleFactor), true);
if (image != scaledBitmap) {
if (Build.VERSION.SDK_INT < 11) {
image.recycle();
}
image.recycle();
image = scaledBitmap;
}
}
@ -339,13 +342,13 @@ public class FileLoadOperation {
});
return;
}
cacheFileTemp = new File(Utilities.getCacheDir(), fileNameTemp);
cacheFileTemp = new File(AndroidUtilities.getCacheDir(), fileNameTemp);
if (cacheFileTemp.exists()) {
downloadedBytes = (int)cacheFileTemp.length();
nextDownloadOffset = downloadedBytes = downloadedBytes / 1024 * 1024;
}
if (fileNameIv != null) {
cacheIvTemp = new File(Utilities.getCacheDir(), fileNameIv);
cacheIvTemp = new File(AndroidUtilities.getCacheDir(), fileNameIv);
try {
fiv = new RandomAccessFile(cacheIvTemp, "rws");
long len = cacheIvTemp.length();
@ -383,27 +386,44 @@ public class FileLoadOperation {
if (httpUrl != null) {
startDownloadHTTPRequest();
} else {
if (totalBytesCount >= 1024 * 1024) {
downloadChunkSize = 1024 * 256;
} else {
downloadChunkSize = 1024 * 32;
}
startDownloadRequest();
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
if (totalBytesCount != 0 && downloadedBytes == totalBytesCount) {
try {
onFinishLoadingFile();
} catch (Exception e) {
delegate.didFailedLoadingFile(FileLoadOperation.this);
}
} else {
startDownloadRequest();
}
}
});
}
}
}
public void cancel() {
if (state != 1) {
return;
}
state = 2;
cleanup();
if (httpUrl == null) {
ConnectionsManager.getInstance().cancelRpc(requestToken, true);
ConnectionsManager.getInstance().cancelRpc(requestToken2, true);
}
delegate.didFailedLoadingFile(FileLoadOperation.this);
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
if (state != 1) {
return;
}
state = 2;
cleanup();
if (httpUrl == null) {
for (RequestInfo requestInfo : requestInfos) {
if (requestInfo.requestToken != 0) {
ConnectionsManager.getInstance().cancelRpc(requestInfo.requestToken, true, true);
}
}
}
delegate.didFailedLoadingFile(FileLoadOperation.this);
}
});
}
private void cleanup() {
@ -435,12 +455,13 @@ public class FileLoadOperation {
} catch (Exception e) {
FileLog.e("tmessages", e);
}
if (delayedRes != null) {
delayedRes.disableFree = false;
delayedRes.freeResources();
delayedRes = null;
for (RequestInfo requestInfo : delayedRequestInfos) {
if (requestInfo.response != null) {
requestInfo.response.disableFree = false;
requestInfo.response.freeResources();
}
}
delayedRequestInfos.clear();
}
}
@ -454,7 +475,6 @@ public class FileLoadOperation {
cacheIvTemp.delete();
}
final boolean renamed = cacheFileTemp.renameTo(cacheFileFinal);
if (needBitmapCreate) {
FileLoader.cacheOutQueue.postRunnable(new Runnable() {
@Override
@ -476,8 +496,8 @@ public class FileLoadOperation {
float h_filter;
if (filter != null) {
String args[] = filter.split("_");
w_filter = Float.parseFloat(args[0]) * Utilities.density;
h_filter = Float.parseFloat(args[1]) * Utilities.density;
w_filter = Float.parseFloat(args[0]) * AndroidUtilities.density;
h_filter = Float.parseFloat(args[1]) * AndroidUtilities.density;
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(cacheFileFinal.getAbsolutePath(), opts);
@ -514,11 +534,9 @@ public class FileLoadOperation {
float bitmapH = image.getHeight();
if (bitmapW != w_filter && bitmapW > w_filter) {
float scaleFactor = bitmapW / w_filter;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(image, (int) w_filter, (int) (bitmapH / scaleFactor), false);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(image, (int) w_filter, (int) (bitmapH / scaleFactor), true);
if (image != scaledBitmap) {
if (Build.VERSION.SDK_INT < 11) {
image.recycle();
}
image.recycle();
image = scaledBitmap;
}
}
@ -612,57 +630,51 @@ public class FileLoadOperation {
}
}
private void processRequestResult(TLRPC.TL_upload_file res, TLRPC.TL_error error, int dowloadOffset, int tokenNum) {
private void processRequestResult(RequestInfo requestInfo, TLRPC.TL_error error) {
requestInfos.remove(requestInfo);
if (error == null) {
try {
if (downloadedBytes != dowloadOffset) {
if (delayedRes != null) {
FileLog.e("tmessages", "something went wrong!");
if (downloadedBytes != requestInfo.offset) {
if (state == 1) {
delayedRequestInfos.add(requestInfo);
requestInfo.response.disableFree = true;
}
delayedRes = res;
delayedRes.disableFree = true;
delayedResOffset = dowloadOffset;
delayedResTokenNum = tokenNum;
return;
} else {
if (tokenNum == 0) {
requestToken = 0;
} else if (tokenNum == 1) {
requestToken2 = 0;
}
}
if (res.bytes.limit() == 0) {
if (requestInfo.response.bytes == null || requestInfo.response.bytes.limit() == 0) {
onFinishLoadingFile();
return;
}
if (key != null) {
Utilities.aesIgeEncryption2(res.bytes.buffer, key, iv, false, true, res.bytes.limit());
Utilities.aesIgeEncryption(requestInfo.response.bytes.buffer, key, iv, false, true, 0, requestInfo.response.bytes.limit());
}
if (fileOutputStream != null) {
FileChannel channel = fileOutputStream.getChannel();
channel.write(res.bytes.buffer);
channel.write(requestInfo.response.bytes.buffer);
}
if (fiv != null) {
fiv.seek(0);
fiv.write(iv);
}
downloadedBytes += res.bytes.limit();
downloadedBytes += requestInfo.response.bytes.limit();
if (totalBytesCount > 0 && state == 1) {
delegate.didChangedLoadProgress(FileLoadOperation.this, Math.min(1.0f, (float)downloadedBytes / (float)totalBytesCount));
}
if(delayedRes != null && res != delayedRes) {
TLRPC.TL_upload_file temp = delayedRes;
processRequestResult(temp, null, delayedResOffset, delayedResTokenNum);
if (delayedRes != null) {
delayedRes.disableFree = false;
delayedRes.freeResources();
delayedRes = null;
for (int a = 0; a < delayedRequestInfos.size(); a++) {
RequestInfo delayedRequestInfo = delayedRequestInfos.get(a);
if (downloadedBytes == delayedRequestInfo.offset) {
delayedRequestInfos.remove(a);
processRequestResult(delayedRequestInfo, null);
delayedRequestInfo.response.disableFree = false;
delayedRequestInfo.response.freeResources();
delayedRequestInfo = null;
break;
}
}
if (downloadedBytes % downloadChunkSize == 0 || totalBytesCount > 0 && totalBytesCount != downloadedBytes) {
if (totalBytesCount != downloadedBytes && downloadedBytes % downloadChunkSize == 0 || totalBytesCount > 0 && totalBytesCount > downloadedBytes) {
startDownloadRequest();
} else {
onFinishLoadingFile();
@ -714,69 +726,36 @@ public class FileLoadOperation {
}
}
private void processRequestProgress() {
delegate.didChangedLoadProgress(FileLoadOperation.this, Math.min(1.0f, (float) (downloadedBytes + requestProgress + requestProgress2) / (float) totalBytesCount));
}
private void startDownloadRequest() {
if (state != 1) {
if (state != 1 || totalBytesCount > 0 && nextDownloadOffset >= totalBytesCount || requestInfos.size() + delayedRequestInfos.size() >= maxDownloadRequests) {
return;
}
if (requestToken == 0) {
requestProgress = 0;
if (totalBytesCount > 0 && nextDownloadOffset >= totalBytesCount) {
return;
}
final TLRPC.TL_upload_getFile req = new TLRPC.TL_upload_getFile();
req.location = location;
req.offset = nextDownloadOffset;
req.limit = downloadChunkSize;
nextDownloadOffset += downloadChunkSize;
final long time = System.currentTimeMillis();
requestToken = ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
processRequestResult((TLRPC.TL_upload_file) response, error, req.offset, 0);
}
}, new RPCRequest.RPCProgressDelegate() {
@Override
public void progress(int length, int progress) {
if (state == 1) {
requestProgress = progress;
if (totalBytesCount == -1) {
delegate.didChangedLoadProgress(FileLoadOperation.this, Math.min(1.0f, (float) (progress) / (float) length));
} else if (totalBytesCount > 0) {
processRequestProgress();
}
}
}
}, null, true, RPCRequest.RPCRequestClassDownloadMedia, datacenter_id);
int count = 1;
if (totalBytesCount > 0) {
count = Math.max(0, maxDownloadRequests - requestInfos.size() - delayedRequestInfos.size());
}
if (totalBytesCount > 0 && requestToken2 == 0) {
requestProgress2 = 0;
for (int a = 0; a < count; a++) {
if (totalBytesCount > 0 && nextDownloadOffset >= totalBytesCount) {
return;
break;
}
final long time = System.currentTimeMillis();
final TLRPC.TL_upload_getFile req = new TLRPC.TL_upload_getFile();
boolean isLast = totalBytesCount <= 0 || a == count - 1 || totalBytesCount > 0 && nextDownloadOffset + downloadChunkSize >= totalBytesCount;
TLRPC.TL_upload_getFile req = new TLRPC.TL_upload_getFile();
req.location = location;
req.offset = nextDownloadOffset;
req.limit = downloadChunkSize;
nextDownloadOffset += downloadChunkSize;
requestToken2 = ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
final RequestInfo requestInfo = new RequestInfo();
requestInfos.add(requestInfo);
requestInfo.offset = req.offset;
requestInfo.requestToken = ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
processRequestResult((TLRPC.TL_upload_file) response, error, req.offset, 1);
requestInfo.response = (TLRPC.TL_upload_file) response;
processRequestResult(requestInfo, error);
}
}, new RPCRequest.RPCProgressDelegate() {
@Override
public void progress(int length, int progress) {
if (state == 1) {
requestProgress2 = progress;
processRequestProgress();
}
}
}, null, true, RPCRequest.RPCRequestClassDownloadMedia | RPCRequest.RPCRequestClassDownloadMedia2, datacenter_id);
}, null, true, RPCRequest.RPCRequestClassDownloadMedia, datacenter_id, isLast);
}
}
}

View File

@ -18,6 +18,7 @@ import android.net.Uri;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import org.telegram.android.AndroidUtilities;
import org.telegram.objects.MessageObject;
import org.telegram.ui.ApplicationLoader;
import org.telegram.ui.Views.ImageReceiver;
@ -291,10 +292,8 @@ public class FileLoader {
if (runtimeHack != null) {
runtimeHack.trackAlloc(oldBitmap.getRowBytes() * oldBitmap.getHeight());
}
if (Build.VERSION.SDK_INT < 11) {
if (!oldBitmap.isRecycled()) {
oldBitmap.recycle();
}
if (!oldBitmap.isRecycled()) {
oldBitmap.recycle();
}
}
}
@ -466,6 +465,7 @@ public class FileLoader {
}
FileLoadOperation operation = loadOperationPaths.get(fileName);
if (operation != null) {
loadOperationPaths.remove(fileName);
if (audio != null) {
audioLoadOperationQueue.remove(operation);
} else if (photo != null) {
@ -946,8 +946,14 @@ public class FileLoader {
}
}
};
boolean isLocalFile = false;
if (httpUrl != null && !httpUrl.startsWith("http")) {
isLocalFile = true;
}
img.loadOperation = loadOperation;
if (runningOperation.size() < maxConcurentLoadingOpertaionsCount) {
if (runningOperation.size() < maxConcurentLoadingOpertaionsCount || isLocalFile) {
loadOperation.start();
runningOperation.add(loadOperation);
} else {
@ -1119,7 +1125,7 @@ public class FileLoader {
try {
if (!cache) {
String fileName = location.volume_id + "_" + location.local_id + ".jpg";
final File cacheFile = new File(Utilities.getCacheDir(), fileName);
final File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName);
FileOutputStream stream = new FileOutputStream(cacheFile);
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);
size.size = (int)stream.getChannel().size();
@ -1129,10 +1135,8 @@ public class FileLoader {
size.bytes = stream.toByteArray();
size.size = size.bytes.length;
}
if (Build.VERSION.SDK_INT < 11) {
if (scaledBitmap != bitmap) {
scaledBitmap.recycle();
}
if (scaledBitmap != bitmap) {
scaledBitmap.recycle();
}
return size;
} catch (Exception e) {

View File

@ -11,6 +11,7 @@ package org.telegram.messenger;
import android.net.Uri;
import android.util.Log;
import org.telegram.android.FastDateFormat;
import org.telegram.ui.ApplicationLoader;
import java.io.File;

View File

@ -31,7 +31,7 @@ public class FileUploadOperation {
private byte[] key;
private byte[] iv;
private byte[] ivChange;
private int fingerprint;
private int fingerprint = 0;
private boolean isBigFile = false;
FileInputStream stream;
MessageDigest mdEnc = null;
@ -57,11 +57,9 @@ public class FileUploadOperation {
System.arraycopy(key, 0, arr, 0, 32);
System.arraycopy(iv, 0, arr, 32, 32);
byte[] digest = md.digest(arr);
byte[] fingerprintBytes = new byte[4];
for (int a = 0; a < 4; a++) {
fingerprintBytes[a] = (byte)(digest[a] ^ digest[a + 4]);
fingerprint |= ((digest[a] ^ digest[a + 4]) & 0xFF) << (a * 8);
}
fingerprint = Utilities.bytesToInt(fingerprintBytes);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
@ -138,7 +136,7 @@ public class FileUploadOperation {
for (int a = 0; a < toAdd; a++) {
sendBuffer.writeByte(0);
}
Utilities.aesIgeEncryption2(sendBuffer.buffer, key, ivChange, true, true, readed + toAdd);
Utilities.aesIgeEncryption(sendBuffer.buffer, key, ivChange, true, true, 0, readed + toAdd);
}
sendBuffer.rewind();
if (!isBigFile) {
@ -211,11 +209,6 @@ public class FileUploadOperation {
delegate.didFailedUploadingFile(FileUploadOperation.this);
}
}
}, new RPCRequest.RPCProgressDelegate() {
@Override
public void progress(int length, int progress) {
}
}, null, true, RPCRequest.RPCRequestClassUploadMedia, ConnectionsManager.DEFAULT_DATACENTER_ID);
}
}

View File

@ -12,7 +12,6 @@ import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
@ -29,9 +28,9 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
private boolean processedPQRes;
private byte[] reqPQMsgData;
private byte[] reqDHMsgData;
private byte[] setClientDHParamsMsgData;
private ByteBufferDesc reqPQMsgData;
private ByteBufferDesc reqDHMsgData;
private ByteBufferDesc setClientDHParamsMsgData;
private boolean wasDisconnect = false;
private long lastOutgoingMessageId;
@ -63,9 +62,18 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
authKey = null;
authKeyId = 0;
processedPQRes = false;
reqPQMsgData = null;
reqDHMsgData = null;
setClientDHParamsMsgData = null;
if (reqPQMsgData != null) {
BuffersStorage.getInstance().reuseFreeBuffer(reqPQMsgData);
reqPQMsgData = null;
}
if (reqDHMsgData != null) {
BuffersStorage.getInstance().reuseFreeBuffer(reqDHMsgData);
reqDHMsgData = null;
}
if (setClientDHParamsMsgData != null) {
BuffersStorage.getInstance().reuseFreeBuffer(setClientDHParamsMsgData);
setClientDHParamsMsgData = null;
}
if (dropConnection) {
datacenter.connection.suspendConnection(true);
@ -165,23 +173,17 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
return messageId;
}
byte[] sendMessageData(TLObject message, long messageId) {
byte[] messageData;
SerializedData innerOs = new SerializedData();
message.serializeToStream(innerOs);
messageData = innerOs.toByteArray();
SerializedData messageOs = new SerializedData();
ByteBufferDesc sendMessageData(TLObject message, long messageId) {
int messageLength = message.getObjectSize();
ByteBufferDesc messageOs = BuffersStorage.getInstance().getFreeBuffer(8 + 8 + 4 + messageLength);
messageOs.writeInt64(0);
messageOs.writeInt64(messageId);
messageOs.writeInt32(messageData.length);
messageOs.writeRaw(messageData);
messageOs.writeInt32(messageLength);
message.serializeToStream(messageOs);
message.freeResources();
byte[] transportData = messageOs.toByteArray();
datacenter.connection.sendData(transportData, null, false);
return transportData;
datacenter.connection.sendData(messageOs, false, false);
return messageOs;
}
void processMessage(TLObject message, long messageId) {
@ -196,7 +198,7 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
processedPQRes = true;
final TLRPC.TL_resPQ resPq = (TLRPC.TL_resPQ)message;
if (Arrays.equals(authNonce, resPq.nonce)) {
if (Utilities.arraysEquals(authNonce, 0, resPq.nonce, 0)) {
final HashMap<String, Object> publicKey = selectPublicKey(resPq.server_public_key_fingerprints);
if (publicKey == null) {
FileLog.e("tmessages", "***** Couldn't find valid server public key");
@ -276,7 +278,10 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
msgsAck.msg_ids.add(messageIdf);
sendMessageData(msgsAck, generateMessageId());
reqPQMsgData = null;
if (reqPQMsgData != null) {
BuffersStorage.getInstance().reuseFreeBuffer(reqPQMsgData);
reqPQMsgData = null;
}
reqDHMsgData = sendMessageData(reqDH, generateMessageId());
}
});
@ -322,33 +327,33 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
System.arraycopy(authNewNonce, 0, newNonce0_4, 0, 4);
tmpAesIv.writeRaw(newNonce0_4);
byte[] answerWithHash = Utilities.aesIgeEncryption(serverDhParams.encrypted_answer, tmpAesKey.toByteArray(), tmpAesIv.toByteArray(), false, false, 0);
byte[] answerHash = new byte[20];
System.arraycopy(answerWithHash, 0, answerHash, 0, 20);
ByteBufferDesc answerWithHash = BuffersStorage.getInstance().getFreeBuffer(serverDhParams.encrypted_answer.length);
answerWithHash.writeRaw(serverDhParams.encrypted_answer);
answerWithHash.position(0);
Utilities.aesIgeEncryption(answerWithHash.buffer, tmpAesKey.toByteArray(), tmpAesIv.toByteArray(), false, false, 0, serverDhParams.encrypted_answer.length);
byte[] answerHash = new byte[20];
answerWithHash.readRaw(answerHash);
byte[] answerData = new byte[answerWithHash.length - 20];
System.arraycopy(answerWithHash, 20, answerData, 0, answerWithHash.length - 20);
boolean hashVerified = false;
for (int i = 0; i < 16; i++) {
byte[] computedAnswerHash = Utilities.computeSHA1(answerData);
if (Arrays.equals(computedAnswerHash, answerHash)) {
byte[] computedAnswerHash = Utilities.computeSHA1(answerWithHash.buffer, 20, answerWithHash.limit() - i);
if (Utilities.arraysEquals(computedAnswerHash, 0, answerHash, 0)) {
hashVerified = true;
break;
}
byte[] answerData2 = new byte[answerData.length - 1];
System.arraycopy(answerData, 0, answerData2, 0, answerData.length - 1);
answerData = answerData2;
}
if (!hashVerified) {
FileLog.e("tmessages", "***** Couldn't decode DH params");
beginHandshake(false);
BuffersStorage.getInstance().reuseFreeBuffer(answerWithHash);
return;
}
SerializedData answerIs = new SerializedData(answerData);
int constructor = answerIs.readInt32();
TLRPC.TL_server_DH_inner_data dhInnerData = (TLRPC.TL_server_DH_inner_data)TLClassStore.Instance().TLdeserialize(answerIs, constructor);
int constructor = answerWithHash.readInt32();
TLRPC.TL_server_DH_inner_data dhInnerData = (TLRPC.TL_server_DH_inner_data)TLClassStore.Instance().TLdeserialize(answerWithHash, constructor);
BuffersStorage.getInstance().reuseFreeBuffer(answerWithHash);
if (!(dhInnerData instanceof TLRPC.TL_server_DH_inner_data)) {
FileLog.e("tmessages", "***** Couldn't parse decoded DH params");
@ -360,12 +365,12 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
throw new RuntimeException("bad prime");
}
if (!Arrays.equals(authNonce, dhInnerData.nonce)) {
if (!Utilities.arraysEquals(authNonce, 0, dhInnerData.nonce, 0)) {
FileLog.e("tmessages", "***** Invalid DH nonce");
beginHandshake(false);
return;
}
if (!Arrays.equals(authServerNonce, dhInnerData.server_nonce)) {
if (!Utilities.arraysEquals(authServerNonce, 0, dhInnerData.server_nonce, 0)) {
FileLog.e("tmessages", "***** Invalid DH server nonce");
beginHandshake(false);
return;
@ -427,50 +432,66 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
clientInnerData.server_nonce = authServerNonce;
clientInnerData.g_b = g_b.toByteArray();
clientInnerData.retry_id = 0;
SerializedData os = new SerializedData();
clientInnerData.serializeToStream(os);
byte[] clientInnerDataBytes = os.toByteArray();
SerializedData clientDataWithHash = new SerializedData();
clientDataWithHash.writeRaw(Utilities.computeSHA1(clientInnerDataBytes));
clientDataWithHash.writeRaw(clientInnerDataBytes);
byte[] bb = new byte[1];
while (clientDataWithHash.length() % 16 != 0) {
ByteBufferDesc os = BuffersStorage.getInstance().getFreeBuffer(clientInnerData.getObjectSize());
clientInnerData.serializeToStream(os);
int len = os.length() + 20;
int extraLen = len % 16 != 0 ? 16 - len % 16 : 0;
ByteBufferDesc clientDataWithHash = BuffersStorage.getInstance().getFreeBuffer(len + extraLen);
clientDataWithHash.writeRaw(Utilities.computeSHA1(os.buffer));
os.position(0);
clientDataWithHash.writeRaw(os);
if (extraLen != 0) {
byte[] bb = new byte[extraLen];
Utilities.random.nextBytes(bb);
clientDataWithHash.writeByte(bb[0]);
clientDataWithHash.writeRaw(bb);
}
BuffersStorage.getInstance().reuseFreeBuffer(os);
TLRPC.TL_set_client_DH_params setClientDhParams = new TLRPC.TL_set_client_DH_params();
setClientDhParams.nonce = authNonce;
setClientDhParams.server_nonce = authServerNonce;
setClientDhParams.encrypted_data = Utilities.aesIgeEncryption(clientDataWithHash.toByteArray(), tmpAesKey.toByteArray(), tmpAesIv.toByteArray(), true, false, 0);
Utilities.aesIgeEncryption(clientDataWithHash.buffer, tmpAesKey.toByteArray(), tmpAesIv.toByteArray(), true, false, 0, clientDataWithHash.length());
setClientDhParams.encrypted_data = clientDataWithHash;
TLRPC.TL_msgs_ack msgsAck = new TLRPC.TL_msgs_ack();
msgsAck.msg_ids = new ArrayList<Long>();
msgsAck.msg_ids.add(messageId);
sendMessageData(msgsAck, generateMessageId());
reqDHMsgData = null;
if (reqDHMsgData != null) {
BuffersStorage.getInstance().reuseFreeBuffer(reqDHMsgData);
reqDHMsgData = null;
}
setClientDHParamsMsgData = sendMessageData(setClientDhParams, generateMessageId());
} else {
FileLog.e("tmessages", "***** Couldn't set DH params");
beginHandshake(false);
}
} else if (message instanceof TLRPC.Set_client_DH_params_answer) {
if (setClientDHParamsMsgData != null) {
BuffersStorage.getInstance().reuseFreeBuffer(setClientDHParamsMsgData);
setClientDHParamsMsgData = null;
}
TLRPC.Set_client_DH_params_answer dhAnswer = (TLRPC.Set_client_DH_params_answer)message;
if (!Arrays.equals(authNonce, dhAnswer.nonce)) {
if (!Utilities.arraysEquals(authNonce, 0, dhAnswer.nonce, 0)) {
FileLog.e("tmessages", "***** Invalid DH answer nonce");
beginHandshake(false);
return;
}
if (!Arrays.equals(authServerNonce, dhAnswer.server_nonce)) {
if (!Utilities.arraysEquals(authServerNonce, 0, dhAnswer.server_nonce, 0)) {
FileLog.e("tmessages", "***** Invalid DH answer server nonce");
beginHandshake(false);
return;
}
reqDHMsgData = null;
if (reqDHMsgData != null) {
BuffersStorage.getInstance().reuseFreeBuffer(reqDHMsgData);
reqDHMsgData = null;
}
TLRPC.TL_msgs_ack msgsAck = new TLRPC.TL_msgs_ack();
msgsAck.msg_ids = new ArrayList<Long>();
@ -507,7 +528,7 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
if (message instanceof TLRPC.TL_dh_gen_ok) {
TLRPC.TL_dh_gen_ok dhGenOk = (TLRPC.TL_dh_gen_ok)message;
if (!Arrays.equals(newNonceHash1, dhGenOk.new_nonce_hash1)) {
if (!Utilities.arraysEquals(newNonceHash1, 0, dhGenOk.new_nonce_hash1, 0)) {
FileLog.e("tmessages", "***** Invalid DH answer nonce hash 1");
beginHandshake(false);
return;
@ -532,7 +553,7 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
});
} else if (message instanceof TLRPC.TL_dh_gen_retry) {
TLRPC.TL_dh_gen_retry dhRetry = (TLRPC.TL_dh_gen_retry)message;
if (!Arrays.equals(newNonceHash2, dhRetry.new_nonce_hash2)) {
if (!Utilities.arraysEquals(newNonceHash2, 0, dhRetry.new_nonce_hash2, 0)) {
FileLog.e("tmessages", "***** Invalid DH answer nonce hash 2");
beginHandshake(false);
return;
@ -541,7 +562,7 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
beginHandshake(false);
} else if (message instanceof TLRPC.TL_dh_gen_fail) {
TLRPC.TL_dh_gen_fail dhFail = (TLRPC.TL_dh_gen_fail)message;
if (!Arrays.equals(newNonceHash3, dhFail.new_nonce_hash3)) {
if (!Utilities.arraysEquals(newNonceHash3, 0, dhFail.new_nonce_hash3, 0)) {
FileLog.e("tmessages", "***** Invalid DH answer nonce hash 3");
beginHandshake(false);
return;
@ -560,11 +581,6 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
}
}
@Override
public void tcpConnectionProgressChanged(TcpConnection connection, long messageId, int currentSize, int length) {
}
@Override
public void tcpConnectionClosed(final TcpConnection connection) {
wasDisconnect = true;
@ -582,11 +598,11 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
return;
}
if (reqPQMsgData != null) {
datacenter.connection.sendData(reqPQMsgData, null, false);
datacenter.connection.sendData(reqPQMsgData, false, false);
} else if (reqDHMsgData != null) {
datacenter.connection.sendData(reqDHMsgData, null, false);
datacenter.connection.sendData(reqDHMsgData, false, false);
} else if (setClientDHParamsMsgData != null) {
datacenter.connection.sendData(setClientDHParamsMsgData, null, false);
datacenter.connection.sendData(setClientDHParamsMsgData, false, false);
}
}

View File

@ -14,9 +14,6 @@ public class RPCRequest {
public interface RPCRequestDelegate {
void run(TLObject response, TLRPC.TL_error error);
}
public interface RPCProgressDelegate {
void progress(int length, int progress);
}
public interface RPCQuickAckDelegate {
void quickAck();
}
@ -29,7 +26,7 @@ public class RPCRequest {
public static int RPCRequestClassCanCompress = 32;
public static int RPCRequestClassPush = 64;
public static int RPCRequestClassWithoutLogin = 128;
public static int RPCRequestClassDownloadMedia2 = 256;
public static int RPCRequestClassTryDifferentDc = 256;
static int RPCRequestClassTransportMask = (RPCRequestClassGeneric | RPCRequestClassDownloadMedia | RPCRequestClassUploadMedia);
@ -38,14 +35,15 @@ public class RPCRequest {
int serverFailureCount;
int flags;
public int retryCount = 0;
protected int retryCount = 0;
protected int lastResendTime = 0;
protected boolean completed = false;
TLObject rawRequest;
TLObject rpcRequest;
int serializedLength;
RPCRequestDelegate completionBlock;
RPCProgressDelegate progressBlock;
RPCQuickAckDelegate quickAckBlock;
boolean requiresCompletion;

View File

@ -412,6 +412,14 @@ public class TLClassStore {
classStore.put(TLRPC.TL_decryptedMessageActionFlushHistory.constructor, TLRPC.TL_decryptedMessageActionFlushHistory.class);
classStore.put(TLRPC.TL_decryptedMessageActionScreenshotMessages.constructor, TLRPC.TL_decryptedMessageActionScreenshotMessages.class);
classStore.put(TLRPC.TL_messageEcryptedAction.constructor, TLRPC.TL_messageEcryptedAction.class);
classStore.put(TLRPC.TL_decryptedMessageActionNotifyLayer.constructor, TLRPC.TL_decryptedMessageActionNotifyLayer.class);
classStore.put(TLRPC.TL_decryptedMessageActionReadMessages.constructor, TLRPC.TL_decryptedMessageActionReadMessages.class);
classStore.put(TLRPC.TL_updateNotifySettings.constructor, TLRPC.TL_updateNotifySettings.class);
classStore.put(TLRPC.TL_updateUserBlocked.constructor, TLRPC.TL_updateUserBlocked.class);
classStore.put(TLRPC.TL_notifyAll.constructor, TLRPC.TL_notifyAll.class);
classStore.put(TLRPC.TL_notifyChats.constructor, TLRPC.TL_notifyChats.class);
classStore.put(TLRPC.TL_notifyUsers.constructor, TLRPC.TL_notifyUsers.class);
classStore.put(TLRPC.TL_notifyPeer.constructor, TLRPC.TL_notifyPeer.class);
classStore.put(TLRPC.TL_msg_container.constructor, TLRPC.TL_msg_container.class);
classStore.put(TLRPC.TL_fileEncryptedLocation.constructor, TLRPC.TL_fileEncryptedLocation.class);
@ -427,6 +435,10 @@ public class TLClassStore {
classStore.put(TLRPC.TL_messageActionLoginUnknownLocation.constructor, TLRPC.TL_messageActionLoginUnknownLocation.class);
classStore.put(TLRPC.TL_encryptedChat_old.constructor, TLRPC.TL_encryptedChat_old.class);
classStore.put(TLRPC.TL_encryptedChatRequested_old.constructor, TLRPC.TL_encryptedChatRequested_old.class);
classStore.put(TLRPC.TL_decryptedMessageMediaVideo_old.constructor, TLRPC.TL_decryptedMessageMediaVideo_old.class);
classStore.put(TLRPC.TL_decryptedMessageMediaAudio_old.constructor, TLRPC.TL_decryptedMessageMediaAudio_old.class);
classStore.put(TLRPC.TL_audio_old.constructor, TLRPC.TL_audio_old.class);
classStore.put(TLRPC.TL_video_old.constructor, TLRPC.TL_video_old.class);
}
static TLClassStore store = null;

View File

@ -42,4 +42,10 @@ public class TLObject {
public void freeResources() {
}
public int getObjectSize() {
ByteBufferDesc bufferDesc = new ByteBufferDesc(true);
serializeToStream(bufferDesc);
return bufferDesc.length();
}
}

View File

@ -140,6 +140,51 @@ public class TLRPC {
}
}
public static class NotifyPeer extends TLObject {
public Peer peer;
}
public static class TL_notifyAll extends NotifyPeer {
public static int constructor = 0x74d07c60;
public void serializeToStream(AbsSerializedData stream) {
stream.writeInt32(constructor);
}
}
public static class TL_notifyChats extends NotifyPeer {
public static int constructor = 0xc007cec3;
public void serializeToStream(AbsSerializedData stream) {
stream.writeInt32(constructor);
}
}
public static class TL_notifyUsers extends NotifyPeer {
public static int constructor = 0xb4c83b4c;
public void serializeToStream(AbsSerializedData stream) {
stream.writeInt32(constructor);
}
}
public static class TL_notifyPeer extends NotifyPeer {
public static int constructor = 0x9fd40bd8;
public void readParams(AbsSerializedData stream) {
peer = (Peer)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32());
}
public void serializeToStream(AbsSerializedData stream) {
stream.writeInt32(constructor);
peer.serializeToStream(stream);
}
}
public static class TL_auth_checkedPhone extends TLObject {
public static int constructor = 0xe300cc3b;
@ -1245,7 +1290,7 @@ public class TLRPC {
}
public static class TL_audio extends Audio {
public static int constructor = 0x427425e7;
public static int constructor = 0xc7ac6496;
public void readParams(AbsSerializedData stream) {
@ -1254,6 +1299,7 @@ public class TLRPC {
user_id = stream.readInt32();
date = stream.readInt32();
duration = stream.readInt32();
mime_type = stream.readString();
size = stream.readInt32();
dc_id = stream.readInt32();
}
@ -1265,6 +1311,7 @@ public class TLRPC {
stream.writeInt32(user_id);
stream.writeInt32(date);
stream.writeInt32(duration);
stream.writeString(mime_type);
stream.writeInt32(size);
stream.writeInt32(dc_id);
}
@ -2515,7 +2562,7 @@ public class TLRPC {
}
public static class TL_video extends Video {
public static int constructor = 0x5a04a49f;
public static int constructor = 0x388fa391;
public void readParams(AbsSerializedData stream) {
@ -2525,6 +2572,7 @@ public class TLRPC {
date = stream.readInt32();
caption = stream.readString();
duration = stream.readInt32();
mime_type = stream.readString();
size = stream.readInt32();
thumb = (PhotoSize)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32());
dc_id = stream.readInt32();
@ -2540,6 +2588,7 @@ public class TLRPC {
stream.writeInt32(date);
stream.writeString(caption);
stream.writeInt32(duration);
stream.writeString(mime_type);
stream.writeInt32(size);
thumb.serializeToStream(stream);
stream.writeInt32(dc_id);
@ -2820,7 +2869,7 @@ public class TLRPC {
}
public static class TL_inputMediaUploadedThumbVideo extends InputMedia {
public static int constructor = 0xe628a145;
public static int constructor = 0x9912dabf;
public void readParams(AbsSerializedData stream) {
@ -2829,6 +2878,7 @@ public class TLRPC {
duration = stream.readInt32();
w = stream.readInt32();
h = stream.readInt32();
mime_type = stream.readString();
}
public void serializeToStream(AbsSerializedData stream) {
@ -2838,6 +2888,7 @@ public class TLRPC {
stream.writeInt32(duration);
stream.writeInt32(w);
stream.writeInt32(h);
stream.writeString(mime_type);
}
}
@ -2856,23 +2907,25 @@ public class TLRPC {
}
public static class TL_inputMediaUploadedAudio extends InputMedia {
public static int constructor = 0x61a6d436;
public static int constructor = 0x4e498cab;
public void readParams(AbsSerializedData stream) {
file = (InputFile)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32());
duration = stream.readInt32();
mime_type = stream.readString();
}
public void serializeToStream(AbsSerializedData stream) {
stream.writeInt32(constructor);
file.serializeToStream(stream);
stream.writeInt32(duration);
stream.writeString(mime_type);
}
}
public static class TL_inputMediaUploadedVideo extends InputMedia {
public static int constructor = 0x4847d92a;
public static int constructor = 0x133ad6f6;
public void readParams(AbsSerializedData stream) {
@ -2880,6 +2933,7 @@ public class TLRPC {
duration = stream.readInt32();
w = stream.readInt32();
h = stream.readInt32();
mime_type = stream.readString();
}
public void serializeToStream(AbsSerializedData stream) {
@ -2888,6 +2942,7 @@ public class TLRPC {
stream.writeInt32(duration);
stream.writeInt32(w);
stream.writeInt32(h);
stream.writeString(mime_type);
}
}
@ -3209,9 +3264,10 @@ public class TLRPC {
}
public static class TL_contacts_importedContacts extends TLObject {
public static int constructor = 0xd1cd0a4c;
public static int constructor = 0xad524315;
public ArrayList<TL_importedContact> imported = new ArrayList<TL_importedContact>();
public ArrayList<Long> retry_contacts = new ArrayList<Long>();
public ArrayList<User> users = new ArrayList<User>();
public void readParams(AbsSerializedData stream) {
@ -3222,6 +3278,11 @@ public class TLRPC {
}
stream.readInt32();
count = stream.readInt32();
for (int a = 0; a < count; a++) {
retry_contacts.add(stream.readInt64());
}
stream.readInt32();
count = stream.readInt32();
for (int a = 0; a < count; a++) {
users.add((User)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32()));
}
@ -3236,6 +3297,12 @@ public class TLRPC {
imported.get(a).serializeToStream(stream);
}
stream.writeInt32(0x1cb5c415);
count = retry_contacts.size();
stream.writeInt32(count);
for (int a = 0; a < count; a++) {
stream.writeInt64(retry_contacts.get(a));
}
stream.writeInt32(0x1cb5c415);
count = users.size();
stream.writeInt32(count);
for (int a = 0; a < count; a++) {
@ -3275,6 +3342,8 @@ public class TLRPC {
public ArrayList<Integer> messages = new ArrayList<Integer>();
public int pts;
public int version;
public NotifyPeer peer;
public PeerNotifySettings notify_settings;
public String first_name;
public String last_name;
public int qts;
@ -3283,6 +3352,7 @@ public class TLRPC {
public ArrayList<TL_dcOption> dc_options = new ArrayList<TL_dcOption>();
public ChatParticipants participants;
public EncryptedChat chat;
public boolean blocked;
public long auth_key_id;
public String device;
public String location;
@ -3396,6 +3466,22 @@ public class TLRPC {
}
}
public static class TL_updateNotifySettings extends Update {
public static int constructor = 0xbec268ef;
public void readParams(AbsSerializedData stream) {
peer = (NotifyPeer)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32());
notify_settings = (PeerNotifySettings)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32());
}
public void serializeToStream(AbsSerializedData stream) {
stream.writeInt32(constructor);
peer.serializeToStream(stream);
notify_settings.serializeToStream(stream);
}
}
public static class TL_updateUserTyping extends Update {
public static int constructor = 0x6baa8508;
@ -3586,6 +3672,22 @@ public class TLRPC {
}
}
public static class TL_updateUserBlocked extends Update {
public static int constructor = 0x80ece81a;
public void readParams(AbsSerializedData stream) {
user_id = stream.readInt32();
blocked = stream.readBool();
}
public void serializeToStream(AbsSerializedData stream) {
stream.writeInt32(constructor);
stream.writeInt32(user_id);
stream.writeBool(blocked);
}
}
public static class TL_updateActivation extends Update {
public static int constructor = 0x6f690963;
@ -3847,6 +3949,7 @@ public class TLRPC {
}
public static class DecryptedMessageAction extends TLObject {
public int layer;
public int ttl_seconds;
public ArrayList<Long> random_ids = new ArrayList<Long>();
}
@ -3872,6 +3975,43 @@ public class TLRPC {
}
}
public static class TL_decryptedMessageActionNotifyLayer extends DecryptedMessageAction {
public static int constructor = 0xf3048883;
public void readParams(AbsSerializedData stream) {
layer = stream.readInt32();
}
public void serializeToStream(AbsSerializedData stream) {
stream.writeInt32(constructor);
stream.writeInt32(layer);
}
}
public static class TL_decryptedMessageActionReadMessages extends DecryptedMessageAction {
public static int constructor = 0xc4f40be;
public void readParams(AbsSerializedData stream) {
stream.readInt32();
int count = stream.readInt32();
for (int a = 0; a < count; a++) {
random_ids.add(stream.readInt64());
}
}
public void serializeToStream(AbsSerializedData stream) {
stream.writeInt32(constructor);
stream.writeInt32(0x1cb5c415);
int count = random_ids.size();
stream.writeInt32(count);
for (Long random_id : random_ids) {
stream.writeInt64(random_id);
}
}
}
public static class contacts_MyLink extends TLObject {
public boolean contact;
}
@ -4497,11 +4637,12 @@ public class TLRPC {
}
public static class TL_decryptedMessageMediaAudio extends DecryptedMessageMedia {
public static int constructor = 0x6080758f;
public static int constructor = 0x57e0a9cb;
public void readParams(AbsSerializedData stream) {
duration = stream.readInt32();
mime_type = stream.readString();
size = stream.readInt32();
key = stream.readByteArray();
iv = stream.readByteArray();
@ -4510,6 +4651,7 @@ public class TLRPC {
public void serializeToStream(AbsSerializedData stream) {
stream.writeInt32(constructor);
stream.writeInt32(duration);
stream.writeString(mime_type);
stream.writeInt32(size);
stream.writeByteArray(key);
stream.writeByteArray(iv);
@ -4517,7 +4659,7 @@ public class TLRPC {
}
public static class TL_decryptedMessageMediaVideo extends DecryptedMessageMedia {
public static int constructor = 0x4cee6ef3;
public static int constructor = 0x524a415d;
public void readParams(AbsSerializedData stream) {
@ -4525,6 +4667,7 @@ public class TLRPC {
thumb_w = stream.readInt32();
thumb_h = stream.readInt32();
duration = stream.readInt32();
mime_type = stream.readString();
w = stream.readInt32();
h = stream.readInt32();
size = stream.readInt32();
@ -4538,6 +4681,7 @@ public class TLRPC {
stream.writeInt32(thumb_w);
stream.writeInt32(thumb_h);
stream.writeInt32(duration);
stream.writeString(mime_type);
stream.writeInt32(w);
stream.writeInt32(h);
stream.writeInt32(size);
@ -6169,31 +6313,6 @@ public class TLRPC {
}
}
public static class TL_set_client_DH_params extends TLObject {
public static int constructor = 0xf5045f1f;
public byte[] nonce;
public byte[] server_nonce;
public byte[] encrypted_data;
public Class responseClass () {
return Set_client_DH_params_answer.class;
}
public void readParams(AbsSerializedData stream) {
nonce = stream.readData(16);
server_nonce = stream.readData(16);
encrypted_data = stream.readByteArray();
}
public void serializeToStream(AbsSerializedData stream) {
stream.writeInt32(constructor);
stream.writeRaw(nonce);
stream.writeRaw(server_nonce);
stream.writeByteArray(encrypted_data);
}
}
public static class TL_auth_checkPhone extends TLObject {
public static int constructor = 0x6fe51dfb;
@ -8000,59 +8119,6 @@ public class TLRPC {
}
}
public static class TL_messages_sendEncrypted extends TLObject {
public static int constructor = 0xa9776773;
public TL_inputEncryptedChat peer;
public long random_id;
public byte[] data;
public Class responseClass () {
return messages_SentEncryptedMessage.class;
}
public void readParams(AbsSerializedData stream) {
peer = (TL_inputEncryptedChat)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32());
random_id = stream.readInt64();
data = stream.readByteArray();
}
public void serializeToStream(AbsSerializedData stream) {
stream.writeInt32(constructor);
peer.serializeToStream(stream);
stream.writeInt64(random_id);
stream.writeByteArray(data);
}
}
public static class TL_messages_sendEncryptedFile extends TLObject {
public static int constructor = 0x9a901b66;
public TL_inputEncryptedChat peer;
public long random_id;
public byte[] data;
public InputEncryptedFile file;
public Class responseClass () {
return messages_SentEncryptedMessage.class;
}
public void readParams(AbsSerializedData stream) {
peer = (TL_inputEncryptedChat)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32());
random_id = stream.readInt64();
data = stream.readByteArray();
file = (InputEncryptedFile)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32());
}
public void serializeToStream(AbsSerializedData stream) {
stream.writeInt32(constructor);
peer.serializeToStream(stream);
stream.writeInt64(random_id);
stream.writeByteArray(data);
file.serializeToStream(stream);
}
}
public static class TL_messages_sendEncryptedService extends TLObject {
public static int constructor = 0x32d439a4;
@ -8080,6 +8146,98 @@ public class TLRPC {
//manually created
public static class TL_set_client_DH_params extends TLObject {
public static int constructor = 0xf5045f1f;
public byte[] nonce;
public byte[] server_nonce;
public ByteBufferDesc encrypted_data;
public Class responseClass () {
return Set_client_DH_params_answer.class;
}
public void serializeToStream(AbsSerializedData stream) {
stream.writeInt32(constructor);
stream.writeRaw(nonce);
stream.writeRaw(server_nonce);
stream.writeByteBuffer(encrypted_data);
}
@Override
public void freeResources() {
if (disableFree) {
return;
}
if (encrypted_data != null) {
BuffersStorage.getInstance().reuseFreeBuffer(encrypted_data);
encrypted_data = null;
}
}
}
public static class TL_messages_sendEncrypted extends TLObject {
public static int constructor = 0xa9776773;
public TL_inputEncryptedChat peer;
public long random_id;
public ByteBufferDesc data;
public Class responseClass () {
return messages_SentEncryptedMessage.class;
}
public void serializeToStream(AbsSerializedData stream) {
stream.writeInt32(constructor);
peer.serializeToStream(stream);
stream.writeInt64(random_id);
stream.writeByteBuffer(data);
}
@Override
public void freeResources() {
if (disableFree) {
return;
}
if (data != null) {
BuffersStorage.getInstance().reuseFreeBuffer(data);
data = null;
}
}
}
public static class TL_messages_sendEncryptedFile extends TLObject {
public static int constructor = 0x9a901b66;
public TL_inputEncryptedChat peer;
public long random_id;
public ByteBufferDesc data;
public InputEncryptedFile file;
public Class responseClass () {
return messages_SentEncryptedMessage.class;
}
public void serializeToStream(AbsSerializedData stream) {
stream.writeInt32(constructor);
peer.serializeToStream(stream);
stream.writeInt64(random_id);
stream.writeByteBuffer(data);
file.serializeToStream(stream);
}
@Override
public void freeResources() {
if (disableFree) {
return;
}
if (data != null) {
BuffersStorage.getInstance().reuseFreeBuffer(data);
data = null;
}
}
}
public static class UserStatus extends TLObject {
public int expires;
}
@ -8313,6 +8471,7 @@ public class TLRPC {
for (int a = 0; a < count; a++) {
TL_futureSalt salt = new TL_futureSalt();
salt.readParams(stream);
salts.add(salt);
}
}
@ -8692,11 +8851,12 @@ public class TLRPC {
}
public static class TL_dialog extends TLObject {
public static int constructor = 0x214a8cdf;
public static int constructor = 0xab3a99ac;
public Peer peer;
public int top_message;
public int unread_count;
public PeerNotifySettings notify_settings;
public int last_message_date;
public long id;
public int last_read;
@ -8705,6 +8865,7 @@ public class TLRPC {
peer = (Peer)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32());
top_message = stream.readInt32();
unread_count = stream.readInt32();
notify_settings = (PeerNotifySettings)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32());
}
public void serializeToStream(AbsSerializedData stream) {
@ -8712,6 +8873,7 @@ public class TLRPC {
peer.serializeToStream(stream);
stream.writeInt32(top_message);
stream.writeInt32(unread_count);
notify_settings.serializeToStream(stream);
}
}
@ -8770,6 +8932,7 @@ public class TLRPC {
public int date;
public String caption;
public int duration;
public String mime_type;
public int size;
public PhotoSize thumb;
public int dc_id;
@ -8801,6 +8964,7 @@ public class TLRPC {
public int user_id;
public int date;
public int duration;
public String mime_type;
public int size;
public int dc_id;
public String path;
@ -8974,8 +9138,8 @@ public class TLRPC {
}
}
public static class invokeWithLayer12 extends TLObject {
public static int constructor = 0xdda60d3c;
public static class invokeWithLayer14 extends TLObject {
public static int constructor = 0x2b9b08fa;
public TLObject query;
@ -9226,4 +9390,114 @@ public class TLRPC {
public byte[] key;
public byte[] iv;
}
public static class TL_decryptedMessageMediaVideo_old extends TL_decryptedMessageMediaVideo {
public static int constructor = 0x4cee6ef3;
public void readParams(AbsSerializedData stream) {
thumb = stream.readByteArray();
thumb_w = stream.readInt32();
thumb_h = stream.readInt32();
duration = stream.readInt32();
w = stream.readInt32();
h = stream.readInt32();
size = stream.readInt32();
key = stream.readByteArray();
iv = stream.readByteArray();
}
public void serializeToStream(AbsSerializedData stream) {
stream.writeInt32(constructor);
stream.writeByteArray(thumb);
stream.writeInt32(thumb_w);
stream.writeInt32(thumb_h);
stream.writeInt32(duration);
stream.writeInt32(w);
stream.writeInt32(h);
stream.writeInt32(size);
stream.writeByteArray(key);
stream.writeByteArray(iv);
}
}
public static class TL_decryptedMessageMediaAudio_old extends TL_decryptedMessageMediaAudio {
public static int constructor = 0x6080758f;
public void readParams(AbsSerializedData stream) {
duration = stream.readInt32();
size = stream.readInt32();
key = stream.readByteArray();
iv = stream.readByteArray();
}
public void serializeToStream(AbsSerializedData stream) {
stream.writeInt32(constructor);
stream.writeInt32(duration);
stream.writeInt32(size);
stream.writeByteArray(key);
stream.writeByteArray(iv);
}
}
public static class TL_audio_old extends TL_audio {
public static int constructor = 0x427425e7;
public void readParams(AbsSerializedData stream) {
id = stream.readInt64();
access_hash = stream.readInt64();
user_id = stream.readInt32();
date = stream.readInt32();
duration = stream.readInt32();
size = stream.readInt32();
dc_id = stream.readInt32();
}
public void serializeToStream(AbsSerializedData stream) {
stream.writeInt32(constructor);
stream.writeInt64(id);
stream.writeInt64(access_hash);
stream.writeInt32(user_id);
stream.writeInt32(date);
stream.writeInt32(duration);
stream.writeInt32(size);
stream.writeInt32(dc_id);
}
}
public static class TL_video_old extends TL_video {
public static int constructor = 0x5a04a49f;
public void readParams(AbsSerializedData stream) {
id = stream.readInt64();
access_hash = stream.readInt64();
user_id = stream.readInt32();
date = stream.readInt32();
caption = stream.readString();
duration = stream.readInt32();
size = stream.readInt32();
thumb = (PhotoSize)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32());
dc_id = stream.readInt32();
w = stream.readInt32();
h = stream.readInt32();
}
public void serializeToStream(AbsSerializedData stream) {
stream.writeInt32(constructor);
stream.writeInt64(id);
stream.writeInt64(access_hash);
stream.writeInt32(user_id);
stream.writeInt32(date);
stream.writeString(caption);
stream.writeInt32(duration);
stream.writeInt32(size);
thumb.serializeToStream(stream);
stream.writeInt32(dc_id);
stream.writeInt32(w);
stream.writeInt32(h);
}
}
}

View File

@ -33,7 +33,6 @@ public class TcpConnection extends ConnectionContext {
public abstract void tcpConnectionConnected(TcpConnection connection);
public abstract void tcpConnectionQuiackAckReceived(TcpConnection connection, int ack);
public abstract void tcpConnectionReceivedData(TcpConnection connection, ByteBufferDesc data, int length);
public abstract void tcpConnectionProgressChanged(TcpConnection connection, long messageId, int currentSize, int length);
}
private static PyroSelector selector;
@ -46,7 +45,6 @@ public class TcpConnection extends ConnectionContext {
private int failedConnectionCount;
public TcpConnectionDelegate delegate;
private ByteBufferDesc restOfTheData;
private long lastMessageId = 0;
private boolean hasSomeDataSinceLastConnect = false;
private int willRetryConnectCount = 5;
private boolean isNextPort = false;
@ -284,8 +282,8 @@ public class TcpConnection extends ConnectionContext {
connect();
}
public void sendData(final byte[] data, final ByteBufferDesc buff, final boolean reportAck) {
if (data == null && buff == null) {
public void sendData(final ByteBufferDesc buff, final boolean canReuse, final boolean reportAck) {
if (buff == null) {
return;
}
selector.scheduleTask(new Runnable() {
@ -298,16 +296,13 @@ public class TcpConnection extends ConnectionContext {
}
if (client == null || client.isDisconnected()) {
BuffersStorage.getInstance().reuseFreeBuffer(buff);
if (canReuse) {
BuffersStorage.getInstance().reuseFreeBuffer(buff);
}
return;
}
int bufferLen = 0;
if (data != null) {
bufferLen = data.length;
} else if (buff != null) {
bufferLen = buff.limit();
}
int bufferLen = buff.limit();
int packetLength = bufferLen / 4;
if (packetLength < 0x7f) {
@ -336,10 +331,9 @@ public class TcpConnection extends ConnectionContext {
}
buffer.writeInt32(packetLength);
}
if (data != null) {
buffer.writeRaw(data);
} else {
buffer.writeRaw(buff);
buffer.writeRaw(buff);
if (canReuse) {
BuffersStorage.getInstance().reuseFreeBuffer(buff);
}
@ -389,19 +383,6 @@ public class TcpConnection extends ConnectionContext {
buffer.limit(oldLimit);
if (restOfTheData.position() != lastPacketLength) {
//FileLog.e("tmessages", this + " don't get much data to restOfTheData");
if (lastMessageId != -1 && lastMessageId != 0) {
if (delegate != null) {
final TcpConnectionDelegate finalDelegate = delegate;
final int arg2 = restOfTheData.position();
final int arg3 = lastPacketLength;
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
finalDelegate.tcpConnectionProgressChanged(TcpConnection.this, lastMessageId, arg2, arg3);
}
});
}
}
return;
} else {
//FileLog.e("tmessages", this + " get much data to restOfTheData - OK!");
@ -424,7 +405,7 @@ public class TcpConnection extends ConnectionContext {
datacenter.storeCurrentAddressAndPortNum();
isNextPort = false;
if ((transportRequestClass & RPCRequest.RPCRequestClassPush) != 0) {
client.setTimeout(60000 * 3 + 20000);
client.setTimeout(60000 * 15);
} else {
client.setTimeout(25000);
}
@ -497,32 +478,10 @@ public class TcpConnection extends ConnectionContext {
if (currentPacketLength < buffer.remaining()) {
FileLog.d("tmessages", TcpConnection.this + " Received message len " + currentPacketLength + " but packet larger " + buffer.remaining());
lastMessageId = 0;
} else if (currentPacketLength == buffer.remaining()) {
FileLog.d("tmessages", TcpConnection.this + " Received message len " + currentPacketLength + " equal to packet size");
lastMessageId = 0;
} else {
FileLog.d("tmessages", TcpConnection.this + " Received packet size less(" + buffer.remaining() + ") then message size(" + currentPacketLength + ")");
if (buffer.remaining() >= 152 && (transportRequestClass & RPCRequest.RPCRequestClassDownloadMedia) != 0) {
if (lastMessageId == 0) {
byte[] temp = new byte[152];
buffer.get(temp);
lastMessageId = ConnectionsManager.getInstance().needsToDecodeMessageIdFromPartialData(TcpConnection.this, temp);
}
if (lastMessageId != -1 && lastMessageId != 0) {
if (delegate != null) {
final TcpConnectionDelegate finalDelegate = delegate;
final int arg2 = buffer.remaining();
final int arg3 = currentPacketLength;
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
finalDelegate.tcpConnectionProgressChanged(TcpConnection.this, lastMessageId, arg2, arg3);
}
});
}
}
}
ByteBufferDesc reuseLater = null;
int len = currentPacketLength + (fByte != 0x7f ? 1 : 4);

View File

@ -12,6 +12,7 @@ import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;
import org.telegram.android.MessagesStorage;
import org.telegram.ui.ApplicationLoader;
import java.io.File;
@ -197,6 +198,5 @@ public class UserConfig {
contactsVersion = 1;
saveIncomingPhotos = false;
saveConfig(true);
MessagesController.getInstance().deleteAllAppAccounts();
}
}

View File

@ -14,11 +14,8 @@ import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Point;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
@ -27,16 +24,12 @@ import android.provider.MediaStore;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.util.Base64;
import android.view.Display;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import net.hockeyapp.android.CrashManager;
import net.hockeyapp.android.CrashManagerListener;
import net.hockeyapp.android.UpdateManager;
import org.telegram.android.LocaleController;
import org.telegram.ui.ApplicationLoader;
import java.io.ByteArrayInputStream;
@ -49,7 +42,6 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.security.KeyFactory;
import java.security.MessageDigest;
@ -59,7 +51,6 @@ import java.security.spec.RSAPublicKeySpec;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -69,16 +60,9 @@ import java.util.zip.GZIPOutputStream;
import javax.crypto.Cipher;
public class Utilities {
public static int statusBarHeight = 0;
public static float density = 1;
public static Point displaySize = new Point();
public static Pattern pattern = Pattern.compile("[0-9]+");
public static SecureRandom random = new SecureRandom();
private final static Integer lock = 1;
private static int prevOrientation = -10;
private static boolean waitingForSms = false;
private static final Integer smsLock = 2;
public static ArrayList<String> goodPrimes = new ArrayList<String>();
@ -108,12 +92,8 @@ public class Utilities {
R.drawable.group_blue,
R.drawable.group_yellow};
public static int externalCacheNotAvailableState = 0;
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
private static final Hashtable<String, Typeface> cache = new Hashtable<String, Typeface>();
public static ProgressDialog progressDialog;
static {
@ -128,7 +108,6 @@ public class Utilities {
FileLog.e("tmessages", e);
}
density = ApplicationLoader.applicationContext.getResources().getDisplayMetrics().density;
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("primes", Context.MODE_PRIVATE);
String primes = preferences.getString("primes", null);
if (primes == null) {
@ -149,104 +128,26 @@ public class Utilities {
goodPrimes.add("C71CAEB9C6B1C9048E6C522F70F13F73980D40238E3E21C14934D037563D930F48198A0AA7C14058229493D22530F4DBFA336F6E0AC925139543AED44CCE7C3720FD51F69458705AC68CD4FE6B6B13ABDC9746512969328454F18FAF8C595F642477FE96BB2A941D5BCD1D4AC8CC49880708FA9B378E3C4F3A9060BEE67CF9A4A4A695811051907E162753B56B0F6B410DBA74D8A84B2A14B3144E0EF1284754FD17ED950D5965B4B9DD46582DB1178D169C6BC465B0D6FF9CA3928FEF5B9AE4E418FC15E83EBEA0F87FA9FF5EED70050DED2849F47BF959D956850CE929851F0D8115F635B105EE2E4E15D04B2454BF6F4FADF034B10403119CD8E3B92FCC5B");
}
}
checkDisplaySize();
}
public native static long doPQNative(long _what);
public native static byte[] aesIgeEncryption(byte[] _what, byte[] _key, byte[] _iv, boolean encrypt, boolean changeIv, int len);
public native static void aesIgeEncryption2(ByteBuffer _what, byte[] _key, byte[] _iv, boolean encrypt, boolean changeIv, int len);
public native static void loadBitmap(String path, int[] bitmap, int scale, int format, int width, int height);
private native static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length);
public static void lockOrientation(Activity activity) {
if (prevOrientation != -10) {
return;
}
try {
prevOrientation = activity.getRequestedOrientation();
WindowManager manager = (WindowManager)activity.getSystemService(Activity.WINDOW_SERVICE);
if (manager != null && manager.getDefaultDisplay() != null) {
int rotation = manager.getDefaultDisplay().getRotation();
int orientation = activity.getResources().getConfiguration().orientation;
if (rotation == Surface.ROTATION_270) {
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
if (Build.VERSION.SDK_INT >= 9) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
} else if (rotation == Surface.ROTATION_90) {
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
if (Build.VERSION.SDK_INT >= 9) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
} else if (rotation == Surface.ROTATION_0) {
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
} else {
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (Build.VERSION.SDK_INT >= 9) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
} else {
if (Build.VERSION.SDK_INT >= 9) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
public static void unlockOrientation(Activity activity) {
try {
if (prevOrientation != -10) {
activity.setRequestedOrientation(prevOrientation);
prevOrientation = -10;
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
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 void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) {
aesIgeEncryption(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length);
}
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);
try {
Matcher matcher = pattern.matcher(value);
if (matcher.find()) {
String num = matcher.group(0);
val = Integer.parseInt(num);
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
return val;
}
@ -259,22 +160,6 @@ public class Utilities {
return null;
}
public static File getCacheDir() {
if (externalCacheNotAvailableState == 1 || externalCacheNotAvailableState == 0 && Environment.getExternalStorageState().startsWith(Environment.MEDIA_MOUNTED)) {
externalCacheNotAvailableState = 1;
File file = ApplicationLoader.applicationContext.getExternalCacheDir();
if (file != null) {
return file;
}
}
externalCacheNotAvailableState = 2;
File file = ApplicationLoader.applicationContext.getCacheDir();
if (file != null) {
return file;
}
return new File("");
}
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
int v;
@ -286,14 +171,6 @@ public class Utilities {
return new String(hexChars);
}
public static int dp(int value) {
return (int)(Math.max(1, density * value));
}
public static int dpf(float value) {
return (int)Math.ceil(density * value);
}
public static boolean isGoodPrime(byte[] prime, int g) {
if (!(g >= 2 && g <= 7)) {
return false;
@ -401,6 +278,18 @@ public class Utilities {
}
}
public static boolean arraysEquals(byte[] arr1, int offset1, byte[] arr2, int offset2) {
if (arr1 == null || arr2 == null || arr1.length - offset1 != arr2.length - offset2 || arr1.length - offset1 < 0) {
return false;
}
for (int a = offset1; a < arr1.length; a++) {
if (arr1[a + offset1] != arr2[a + offset2]) {
return false;
}
}
return true;
}
public static byte[] computeSHA1(byte[] convertme, int offset, int len) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
@ -413,30 +302,29 @@ public class Utilities {
}
public static byte[] computeSHA1(ByteBuffer convertme, int offset, int len) {
int oldp = convertme.position();
int oldl = convertme.limit();
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
int oldp = convertme.position();
int oldl = convertme.limit();
convertme.position(offset);
convertme.limit(len);
md.update(convertme);
convertme.position(oldp);
convertme.limit(oldl);
return md.digest();
} catch (Exception e) {
FileLog.e("tmessages", e);
} finally {
convertme.limit(oldl);
convertme.position(oldp);
}
return null;
}
public static byte[] computeSHA1(ByteBuffer convertme) {
return computeSHA1(convertme, 0, convertme.limit());
}
public static byte[] computeSHA1(byte[] convertme) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
return md.digest(convertme);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
return null;
return computeSHA1(convertme, 0, convertme.length);
}
public static byte[] encryptWithRSA(BigInteger[] key, byte[] data) {
@ -453,26 +341,9 @@ public class Utilities {
return null;
}
public static byte[] longToBytes(long x) {
ByteBuffer buffer = ByteBuffer.allocate(8);
buffer.putLong(x);
return buffer.array();
}
public static long bytesToLong(byte[] bytes) {
ByteBuffer buffer = ByteBuffer.allocate(8);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.put(bytes);
buffer.flip();
return buffer.getLong();
}
public static int bytesToInt(byte[] bytes) {
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.put(bytes);
buffer.flip();
return buffer.getInt();
return ((long) bytes[7] << 56) + (((long) bytes[6] & 0xFF) << 48) + (((long) bytes[5] & 0xFF) << 40) + (((long) bytes[4] & 0xFF) << 32)
+ (((long) bytes[3] & 0xFF) << 24) + (((long) bytes[2] & 0xFF) << 16) + (((long) bytes[1] & 0xFF) << 8) + ((long) bytes[0] & 0xFF);
}
public static MessageKeyData generateMessageKeyData(byte[] authKey, byte[] messageKey, boolean incoming) {
@ -562,51 +433,6 @@ public class Utilities {
return packedData;
}
public static Typeface getTypeface(String assetPath) {
synchronized (cache) {
if (!cache.containsKey(assetPath)) {
try {
Typeface t = Typeface.createFromAsset(ApplicationLoader.applicationContext.getAssets(),
assetPath);
cache.put(assetPath, t);
} catch (Exception e) {
FileLog.e("Typefaces", "Could not get typeface '" + assetPath + "' because " + e.getMessage());
return null;
}
}
return cache.get(assetPath);
}
}
public static void showKeyboard(View view) {
if (view == null) {
return;
}
InputMethodManager inputManager = (InputMethodManager)view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
((InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(view, 0);
}
public static boolean isKeyboardShowed(View view) {
if (view == null) {
return false;
}
InputMethodManager inputManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
return inputManager.isActive(view);
}
public static void hideKeyboard(View view) {
if (view == null) {
return;
}
InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (!imm.isActive()) {
return;
}
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
public static void ShowProgressDialog(final Activity activity, final String message) {
activity.runOnUiThread(new Runnable() {
@Override
@ -624,25 +450,6 @@ public class Utilities {
});
}
public static void checkDisplaySize() {
try {
WindowManager manager = (WindowManager)ApplicationLoader.applicationContext.getSystemService(Context.WINDOW_SERVICE);
if (manager != null) {
Display display = manager.getDefaultDisplay();
if (display != null) {
if(android.os.Build.VERSION.SDK_INT < 13) {
displaySize.set(display.getWidth(), display.getHeight());
} else {
display.getSize(displaySize);
}
FileLog.e("tmessages", "display size = " + displaySize.x + " " + displaySize.y);
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
public static void HideProgressDialog(Activity activity) {
activity.runOnUiThread(new Runnable() {
@Override

View File

@ -16,12 +16,13 @@ import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.util.Linkify;
import org.telegram.android.AndroidUtilities;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.android.LocaleController;
import org.telegram.messenger.TLObject;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.Emoji;
import org.telegram.messenger.MessagesController;
import org.telegram.android.Emoji;
import org.telegram.android.MessagesController;
import org.telegram.messenger.R;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
@ -68,7 +69,7 @@ public class MessageObject {
textPaint.linkColor = 0xff316f9f;
}
textPaint.setTextSize(Utilities.dp(MessagesController.getInstance().fontSize));
textPaint.setTextSize(AndroidUtilities.dp(MessagesController.getInstance().fontSize));
messageOwner = message;
@ -271,7 +272,7 @@ public class MessageObject {
} else {
messageText = message.message;
}
messageText = Emoji.replaceEmoji(messageText, textPaint.getFontMetricsInt(), Utilities.dp(20));
messageText = Emoji.replaceEmoji(messageText, textPaint.getFontMetricsInt(), AndroidUtilities.dp(20));
if (message instanceof TLRPC.TL_message || (message instanceof TLRPC.TL_messageForwarded && (message.media == null || !(message.media instanceof TLRPC.TL_messageMediaEmpty)))) {
if (message.media == null || message.media instanceof TLRPC.TL_messageMediaEmpty) {
@ -397,9 +398,9 @@ public class MessageObject {
int maxWidth;
if (messageOwner.to_id.chat_id != 0) {
maxWidth = Math.min(Utilities.displaySize.x, Utilities.displaySize.y) - Utilities.dp(122);
maxWidth = Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) - AndroidUtilities.dp(122);
} else {
maxWidth = Math.min(Utilities.displaySize.x, Utilities.displaySize.y) - Utilities.dp(80);
maxWidth = Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) - AndroidUtilities.dp(80);
}
StaticLayout textLayout = null;
@ -467,13 +468,11 @@ public class MessageObject {
FileLog.e("tmessages", e);
}
int linesMaxWidth;
int linesMaxWidth = (int)Math.ceil(lastLine);
int lastLineWidthWithLeft;
int linesMaxWidthWithLeft;
boolean hasNonRTL = false;
linesMaxWidth = (int)Math.ceil(lastLine);
if (a == blocksCount - 1) {
lastLineWidth = linesMaxWidth;
}
@ -493,6 +492,13 @@ public class MessageObject {
lineWidth = 0;
}
if (lineWidth > maxWidth + 100) {
int start = block.textLayout.getLineStart(n);
int end = block.textLayout.getLineEnd(n);
CharSequence text = block.textLayout.getText().subSequence(start, end);
continue;
}
try {
lineLeft = block.textLayout.getLineLeft(n);
} catch (Exception e) {
@ -539,4 +545,22 @@ public class MessageObject {
public boolean isFromMe() {
return messageOwner.from_id == UserConfig.getClientUserId();
}
public boolean isUnread () {
return messageOwner.unread;
}
public long getDialogId() {
if (messageOwner.dialog_id != 0) {
return messageOwner.dialog_id;
} else {
if (messageOwner.to_id.chat_id != 0) {
return -messageOwner.to_id.chat_id;
} else if (isFromMe()) {
return messageOwner.to_id.user_id;
} else {
return messageOwner.from_id;
}
}
}
}

View File

@ -14,10 +14,10 @@ import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.telegram.messenger.LocaleController;
import org.telegram.android.LocaleController;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.MessagesController;
import org.telegram.android.ContactsController;
import org.telegram.android.MessagesController;
import org.telegram.messenger.R;
import org.telegram.ui.Cells.ChatOrUserCell;
import org.telegram.ui.Views.SectionedBaseAdapter;

View File

@ -13,9 +13,9 @@ import android.view.View;
import android.view.ViewGroup;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.ContactsController;
import org.telegram.android.ContactsController;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.MessagesController;
import org.telegram.android.MessagesController;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
import org.telegram.ui.Cells.ChatOrUserCell;

View File

@ -29,14 +29,16 @@ import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import org.telegram.messenger.NotificationsService;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.ContactsController;
import org.telegram.android.NotificationsService;
import org.telegram.messenger.BuildVars;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.NativeLoader;
import org.telegram.messenger.ScreenReceiver;
import org.telegram.android.LocaleController;
import org.telegram.android.MessagesController;
import org.telegram.android.NativeLoader;
import org.telegram.android.ScreenReceiver;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
@ -57,6 +59,7 @@ public class ApplicationLoader extends Application {
private static volatile boolean applicationInited = false;
public static volatile boolean isScreenOn = false;
public static volatile boolean mainInterfacePaused = true;
public static void postInitApplication() {
if (applicationInited) {
@ -65,8 +68,6 @@ public class ApplicationLoader extends Application {
applicationInited = true;
NativeLoader.initNativeLibs(applicationContext);
try {
LocaleController.getInstance();
} catch (Exception e) {
@ -128,12 +129,15 @@ public class ApplicationLoader extends Application {
ApplicationLoader app = (ApplicationLoader)ApplicationLoader.applicationContext;
app.initPlayServices();
FileLog.e("tmessages", "app initied");
ContactsController.getInstance().checkAppAccount();
}
@Override
public void onCreate() {
super.onCreate();
applicationContext = getApplicationContext();
NativeLoader.initNativeLibs(ApplicationLoader.applicationContext);
applicationHandler = new Handler(applicationContext.getMainLooper());
@ -177,7 +181,7 @@ public class ApplicationLoader extends Application {
super.onConfigurationChanged(newConfig);
try {
LocaleController.getInstance().onDeviceConfigurationChange(newConfig);
Utilities.checkDisplaySize();
AndroidUtilities.checkDisplaySize();
} catch (Exception e) {
e.printStackTrace();
}

View File

@ -16,12 +16,12 @@ import android.text.StaticLayout;
import android.text.TextPaint;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import org.telegram.android.AndroidUtilities;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.MediaController;
import org.telegram.android.MediaController;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.MessagesController;
import org.telegram.android.MessagesController;
import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;
import org.telegram.objects.MessageObject;
@ -30,7 +30,6 @@ import org.telegram.ui.Views.ProgressView;
import org.telegram.ui.Views.SeekBar;
import java.io.File;
import java.lang.ref.WeakReference;
public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelegate, MediaController.FileDownloadProgressListener {
@ -90,7 +89,7 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
statesDrawable[7][1] = getResources().getDrawable(R.drawable.audiocancel2_pressed);
timePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
timePaint.setTextSize(Utilities.dp(12));
timePaint.setTextSize(AndroidUtilities.dp(12));
}
}
@ -115,7 +114,7 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
}
invalidate();
} else {
int side = Utilities.dp(36);
int side = AndroidUtilities.dp(36);
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (x >= buttonX && x <= buttonX + side && y >= buttonY && y <= buttonY + side) {
buttonPressed = 1;
@ -220,7 +219,7 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
public void updateButtonState() {
String fileName = currentMessageObject.getFileName();
File cacheFile = new File(Utilities.getCacheDir(), fileName);
File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName);
if (cacheFile.exists()) {
MediaController.getInstance().removeLoadingFileObserver(this);
boolean playing = MediaController.getInstance().isPlayingAudio(currentMessageObject);
@ -286,11 +285,11 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
setMeasuredDimension(width, Utilities.dp(68));
setMeasuredDimension(width, AndroidUtilities.dp(68));
if (isChat) {
backgroundWidth = Math.min(width - Utilities.dp(102), Utilities.dp(300));
backgroundWidth = Math.min(width - AndroidUtilities.dp(102), AndroidUtilities.dp(300));
} else {
backgroundWidth = Math.min(width - Utilities.dp(50), Utilities.dp(300));
backgroundWidth = Math.min(width - AndroidUtilities.dp(50), AndroidUtilities.dp(300));
}
}
@ -299,33 +298,33 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
super.onLayout(changed, left, top, right, bottom);
if (currentMessageObject.isOut()) {
avatarImage.imageX = layoutWidth - backgroundWidth + Utilities.dp(9);
seekBarX = layoutWidth - backgroundWidth + Utilities.dp(97);
buttonX = layoutWidth - backgroundWidth + Utilities.dp(67);
timeX = layoutWidth - backgroundWidth + Utilities.dp(71);
avatarImage.imageX = layoutWidth - backgroundWidth + AndroidUtilities.dp(9);
seekBarX = layoutWidth - backgroundWidth + AndroidUtilities.dp(97);
buttonX = layoutWidth - backgroundWidth + AndroidUtilities.dp(67);
timeX = layoutWidth - backgroundWidth + AndroidUtilities.dp(71);
} else {
if (isChat) {
avatarImage.imageX = Utilities.dp(69);
seekBarX = Utilities.dp(158);
buttonX = Utilities.dp(128);
timeX = Utilities.dp(132);
avatarImage.imageX = AndroidUtilities.dp(69);
seekBarX = AndroidUtilities.dp(158);
buttonX = AndroidUtilities.dp(128);
timeX = AndroidUtilities.dp(132);
} else {
avatarImage.imageX = Utilities.dp(16);
seekBarX = Utilities.dp(106);
buttonX = Utilities.dp(76);
timeX = Utilities.dp(80);
avatarImage.imageX = AndroidUtilities.dp(16);
seekBarX = AndroidUtilities.dp(106);
buttonX = AndroidUtilities.dp(76);
timeX = AndroidUtilities.dp(80);
}
}
avatarImage.imageY = Utilities.dp(9);
avatarImage.imageW = Utilities.dp(50);
avatarImage.imageH = Utilities.dp(50);
avatarImage.imageY = AndroidUtilities.dp(9);
avatarImage.imageW = AndroidUtilities.dp(50);
avatarImage.imageH = AndroidUtilities.dp(50);
seekBar.width = backgroundWidth - Utilities.dp(112);
seekBar.height = Utilities.dp(30);
progressView.width = backgroundWidth - Utilities.dp(136);
progressView.height = Utilities.dp(30);
seekBarY = Utilities.dp(13);
buttonY = Utilities.dp(10);
seekBar.width = backgroundWidth - AndroidUtilities.dp(112);
seekBar.height = AndroidUtilities.dp(30);
progressView.width = backgroundWidth - AndroidUtilities.dp(136);
progressView.height = AndroidUtilities.dp(30);
seekBarY = AndroidUtilities.dp(13);
buttonY = AndroidUtilities.dp(10);
updateProgress();
}
@ -380,14 +379,14 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
return;
}
avatarImage.draw(canvas, avatarImage.imageX, avatarImage.imageY, Utilities.dp(50), Utilities.dp(50));
avatarImage.draw(canvas, avatarImage.imageX, avatarImage.imageY, AndroidUtilities.dp(50), AndroidUtilities.dp(50));
canvas.save();
if (buttonState == 0 || buttonState == 1) {
canvas.translate(seekBarX, seekBarY);
seekBar.draw(canvas);
} else {
canvas.translate(seekBarX + Utilities.dp(12), seekBarY);
canvas.translate(seekBarX + AndroidUtilities.dp(12), seekBarY);
progressView.draw(canvas);
}
canvas.restore();
@ -400,14 +399,14 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
timePaint.setColor(0xff70b15c);
}
Drawable buttonDrawable = statesDrawable[state][buttonPressed];
int side = Utilities.dp(36);
int side = AndroidUtilities.dp(36);
int x = (side - buttonDrawable.getIntrinsicWidth()) / 2;
int y = (side - buttonDrawable.getIntrinsicHeight()) / 2;
setDrawableBounds(buttonDrawable, x + buttonX, y + buttonY);
buttonDrawable.draw(canvas);
canvas.save();
canvas.translate(timeX, Utilities.dp(45));
canvas.translate(timeX, AndroidUtilities.dp(45));
timeLayout.draw(canvas);
canvas.restore();
}

View File

@ -22,9 +22,10 @@ import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.ViewConfiguration;
import org.telegram.messenger.LocaleController;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.LocaleController;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.MessagesController;
import org.telegram.android.MessagesController;
import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;
import org.telegram.objects.MessageObject;
@ -114,6 +115,8 @@ public class ChatBaseCell extends BaseCell {
private CheckForLongPress pendingCheckForLongPress = null;
private CheckForTap pendingCheckForTap = null;
private int last_send_state = 0;
private final class CheckForTap implements Runnable {
public void run() {
if (pendingCheckForLongPress == null) {
@ -176,22 +179,22 @@ public class ChatBaseCell extends BaseCell {
mediaBackgroundDrawable = getResources().getDrawable(R.drawable.phototime);
timePaintIn = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
timePaintIn.setTextSize(Utilities.dp(12));
timePaintIn.setTextSize(AndroidUtilities.dp(12));
timePaintIn.setColor(0xffa1aab3);
timePaintOut = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
timePaintOut.setTextSize(Utilities.dp(12));
timePaintOut.setTextSize(AndroidUtilities.dp(12));
timePaintOut.setColor(0xff70b15c);
timeMediaPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
timeMediaPaint.setTextSize(Utilities.dp(12));
timeMediaPaint.setTextSize(AndroidUtilities.dp(12));
timeMediaPaint.setColor(0xffffffff);
namePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
namePaint.setTextSize(Utilities.dp(15));
namePaint.setTextSize(AndroidUtilities.dp(15));
forwardNamePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
forwardNamePaint.setTextSize(Utilities.dp(14));
forwardNamePaint.setTextSize(AndroidUtilities.dp(14));
}
}
@ -211,6 +214,10 @@ public class ChatBaseCell extends BaseCell {
if (currentMessageObject == null || currentUser == null) {
return false;
}
if (last_send_state != currentMessageObject.messageOwner.send_state) {
return true;
}
TLRPC.User newUser = MessagesController.getInstance().users.get(currentMessageObject.messageOwner.from_id);
TLRPC.FileLocation newPhoto = null;
@ -241,6 +248,7 @@ public class ChatBaseCell extends BaseCell {
public void setMessageObject(MessageObject messageObject) {
currentMessageObject = messageObject;
last_send_state = messageObject.messageOwner.send_state;
isPressed = false;
isCheckPressed = true;
isAvatarVisible = false;
@ -286,11 +294,11 @@ public class ChatBaseCell extends BaseCell {
currentNameString = Utilities.formatName(currentUser.first_name, currentUser.last_name);
nameWidth = getMaxNameWidth();
CharSequence nameStringFinal = TextUtils.ellipsize(currentNameString.replace("\n", " "), namePaint, nameWidth - Utilities.dp(12), TextUtils.TruncateAt.END);
CharSequence nameStringFinal = TextUtils.ellipsize(currentNameString.replace("\n", " "), namePaint, nameWidth - AndroidUtilities.dp(12), TextUtils.TruncateAt.END);
nameLayout = new StaticLayout(nameStringFinal, namePaint, nameWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
if (nameLayout.getLineCount() > 0) {
nameWidth = (int)Math.ceil(nameLayout.getLineWidth(0));
namesOffset += Utilities.dp(18);
namesOffset += AndroidUtilities.dp(18);
nameOffsetX = nameLayout.getLineLeft(0);
} else {
nameWidth = 0;
@ -308,12 +316,12 @@ public class ChatBaseCell extends BaseCell {
forwardedNameWidth = getMaxNameWidth();
CharSequence str = TextUtils.ellipsize(currentForwardNameString.replace("\n", " "), forwardNamePaint, forwardedNameWidth - Utilities.dp(40), TextUtils.TruncateAt.END);
CharSequence str = TextUtils.ellipsize(currentForwardNameString.replace("\n", " "), forwardNamePaint, forwardedNameWidth - AndroidUtilities.dp(40), TextUtils.TruncateAt.END);
str = Html.fromHtml(String.format("%s<br>%s <b>%s</b>", LocaleController.getString("ForwardedMessage", R.string.ForwardedMessage), LocaleController.getString("From", R.string.From), str));
forwardedNameLayout = new StaticLayout(str, forwardNamePaint, forwardedNameWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
if (forwardedNameLayout.getLineCount() > 1) {
forwardedNameWidth = Math.max((int) Math.ceil(forwardedNameLayout.getLineWidth(0)), (int) Math.ceil(forwardedNameLayout.getLineWidth(1)));
namesOffset += Utilities.dp(36);
namesOffset += AndroidUtilities.dp(36);
forwardNameOffsetX = Math.min(forwardedNameLayout.getLineLeft(0), forwardedNameLayout.getLineLeft(1));
} else {
forwardedNameWidth = 0;
@ -337,7 +345,7 @@ public class ChatBaseCell extends BaseCell {
}
protected int getMaxNameWidth() {
return backgroundWidth - Utilities.dp(8);
return backgroundWidth - AndroidUtilities.dp(8);
}
protected void startCheckLongPress() {
@ -372,7 +380,7 @@ public class ChatBaseCell extends BaseCell {
avatarPressed = true;
result = true;
} else if (drawForwardedName && forwardedNameLayout != null) {
if (x >= forwardNameX && x <= forwardNameX + forwardedNameWidth && y >= forwardNameY && y <= forwardNameY + Utilities.dp(32)) {
if (x >= forwardNameX && x <= forwardNameX + forwardedNameWidth && y >= forwardNameY && y <= forwardNameY + AndroidUtilities.dp(32)) {
forwardNamePressed = true;
result = true;
}
@ -409,7 +417,7 @@ public class ChatBaseCell extends BaseCell {
} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
forwardNamePressed = false;
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (!(x >= forwardNameX && x <= forwardNameX + forwardedNameWidth && y >= forwardNameY && y <= forwardNameY + Utilities.dp(32))) {
if (!(x >= forwardNameX && x <= forwardNameX + forwardedNameWidth && y >= forwardNameY && y <= forwardNameY + AndroidUtilities.dp(32))) {
forwardNamePressed = false;
}
}
@ -433,23 +441,23 @@ public class ChatBaseCell extends BaseCell {
timeLayout = new StaticLayout(currentTimeString, currentTimePaint, timeWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
if (!media) {
if (!currentMessageObject.isOut()) {
timeX = backgroundWidth - Utilities.dp(9) - timeWidth + (isChat ? Utilities.dp(52) : 0);
timeX = backgroundWidth - AndroidUtilities.dp(9) - timeWidth + (isChat ? AndroidUtilities.dp(52) : 0);
} else {
timeX = layoutWidth - timeWidth - Utilities.dpf(38.5f);
timeX = layoutWidth - timeWidth - AndroidUtilities.dpf(38.5f);
}
} else {
if (!currentMessageObject.isOut()) {
timeX = backgroundWidth - Utilities.dp(4) - timeWidth + (isChat ? Utilities.dp(52) : 0);
timeX = backgroundWidth - AndroidUtilities.dp(4) - timeWidth + (isChat ? AndroidUtilities.dp(52) : 0);
} else {
timeX = layoutWidth - timeWidth - Utilities.dpf(42.0f);
timeX = layoutWidth - timeWidth - AndroidUtilities.dpf(42.0f);
}
}
if (isAvatarVisible) {
avatarImage.imageX = Utilities.dp(6);
avatarImage.imageY = layoutHeight - Utilities.dp(45);
avatarImage.imageW = Utilities.dp(42);
avatarImage.imageH = Utilities.dp(42);
avatarImage.imageX = AndroidUtilities.dp(6);
avatarImage.imageY = layoutHeight - AndroidUtilities.dp(45);
avatarImage.imageW = AndroidUtilities.dp(42);
avatarImage.imageH = AndroidUtilities.dp(42);
}
wasLayout = true;
@ -473,7 +481,7 @@ public class ChatBaseCell extends BaseCell {
}
if (isAvatarVisible) {
avatarImage.draw(canvas, Utilities.dp(6), layoutHeight - Utilities.dp(45), Utilities.dp(42), Utilities.dp(42));
avatarImage.draw(canvas, AndroidUtilities.dp(6), layoutHeight - AndroidUtilities.dp(45), AndroidUtilities.dp(42), AndroidUtilities.dp(42));
}
Drawable currentBackgroundDrawable = null;
@ -491,7 +499,7 @@ public class ChatBaseCell extends BaseCell {
currentBackgroundDrawable = backgroundMediaDrawableOut;
}
}
setDrawableBounds(currentBackgroundDrawable, layoutWidth - backgroundWidth - (!media ? 0 : Utilities.dp(9)), Utilities.dp(1), backgroundWidth, layoutHeight - Utilities.dp(2));
setDrawableBounds(currentBackgroundDrawable, layoutWidth - backgroundWidth - (!media ? 0 : AndroidUtilities.dp(9)), AndroidUtilities.dp(1), backgroundWidth, layoutHeight - AndroidUtilities.dp(2));
} else {
if (isPressed() && isCheckPressed || !isCheckPressed && isPressed) {
if (!media) {
@ -507,9 +515,9 @@ public class ChatBaseCell extends BaseCell {
}
}
if (isChat) {
setDrawableBounds(currentBackgroundDrawable, Utilities.dp(52 + (!media ? 0 : 9)), Utilities.dp(1), backgroundWidth, layoutHeight - Utilities.dp(2));
setDrawableBounds(currentBackgroundDrawable, AndroidUtilities.dp(52 + (!media ? 0 : 9)), AndroidUtilities.dp(1), backgroundWidth, layoutHeight - AndroidUtilities.dp(2));
} else {
setDrawableBounds(currentBackgroundDrawable, (!media ? 0 : Utilities.dp(9)), Utilities.dp(1), backgroundWidth, layoutHeight - Utilities.dp(2));
setDrawableBounds(currentBackgroundDrawable, (!media ? 0 : AndroidUtilities.dp(9)), AndroidUtilities.dp(1), backgroundWidth, layoutHeight - AndroidUtilities.dp(2));
}
}
currentBackgroundDrawable.draw(canvas);
@ -518,7 +526,7 @@ public class ChatBaseCell extends BaseCell {
if (drawName && nameLayout != null) {
canvas.save();
canvas.translate(currentBackgroundDrawable.getBounds().left + Utilities.dp(19) - nameOffsetX, Utilities.dp(10));
canvas.translate(currentBackgroundDrawable.getBounds().left + AndroidUtilities.dp(19) - nameOffsetX, AndroidUtilities.dp(10));
namePaint.setColor(Utilities.getColorForId(currentUser.id));
nameLayout.draw(canvas);
canvas.restore();
@ -528,12 +536,12 @@ public class ChatBaseCell extends BaseCell {
canvas.save();
if (currentMessageObject.isOut()) {
forwardNamePaint.setColor(0xff4a923c);
forwardNameX = currentBackgroundDrawable.getBounds().left + Utilities.dp(10);
forwardNameY = Utilities.dp(10 + (drawName ? 18 : 0));
forwardNameX = currentBackgroundDrawable.getBounds().left + AndroidUtilities.dp(10);
forwardNameY = AndroidUtilities.dp(10 + (drawName ? 18 : 0));
} else {
forwardNamePaint.setColor(0xff006fc8);
forwardNameX = currentBackgroundDrawable.getBounds().left + Utilities.dp(19);
forwardNameY = Utilities.dp(10 + (drawName ? 18 : 0));
forwardNameX = currentBackgroundDrawable.getBounds().left + AndroidUtilities.dp(19);
forwardNameY = AndroidUtilities.dp(10 + (drawName ? 18 : 0));
}
canvas.translate(forwardNameX - forwardNameOffsetX, forwardNameY);
forwardedNameLayout.draw(canvas);
@ -542,16 +550,16 @@ public class ChatBaseCell extends BaseCell {
if (drawTime) {
if (media) {
setDrawableBounds(mediaBackgroundDrawable, timeX - Utilities.dp(3), layoutHeight - Utilities.dpf(27.5f), timeWidth + Utilities.dp(6 + (currentMessageObject.isOut() ? 20 : 0)), Utilities.dpf(16.5f));
setDrawableBounds(mediaBackgroundDrawable, timeX - AndroidUtilities.dp(3), layoutHeight - AndroidUtilities.dpf(27.5f), timeWidth + AndroidUtilities.dp(6 + (currentMessageObject.isOut() ? 20 : 0)), AndroidUtilities.dpf(16.5f));
mediaBackgroundDrawable.draw(canvas);
canvas.save();
canvas.translate(timeX, layoutHeight - Utilities.dpf(12.0f) - timeLayout.getHeight());
canvas.translate(timeX, layoutHeight - AndroidUtilities.dpf(12.0f) - timeLayout.getHeight());
timeLayout.draw(canvas);
canvas.restore();
} else {
canvas.save();
canvas.translate(timeX, layoutHeight - Utilities.dpf(6.5f) - timeLayout.getHeight());
canvas.translate(timeX, layoutHeight - AndroidUtilities.dpf(6.5f) - timeLayout.getHeight());
timeLayout.draw(canvas);
canvas.restore();
}
@ -586,45 +594,45 @@ public class ChatBaseCell extends BaseCell {
if (drawClock) {
if (!media) {
setDrawableBounds(clockDrawable, layoutWidth - Utilities.dpf(18.5f) - clockDrawable.getIntrinsicWidth(), layoutHeight - Utilities.dpf(8.5f) - clockDrawable.getIntrinsicHeight());
setDrawableBounds(clockDrawable, layoutWidth - AndroidUtilities.dpf(18.5f) - clockDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dpf(8.5f) - clockDrawable.getIntrinsicHeight());
clockDrawable.draw(canvas);
} else {
setDrawableBounds(clockMediaDrawable, layoutWidth - Utilities.dpf(22.0f) - clockMediaDrawable.getIntrinsicWidth(), layoutHeight - Utilities.dpf(13.0f) - clockMediaDrawable.getIntrinsicHeight());
setDrawableBounds(clockMediaDrawable, layoutWidth - AndroidUtilities.dpf(22.0f) - clockMediaDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dpf(13.0f) - clockMediaDrawable.getIntrinsicHeight());
clockMediaDrawable.draw(canvas);
}
}
if (drawCheck2) {
if (!media) {
if (drawCheck1) {
setDrawableBounds(checkDrawable, layoutWidth - Utilities.dpf(22.5f) - checkDrawable.getIntrinsicWidth(), layoutHeight - Utilities.dpf(8.5f) - checkDrawable.getIntrinsicHeight());
setDrawableBounds(checkDrawable, layoutWidth - AndroidUtilities.dpf(22.5f) - checkDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dpf(8.5f) - checkDrawable.getIntrinsicHeight());
} else {
setDrawableBounds(checkDrawable, layoutWidth - Utilities.dpf(18.5f) - checkDrawable.getIntrinsicWidth(), layoutHeight - Utilities.dpf(8.5f) - checkDrawable.getIntrinsicHeight());
setDrawableBounds(checkDrawable, layoutWidth - AndroidUtilities.dpf(18.5f) - checkDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dpf(8.5f) - checkDrawable.getIntrinsicHeight());
}
checkDrawable.draw(canvas);
} else {
if (drawCheck1) {
setDrawableBounds(checkMediaDrawable, layoutWidth - Utilities.dpf(26.0f) - checkMediaDrawable.getIntrinsicWidth(), layoutHeight - Utilities.dpf(13.0f) - checkMediaDrawable.getIntrinsicHeight());
setDrawableBounds(checkMediaDrawable, layoutWidth - AndroidUtilities.dpf(26.0f) - checkMediaDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dpf(13.0f) - checkMediaDrawable.getIntrinsicHeight());
} else {
setDrawableBounds(checkMediaDrawable, layoutWidth - Utilities.dpf(22.0f) - checkMediaDrawable.getIntrinsicWidth(), layoutHeight - Utilities.dpf(13.0f) - checkMediaDrawable.getIntrinsicHeight());
setDrawableBounds(checkMediaDrawable, layoutWidth - AndroidUtilities.dpf(22.0f) - checkMediaDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dpf(13.0f) - checkMediaDrawable.getIntrinsicHeight());
}
checkMediaDrawable.draw(canvas);
}
}
if (drawCheck1) {
if (!media) {
setDrawableBounds(halfCheckDrawable, layoutWidth - Utilities.dp(18) - halfCheckDrawable.getIntrinsicWidth(), layoutHeight - Utilities.dpf(8.5f) - halfCheckDrawable.getIntrinsicHeight());
setDrawableBounds(halfCheckDrawable, layoutWidth - AndroidUtilities.dp(18) - halfCheckDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dpf(8.5f) - halfCheckDrawable.getIntrinsicHeight());
halfCheckDrawable.draw(canvas);
} else {
setDrawableBounds(halfCheckMediaDrawable, layoutWidth - Utilities.dpf(20.5f) - halfCheckMediaDrawable.getIntrinsicWidth(), layoutHeight - Utilities.dpf(13.0f) - halfCheckMediaDrawable.getIntrinsicHeight());
setDrawableBounds(halfCheckMediaDrawable, layoutWidth - AndroidUtilities.dpf(20.5f) - halfCheckMediaDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dpf(13.0f) - halfCheckMediaDrawable.getIntrinsicHeight());
halfCheckMediaDrawable.draw(canvas);
}
}
if (drawError) {
if (!media) {
setDrawableBounds(errorDrawable, layoutWidth - Utilities.dp(18) - errorDrawable.getIntrinsicWidth(), layoutHeight - Utilities.dpf(6.5f) - errorDrawable.getIntrinsicHeight());
setDrawableBounds(errorDrawable, layoutWidth - AndroidUtilities.dp(18) - errorDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dpf(6.5f) - errorDrawable.getIntrinsicHeight());
errorDrawable.draw(canvas);
} else {
setDrawableBounds(errorDrawable, layoutWidth - Utilities.dpf(20.5f) - errorDrawable.getIntrinsicWidth(), layoutHeight - Utilities.dpf(12.5f) - errorDrawable.getIntrinsicHeight());
setDrawableBounds(errorDrawable, layoutWidth - AndroidUtilities.dpf(20.5f) - errorDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dpf(12.5f) - errorDrawable.getIntrinsicHeight());
errorDrawable.draw(canvas);
}
}

View File

@ -18,12 +18,12 @@ import android.text.StaticLayout;
import android.text.TextPaint;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import org.telegram.android.AndroidUtilities;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.MediaController;
import org.telegram.messenger.MessagesController;
import org.telegram.android.MediaController;
import org.telegram.android.MessagesController;
import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;
import org.telegram.objects.MessageObject;
@ -34,7 +34,6 @@ import org.telegram.ui.Views.ImageReceiver;
import org.telegram.ui.Views.ProgressView;
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.Locale;
public class ChatMediaCell extends ChatBaseCell implements MediaController.FileDownloadProgressListener {
@ -96,7 +95,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
infoPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
infoPaint.setColor(0xffffffff);
infoPaint.setTextSize(Utilities.dp(12));
infoPaint.setTextSize(AndroidUtilities.dp(12));
}
TAG = MediaController.getInstance().generateObserverTag();
@ -136,7 +135,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
float y = event.getY();
boolean result = false;
int side = Utilities.dp(44);
int side = AndroidUtilities.dp(44);
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (delegate == null || delegate.canPerformActions()) {
if (buttonState != -1 && x >= buttonX && x <= buttonX + side && y >= buttonY && y <= buttonY + side) {
@ -285,7 +284,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
}
double lat = object.messageOwner.media.geo.lat;
double lon = object.messageOwner.media.geo._long;
String url = String.format(Locale.US, "https://maps.googleapis.com/maps/api/staticmap?center=%f,%f&zoom=13&size=100x100&maptype=roadmap&scale=%d&markers=color:red|size:big|%f,%f&sensor=false", lat, lon, Math.min(2, (int)Math.ceil(Utilities.density)), lat, lon);
String url = String.format(Locale.US, "https://maps.googleapis.com/maps/api/staticmap?center=%f,%f&zoom=13&size=100x100&maptype=roadmap&scale=%d&markers=color:red|size:big|%f,%f&sensor=false", lat, lon, Math.min(2, (int)Math.ceil(AndroidUtilities.density)), lat, lon);
if (!url.equals(currentUrl)) {
return true;
}
@ -293,7 +292,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
return true;
} else if (currentPhotoObject != null && photoNotSet) {
String fileName = MessageObject.getAttachFileName(currentPhotoObject.photoOwner);
File cacheFile = new File(Utilities.getCacheDir(), fileName);
File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName);
if (cacheFile.exists()) {
return true;
}
@ -330,7 +329,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
String str = String.format("%d:%02d, %s", minutes, seconds, Utilities.formatFileSize(messageObject.messageOwner.media.video.size));
if (currentInfoString == null || !currentInfoString.equals(str)) {
currentInfoString = str;
infoOffset = videoIconDrawable.getIntrinsicWidth() + Utilities.dp(4);
infoOffset = videoIconDrawable.getIntrinsicWidth() + AndroidUtilities.dp(4);
infoWidth = (int) Math.ceil(infoPaint.measureText(currentInfoString));
infoLayout = new StaticLayout(currentInfoString, infoPaint, infoWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
}
@ -340,17 +339,17 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
}
if (messageObject.type == 4) {
photoWidth = Utilities.dp(100);
photoHeight = Utilities.dp(100);
backgroundWidth = photoWidth + Utilities.dp(12);
photoWidth = AndroidUtilities.dp(100);
photoHeight = AndroidUtilities.dp(100);
backgroundWidth = photoWidth + AndroidUtilities.dp(12);
double lat = messageObject.messageOwner.media.geo.lat;
double lon = messageObject.messageOwner.media.geo._long;
currentUrl = String.format(Locale.US, "https://maps.googleapis.com/maps/api/staticmap?center=%f,%f&zoom=13&size=100x100&maptype=roadmap&scale=%d&markers=color:red|size:big|%f,%f&sensor=false", lat, lon, Math.min(2, (int)Math.ceil(Utilities.density)), lat, lon);
currentUrl = String.format(Locale.US, "https://maps.googleapis.com/maps/api/staticmap?center=%f,%f&zoom=13&size=100x100&maptype=roadmap&scale=%d&markers=color:red|size:big|%f,%f&sensor=false", lat, lon, Math.min(2, (int)Math.ceil(AndroidUtilities.density)), lat, lon);
photoImage.setImage(currentUrl, null, messageObject.isOut() ? placeholderOutDrawable : placeholderInDrawable);
} else {
photoWidth = (int) (Math.min(Utilities.displaySize.x, Utilities.displaySize.y) * 0.7f);
photoHeight = photoWidth + Utilities.dp(100);
photoWidth = (int) (Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) * 0.7f);
photoHeight = photoWidth + AndroidUtilities.dp(100);
if (photoWidth > 800) {
photoWidth = 800;
@ -367,35 +366,35 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
int h = (int) (currentPhotoObject.photoOwner.h / scale);
if (w == 0) {
if (messageObject.type == 3) {
w = infoWidth + infoOffset + Utilities.dp(16);
w = infoWidth + infoOffset + AndroidUtilities.dp(16);
} else {
w = Utilities.dp(100);
w = AndroidUtilities.dp(100);
}
}
if (h == 0) {
h = Utilities.dp(100);
h = AndroidUtilities.dp(100);
}
if (h > photoHeight) {
float scale2 = h;
h = photoHeight;
scale2 /= h;
w = (int) (w / scale2);
} else if (h < Utilities.dp(120)) {
h = Utilities.dp(120);
} else if (h < AndroidUtilities.dp(120)) {
h = AndroidUtilities.dp(120);
float hScale = (float) currentPhotoObject.photoOwner.h / h;
if (currentPhotoObject.photoOwner.w / hScale < photoWidth) {
w = (int) (currentPhotoObject.photoOwner.w / hScale);
}
}
int timeWidthTotal = timeWidth + Utilities.dp(14 + (currentMessageObject.isOut() ? 20 : 0));
int timeWidthTotal = timeWidth + AndroidUtilities.dp(14 + (currentMessageObject.isOut() ? 20 : 0));
if (w < timeWidthTotal) {
w = timeWidthTotal;
}
photoWidth = w;
photoHeight = h;
backgroundWidth = w + Utilities.dp(12);
currentPhotoFilter = String.format(Locale.US, "%d_%d", (int) (w / Utilities.density), (int) (h / Utilities.density));
backgroundWidth = w + AndroidUtilities.dp(12);
currentPhotoFilter = String.format(Locale.US, "%d_%d", (int) (w / AndroidUtilities.density), (int) (h / AndroidUtilities.density));
if (currentPhotoObject.image != null) {
photoImage.setImageBitmap(currentPhotoObject.image);
@ -403,7 +402,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
boolean photoExist = true;
String fileName = MessageObject.getAttachFileName(currentPhotoObject.photoOwner);
if (messageObject.type == 1) {
File cacheFile = new File(Utilities.getCacheDir(), fileName);
File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName);
if (!cacheFile.exists()) {
photoExist = false;
} else {
@ -447,7 +446,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
return;
}
fileName = MessageObject.getAttachFileName(currentPhotoObject.photoOwner);
cacheFile = new File(Utilities.getCacheDir(), fileName);
cacheFile = new File(AndroidUtilities.getCacheDir(), fileName);
} else if (currentMessageObject.type == 8 || currentMessageObject.type == 3) {
if (currentMessageObject.messageOwner.attachPath != null && currentMessageObject.messageOwner.attachPath.length() != 0) {
File f = new File(currentMessageObject.messageOwner.attachPath);
@ -458,7 +457,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
}
if (fileName == null) {
fileName = currentMessageObject.getFileName();
cacheFile = new File(Utilities.getCacheDir(), fileName);
cacheFile = new File(AndroidUtilities.getCacheDir(), fileName);
}
}
if (fileName == null) {
@ -525,7 +524,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), photoHeight + Utilities.dp(14));
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), photoHeight + AndroidUtilities.dp(14));
}
@Override
@ -533,23 +532,23 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
super.onLayout(changed, left, top, right, bottom);
if (currentMessageObject.isOut()) {
photoImage.imageX = layoutWidth - backgroundWidth - Utilities.dp(3);
photoImage.imageX = layoutWidth - backgroundWidth - AndroidUtilities.dp(3);
} else {
if (isChat) {
photoImage.imageX = Utilities.dp(67);
photoImage.imageX = AndroidUtilities.dp(67);
} else {
photoImage.imageX = Utilities.dp(15);
photoImage.imageX = AndroidUtilities.dp(15);
}
}
photoImage.imageY = Utilities.dp(7);
photoImage.imageY = AndroidUtilities.dp(7);
photoImage.imageW = photoWidth;
photoImage.imageH = photoHeight;
progressView.width = timeX - photoImage.imageX - Utilities.dpf(23.0f);
progressView.height = Utilities.dp(3);
progressView.progressHeight = Utilities.dp(3);
progressView.width = timeX - photoImage.imageX - AndroidUtilities.dpf(23.0f);
progressView.height = AndroidUtilities.dp(3);
progressView.progressHeight = AndroidUtilities.dp(3);
int size = Utilities.dp(44);
int size = AndroidUtilities.dp(44);
buttonX = (int)(photoImage.imageX + (photoWidth - size) / 2.0f);
buttonY = (int)(photoImage.imageY + (photoHeight - size) / 2.0f);
}
@ -568,11 +567,11 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
}
if (progressVisible) {
setDrawableBounds(mediaBackgroundDrawable, photoImage.imageX + Utilities.dp(4), layoutHeight - Utilities.dpf(27.5f), progressView.width + Utilities.dp(12), Utilities.dpf(16.5f));
setDrawableBounds(mediaBackgroundDrawable, photoImage.imageX + AndroidUtilities.dp(4), layoutHeight - AndroidUtilities.dpf(27.5f), progressView.width + AndroidUtilities.dp(12), AndroidUtilities.dpf(16.5f));
mediaBackgroundDrawable.draw(canvas);
canvas.save();
canvas.translate(photoImage.imageX + Utilities.dp(10), layoutHeight - Utilities.dpf(21.0f));
canvas.translate(photoImage.imageX + AndroidUtilities.dp(10), layoutHeight - AndroidUtilities.dpf(21.0f));
progressView.draw(canvas);
canvas.restore();
}
@ -584,16 +583,16 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
}
if (infoLayout != null && (buttonState == 1 || buttonState == 0 || buttonState == 3)) {
setDrawableBounds(mediaBackgroundDrawable, photoImage.imageX + Utilities.dp(4), photoImage.imageY + Utilities.dp(4), infoWidth + Utilities.dp(8) + infoOffset, Utilities.dpf(16.5f));
setDrawableBounds(mediaBackgroundDrawable, photoImage.imageX + AndroidUtilities.dp(4), photoImage.imageY + AndroidUtilities.dp(4), infoWidth + AndroidUtilities.dp(8) + infoOffset, AndroidUtilities.dpf(16.5f));
mediaBackgroundDrawable.draw(canvas);
if (currentMessageObject.type == 3) {
setDrawableBounds(videoIconDrawable, photoImage.imageX + Utilities.dp(8), photoImage.imageY + Utilities.dpf(7.5f));
setDrawableBounds(videoIconDrawable, photoImage.imageX + AndroidUtilities.dp(8), photoImage.imageY + AndroidUtilities.dpf(7.5f));
videoIconDrawable.draw(canvas);
}
canvas.save();
canvas.translate(photoImage.imageX + Utilities.dp(8) + infoOffset, photoImage.imageY + Utilities.dpf(5.5f));
canvas.translate(photoImage.imageX + AndroidUtilities.dp(8) + infoOffset, photoImage.imageY + AndroidUtilities.dpf(5.5f));
infoLayout.draw(canvas);
canvas.restore();
}

View File

@ -14,8 +14,8 @@ import android.text.Spannable;
import android.text.style.ClickableSpan;
import android.view.MotionEvent;
import org.telegram.android.AndroidUtilities;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.Utilities;
import org.telegram.objects.MessageObject;
public class ChatMessageCell extends ChatBaseCell {
@ -132,10 +132,10 @@ public class ChatMessageCell extends ChatBaseCell {
pressedLink = null;
int maxWidth;
if (isChat && !messageObject.isOut()) {
maxWidth = Utilities.displaySize.x - Utilities.dp(122);
maxWidth = AndroidUtilities.displaySize.x - AndroidUtilities.dp(122);
drawName = true;
} else {
maxWidth = Utilities.displaySize.x - Utilities.dp(80);
maxWidth = AndroidUtilities.displaySize.x - AndroidUtilities.dp(80);
drawName = false;
}
@ -144,25 +144,25 @@ public class ChatMessageCell extends ChatBaseCell {
super.setMessageObject(messageObject);
backgroundWidth = messageObject.textWidth;
totalHeight = messageObject.textHeight + Utilities.dpf(19.5f) + namesOffset;
totalHeight = messageObject.textHeight + AndroidUtilities.dpf(19.5f) + namesOffset;
int maxChildWidth = Math.max(backgroundWidth, nameWidth);
maxChildWidth = Math.max(maxChildWidth, forwardedNameWidth);
int timeMore = timeWidth + Utilities.dp(6);
int timeMore = timeWidth + AndroidUtilities.dp(6);
if (messageObject.isOut()) {
timeMore += Utilities.dpf(20.5f);
timeMore += AndroidUtilities.dpf(20.5f);
}
if (maxWidth - messageObject.lastLineWidth < timeMore) {
totalHeight += Utilities.dp(14);
backgroundWidth = Math.max(maxChildWidth, messageObject.lastLineWidth) + Utilities.dp(29);
totalHeight += AndroidUtilities.dp(14);
backgroundWidth = Math.max(maxChildWidth, messageObject.lastLineWidth) + AndroidUtilities.dp(29);
} else {
int diff = maxChildWidth - messageObject.lastLineWidth;
if (diff >= 0 && diff <= timeMore) {
backgroundWidth = maxChildWidth + timeMore - diff + Utilities.dp(29);
backgroundWidth = maxChildWidth + timeMore - diff + AndroidUtilities.dp(29);
} else {
backgroundWidth = Math.max(maxChildWidth, messageObject.lastLineWidth + timeMore) + Utilities.dp(29);
backgroundWidth = Math.max(maxChildWidth, messageObject.lastLineWidth + timeMore) + AndroidUtilities.dp(29);
}
}
}
@ -178,11 +178,11 @@ public class ChatMessageCell extends ChatBaseCell {
super.onLayout(changed, left, top, right, bottom);
if (currentMessageObject.isOut()) {
textX = layoutWidth - backgroundWidth + Utilities.dp(10);
textY = Utilities.dp(10) + namesOffset;
textX = layoutWidth - backgroundWidth + AndroidUtilities.dp(10);
textY = AndroidUtilities.dp(10) + namesOffset;
} else {
textX = Utilities.dp(19) + (isChat ? Utilities.dp(52) : 0);
textY = Utilities.dp(10) + namesOffset;
textX = AndroidUtilities.dp(19) + (isChat ? AndroidUtilities.dp(52) : 0);
textY = AndroidUtilities.dp(10) + namesOffset;
}
}
@ -194,11 +194,11 @@ public class ChatMessageCell extends ChatBaseCell {
}
if (currentMessageObject.isOut()) {
textX = layoutWidth - backgroundWidth + Utilities.dp(10);
textY = Utilities.dp(10) + namesOffset;
textX = layoutWidth - backgroundWidth + AndroidUtilities.dp(10);
textY = AndroidUtilities.dp(10) + namesOffset;
} else {
textX = Utilities.dp(19) + (isChat ? Utilities.dp(52) : 0);
textY = Utilities.dp(10) + namesOffset;
textX = AndroidUtilities.dp(19) + (isChat ? AndroidUtilities.dp(52) : 0);
textY = AndroidUtilities.dp(10) + namesOffset;
}
for (int a = firstVisibleBlockNum; a <= lastVisibleBlockNum; a++) {

View File

@ -17,11 +17,12 @@ import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import org.telegram.android.AndroidUtilities;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.LocaleController;
import org.telegram.android.LocaleController;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.MessagesController;
import org.telegram.android.MessagesController;
import org.telegram.messenger.R;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
@ -61,25 +62,25 @@ public class ChatOrUserCell extends BaseCell {
private void init() {
if (namePaint == null) {
namePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
namePaint.setTextSize(Utilities.dp(18));
namePaint.setTextSize(AndroidUtilities.dp(18));
namePaint.setColor(0xff222222);
}
if (nameEncryptedPaint == null) {
nameEncryptedPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
nameEncryptedPaint.setTextSize(Utilities.dp(18));
nameEncryptedPaint.setTextSize(AndroidUtilities.dp(18));
nameEncryptedPaint.setColor(0xff00a60e);
}
if (onlinePaint == null) {
onlinePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
onlinePaint.setTextSize(Utilities.dp(15));
onlinePaint.setTextSize(AndroidUtilities.dp(15));
onlinePaint.setColor(0xff316f9f);
}
if (offlinePaint == null) {
offlinePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
offlinePaint.setTextSize(Utilities.dp(15));
offlinePaint.setTextSize(AndroidUtilities.dp(15));
offlinePaint.setColor(0xff999999);
}
@ -122,7 +123,7 @@ public class ChatOrUserCell extends BaseCell {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), Utilities.dp(64));
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), AndroidUtilities.dp(64));
}
@Override
@ -243,14 +244,14 @@ public class ChatOrUserCell extends BaseCell {
canvas.restore();
}
avatarImage.draw(canvas, cellLayout.avatarLeft, cellLayout.avatarTop, Utilities.dp(50), Utilities.dp(50));
avatarImage.draw(canvas, cellLayout.avatarLeft, cellLayout.avatarTop, AndroidUtilities.dp(50), AndroidUtilities.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);
canvas.drawLine(AndroidUtilities.dp(11), h - 1, getMeasuredWidth() - AndroidUtilities.dp(11), h, linePaint);
}
}
}
@ -262,14 +263,14 @@ public class ChatOrUserCell extends BaseCell {
private StaticLayout nameLayout;
private boolean drawNameLock;
private int nameLockLeft;
private int nameLockTop = Utilities.dp(15);
private int nameLockTop = AndroidUtilities.dp(15);
private int onlineLeft;
private int onlineTop = Utilities.dp(36);
private int onlineTop = AndroidUtilities.dp(36);
private int onlineWidth;
private StaticLayout onlineLayout;
private int avatarTop = Utilities.dp(7);
private int avatarTop = AndroidUtilities.dp(7);
private int avatarLeft;
public void build(int width, int height) {
@ -279,18 +280,18 @@ public class ChatOrUserCell extends BaseCell {
if (encryptedChat != null) {
drawNameLock = true;
if (!LocaleController.isRTL) {
nameLockLeft = Utilities.dp(61 + (usePadding ? 11 : 0));
nameLeft = Utilities.dp(65 + (usePadding ? 11 : 0)) + lockDrawable.getIntrinsicWidth();
nameLockLeft = AndroidUtilities.dp(61 + (usePadding ? 11 : 0));
nameLeft = AndroidUtilities.dp(65 + (usePadding ? 11 : 0)) + lockDrawable.getIntrinsicWidth();
} else {
nameLockLeft = width - Utilities.dp(63 + (usePadding ? 11 : 0)) - lockDrawable.getIntrinsicWidth();
nameLeft = usePadding ? Utilities.dp(11) : 0;
nameLockLeft = width - AndroidUtilities.dp(63 + (usePadding ? 11 : 0)) - lockDrawable.getIntrinsicWidth();
nameLeft = usePadding ? AndroidUtilities.dp(11) : 0;
}
} else {
drawNameLock = false;
if (!LocaleController.isRTL) {
nameLeft = Utilities.dp(61 + (usePadding ? 11 : 0));
nameLeft = AndroidUtilities.dp(61 + (usePadding ? 11 : 0));
} else {
nameLeft = usePadding ? Utilities.dp(11) : 0;
nameLeft = usePadding ? AndroidUtilities.dp(11) : 0;
}
}
@ -306,7 +307,7 @@ public class ChatOrUserCell extends BaseCell {
nameString = nameString2.replace("\n", " ");
}
if (nameString.length() == 0) {
if (user.phone != null && user.phone.length() != 0) {
if (user != null && user.phone != null && user.phone.length() != 0) {
nameString = PhoneFormat.getInstance().format("+" + user.phone);
} else {
nameString = LocaleController.getString("HiddenName", R.string.HiddenName);
@ -319,22 +320,22 @@ public class ChatOrUserCell extends BaseCell {
}
if (!LocaleController.isRTL) {
onlineWidth = nameWidth = width - nameLeft - Utilities.dp(3 + (usePadding ? 11 : 0));
onlineWidth = nameWidth = width - nameLeft - AndroidUtilities.dp(3 + (usePadding ? 11 : 0));
} else {
onlineWidth = nameWidth = width - nameLeft - Utilities.dp(61 + (usePadding ? 11 : 0));
onlineWidth = nameWidth = width - nameLeft - AndroidUtilities.dp(61 + (usePadding ? 11 : 0));
}
if (drawNameLock) {
nameWidth -= Utilities.dp(6) + lockDrawable.getIntrinsicWidth();
nameWidth -= AndroidUtilities.dp(6) + lockDrawable.getIntrinsicWidth();
}
CharSequence nameStringFinal = TextUtils.ellipsize(nameString, currentNamePaint, nameWidth - Utilities.dp(12), TextUtils.TruncateAt.END);
CharSequence nameStringFinal = TextUtils.ellipsize(nameString, currentNamePaint, nameWidth - AndroidUtilities.dp(12), TextUtils.TruncateAt.END);
nameLayout = new StaticLayout(nameStringFinal, currentNamePaint, nameWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
if (chat == null) {
if (!LocaleController.isRTL) {
onlineLeft = Utilities.dp(61 + (usePadding ? 11 : 0));
onlineLeft = AndroidUtilities.dp(61 + (usePadding ? 11 : 0));
} else {
onlineLeft = usePadding ? Utilities.dp(11) : 0;
onlineLeft = usePadding ? AndroidUtilities.dp(11) : 0;
}
String onlineString = "";
@ -350,23 +351,23 @@ public class ChatOrUserCell extends BaseCell {
}
}
CharSequence onlineStringFinal = TextUtils.ellipsize(onlineString, currentOnlinePaint, nameWidth - Utilities.dp(12), TextUtils.TruncateAt.END);
CharSequence onlineStringFinal = TextUtils.ellipsize(onlineString, currentOnlinePaint, nameWidth - AndroidUtilities.dp(12), TextUtils.TruncateAt.END);
onlineLayout = new StaticLayout(onlineStringFinal, currentOnlinePaint, nameWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
nameTop = Utilities.dp(12);
nameTop = AndroidUtilities.dp(12);
} else {
onlineLayout = null;
nameTop = Utilities.dp(22);
nameTop = AndroidUtilities.dp(22);
}
if (!LocaleController.isRTL) {
avatarLeft = usePadding ? Utilities.dp(11) : 0;
avatarLeft = usePadding ? AndroidUtilities.dp(11) : 0;
} else {
avatarLeft = width - Utilities.dp(50 + (usePadding ? 11 : 0));
avatarLeft = width - AndroidUtilities.dp(50 + (usePadding ? 11 : 0));
}
avatarImage.imageX = avatarLeft;
avatarImage.imageY = avatarTop;
avatarImage.imageW = Utilities.dp(50);
avatarImage.imageH = Utilities.dp(50);
avatarImage.imageW = AndroidUtilities.dp(50);
avatarImage.imageH = AndroidUtilities.dp(50);
double widthpx = 0;
float left = 0;

View File

@ -17,12 +17,13 @@ import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import org.telegram.android.AndroidUtilities;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.LocaleController;
import org.telegram.android.LocaleController;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.Emoji;
import org.telegram.messenger.MessagesController;
import org.telegram.android.ContactsController;
import org.telegram.android.Emoji;
import org.telegram.android.MessagesController;
import org.telegram.messenger.R;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
@ -58,46 +59,46 @@ public class DialogCell extends BaseCell {
private void init() {
if (namePaint == null) {
namePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
namePaint.setTextSize(Utilities.dp(19));
namePaint.setTextSize(AndroidUtilities.dp(19));
namePaint.setColor(0xff222222);
namePaint.setTypeface(Utilities.getTypeface("fonts/rmedium.ttf"));
namePaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
}
if (nameEncryptedPaint == null) {
nameEncryptedPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
nameEncryptedPaint.setTextSize(Utilities.dp(19));
nameEncryptedPaint.setTextSize(AndroidUtilities.dp(19));
nameEncryptedPaint.setColor(0xff00a60e);
nameEncryptedPaint.setTypeface(Utilities.getTypeface("fonts/rmedium.ttf"));
nameEncryptedPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
}
if (nameUnknownPaint == null) {
nameUnknownPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
nameUnknownPaint.setTextSize(Utilities.dp(19));
nameUnknownPaint.setTextSize(AndroidUtilities.dp(19));
nameUnknownPaint.setColor(0xff316f9f);
nameUnknownPaint.setTypeface(Utilities.getTypeface("fonts/rmedium.ttf"));
nameUnknownPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
}
if (messagePaint == null) {
messagePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
messagePaint.setTextSize(Utilities.dp(16));
messagePaint.setTextSize(AndroidUtilities.dp(16));
messagePaint.setColor(0xff808080);
}
if (messagePrintingPaint == null) {
messagePrintingPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
messagePrintingPaint.setTextSize(Utilities.dp(16));
messagePrintingPaint.setTextSize(AndroidUtilities.dp(16));
messagePrintingPaint.setColor(0xff316f9f);
}
if (timePaint == null) {
timePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
timePaint.setTextSize(Utilities.dp(14));
timePaint.setTextSize(AndroidUtilities.dp(14));
timePaint.setColor(0xff9e9e9e);
}
if (countPaint == null) {
countPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
countPaint.setTextSize(Utilities.dp(13));
countPaint.setTextSize(AndroidUtilities.dp(13));
countPaint.setColor(0xffffffff);
}
@ -159,7 +160,7 @@ public class DialogCell extends BaseCell {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), Utilities.dp(70));
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), AndroidUtilities.dp(70));
}
@Override
@ -309,20 +310,20 @@ public class DialogCell extends BaseCell {
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());
setDrawableBounds(countDrawable, cellLayout.countLeft - AndroidUtilities.dp(5), cellLayout.countTop, cellLayout.countWidth + AndroidUtilities.dp(10), countDrawable.getIntrinsicHeight());
countDrawable.draw(canvas);
canvas.save();
canvas.translate(cellLayout.countLeft, cellLayout.countTop + Utilities.dp(3));
canvas.translate(cellLayout.countLeft, cellLayout.countTop + AndroidUtilities.dp(3));
cellLayout.countLayout.draw(canvas);
canvas.restore();
}
avatarImage.draw(canvas, cellLayout.avatarLeft, cellLayout.avatarTop, Utilities.dp(54), Utilities.dp(54));
avatarImage.draw(canvas, cellLayout.avatarLeft, cellLayout.avatarTop, AndroidUtilities.dp(54), AndroidUtilities.dp(54));
}
private class DialogCellLayout {
private int nameLeft;
private int nameTop = Utilities.dp(10);
private int nameTop = AndroidUtilities.dp(10);
private int nameWidth;
private StaticLayout nameLayout;
private boolean drawNameLock;
@ -331,7 +332,7 @@ public class DialogCell extends BaseCell {
private int nameLockTop;
private int timeLeft;
private int timeTop = Utilities.dp(13);
private int timeTop = AndroidUtilities.dp(13);
private int timeWidth;
private StaticLayout timeLayout;
@ -339,25 +340,25 @@ public class DialogCell extends BaseCell {
private boolean drawCheck2;
private boolean drawClock;
private int checkDrawLeft;
private int checkDrawTop = Utilities.dp(15);
private int checkDrawTop = AndroidUtilities.dp(15);
private int halfCheckDrawLeft;
private int messageTop = Utilities.dp(40);
private int messageTop = AndroidUtilities.dp(40);
private int messageLeft;
private int messageWidth;
private StaticLayout messageLayout;
private boolean drawError;
private int errorTop = Utilities.dp(37);
private int errorTop = AndroidUtilities.dp(37);
private int errorLeft;
private boolean drawCount;
private int countTop = Utilities.dp(37);
private int countTop = AndroidUtilities.dp(37);
private int countLeft;
private int countWidth;
private StaticLayout countLayout;
private int avatarTop = Utilities.dp(8);
private int avatarTop = AndroidUtilities.dp(8);
private int avatarLeft;
public void build(int width, int height) {
@ -374,32 +375,32 @@ public class DialogCell extends BaseCell {
if (encryptedChat != null) {
drawNameLock = true;
drawNameGroup = false;
nameLockTop = Utilities.dp(13);
nameLockTop = AndroidUtilities.dp(13);
if (!LocaleController.isRTL) {
nameLockLeft = Utilities.dp(77);
nameLeft = Utilities.dp(81) + lockDrawable.getIntrinsicWidth();
nameLockLeft = AndroidUtilities.dp(77);
nameLeft = AndroidUtilities.dp(81) + lockDrawable.getIntrinsicWidth();
} else {
nameLockLeft = width - Utilities.dp(77) - lockDrawable.getIntrinsicWidth();
nameLeft = Utilities.dp(14);
nameLockLeft = width - AndroidUtilities.dp(77) - lockDrawable.getIntrinsicWidth();
nameLeft = AndroidUtilities.dp(14);
}
} else {
drawNameLock = false;
if (chat != null) {
drawNameGroup = true;
nameLockTop = Utilities.dp(14);
nameLockTop = AndroidUtilities.dp(14);
if (!LocaleController.isRTL) {
nameLockLeft = Utilities.dp(77);
nameLeft = Utilities.dp(81) + groupDrawable.getIntrinsicWidth();
nameLockLeft = AndroidUtilities.dp(77);
nameLeft = AndroidUtilities.dp(81) + groupDrawable.getIntrinsicWidth();
} else {
nameLockLeft = width - Utilities.dp(77) - groupDrawable.getIntrinsicWidth();
nameLeft = Utilities.dp(14);
nameLockLeft = width - AndroidUtilities.dp(77) - groupDrawable.getIntrinsicWidth();
nameLeft = AndroidUtilities.dp(14);
}
} else {
drawNameGroup = false;
if (!LocaleController.isRTL) {
nameLeft = Utilities.dp(77);
nameLeft = AndroidUtilities.dp(77);
} else {
nameLeft = Utilities.dp(14);
nameLeft = AndroidUtilities.dp(14);
}
}
}
@ -476,10 +477,10 @@ public class DialogCell extends BaseCell {
checkMessage = false;
if (message.messageOwner.media != null && !(message.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty)) {
currentMessagePaint = messagePrintingPaint;
messageString = Emoji.replaceEmoji(Html.fromHtml(String.format("<font color=#316f9f>%s:</font> <font color=#316f9f>%s</font>", name, message.messageText)), messagePaint.getFontMetricsInt(), Utilities.dp(20));
messageString = Emoji.replaceEmoji(Html.fromHtml(String.format("<font color=#316f9f>%s:</font> <font color=#316f9f>%s</font>", name, message.messageText)), messagePaint.getFontMetricsInt(), AndroidUtilities.dp(20));
} else {
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", " ").replace("<", "&lt;").replace(">", "&gt;"))), messagePaint.getFontMetricsInt(), Utilities.dp(20));
messageString = Emoji.replaceEmoji(Html.fromHtml(String.format("<font color=#316f9f>%s:</font> <font color=#808080>%s</font>", name, message.messageOwner.message.replace("\n", " ").replace("<", "&lt;").replace(">", "&gt;"))), messagePaint.getFontMetricsInt(), AndroidUtilities.dp(20));
}
}
} else {
@ -538,9 +539,9 @@ public class DialogCell extends BaseCell {
timeWidth = (int)Math.ceil(timePaint.measureText(timeString));
timeLayout = new StaticLayout(timeString, timePaint, timeWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
if (!LocaleController.isRTL) {
timeLeft = width - Utilities.dp(11) - timeWidth;
timeLeft = width - AndroidUtilities.dp(11) - timeWidth;
} else {
timeLeft = Utilities.dp(11);
timeLeft = AndroidUtilities.dp(11);
}
if (chat != null) {
@ -569,81 +570,81 @@ public class DialogCell extends BaseCell {
}
if (!LocaleController.isRTL) {
nameWidth = width - nameLeft - Utilities.dp(14) - timeWidth;
nameWidth = width - nameLeft - AndroidUtilities.dp(14) - timeWidth;
} else {
nameWidth = width - nameLeft - Utilities.dp(77) - timeWidth;
nameWidth = width - nameLeft - AndroidUtilities.dp(77) - timeWidth;
nameLeft += timeWidth;
}
if (drawNameLock) {
nameWidth -= Utilities.dp(4) + lockDrawable.getIntrinsicWidth();
nameWidth -= AndroidUtilities.dp(4) + lockDrawable.getIntrinsicWidth();
} else if (drawNameGroup) {
nameWidth -= Utilities.dp(4) + groupDrawable.getIntrinsicWidth();
nameWidth -= AndroidUtilities.dp(4) + groupDrawable.getIntrinsicWidth();
}
if (drawClock) {
int w = clockDrawable.getIntrinsicWidth() + Utilities.dp(2);
int w = clockDrawable.getIntrinsicWidth() + AndroidUtilities.dp(2);
nameWidth -= w;
if (!LocaleController.isRTL) {
checkDrawLeft = timeLeft - w;
} else {
checkDrawLeft = timeLeft + timeWidth + Utilities.dp(2);
checkDrawLeft = timeLeft + timeWidth + AndroidUtilities.dp(2);
nameLeft += w;
}
} else if (drawCheck2) {
int w = checkDrawable.getIntrinsicWidth() + Utilities.dp(2);
int w = checkDrawable.getIntrinsicWidth() + AndroidUtilities.dp(2);
nameWidth -= w;
if (drawCheck1) {
nameWidth -= halfCheckDrawable.getIntrinsicWidth() - Utilities.dp(5);
nameWidth -= halfCheckDrawable.getIntrinsicWidth() - AndroidUtilities.dp(5);
if (!LocaleController.isRTL) {
halfCheckDrawLeft = timeLeft - w;
checkDrawLeft = halfCheckDrawLeft - Utilities.dp(5);
checkDrawLeft = halfCheckDrawLeft - AndroidUtilities.dp(5);
} else {
checkDrawLeft = timeLeft + timeWidth + Utilities.dp(2);
halfCheckDrawLeft = checkDrawLeft + Utilities.dp(5);
nameLeft += w + halfCheckDrawable.getIntrinsicWidth() - Utilities.dp(5);
checkDrawLeft = timeLeft + timeWidth + AndroidUtilities.dp(2);
halfCheckDrawLeft = checkDrawLeft + AndroidUtilities.dp(5);
nameLeft += w + halfCheckDrawable.getIntrinsicWidth() - AndroidUtilities.dp(5);
}
} else {
if (!LocaleController.isRTL) {
checkDrawLeft = timeLeft - w;
} else {
checkDrawLeft = timeLeft + timeWidth + Utilities.dp(2);
checkDrawLeft = timeLeft + timeWidth + AndroidUtilities.dp(2);
nameLeft += w;
}
}
}
CharSequence nameStringFinal = TextUtils.ellipsize(nameString.replace("\n", " "), currentNamePaint, nameWidth - Utilities.dp(12), TextUtils.TruncateAt.END);
CharSequence nameStringFinal = TextUtils.ellipsize(nameString.replace("\n", " "), currentNamePaint, nameWidth - AndroidUtilities.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);
messageWidth = width - AndroidUtilities.dp(88);
if (!LocaleController.isRTL) {
messageLeft = Utilities.dp(77);
avatarLeft = Utilities.dp(11);
messageLeft = AndroidUtilities.dp(77);
avatarLeft = AndroidUtilities.dp(11);
} else {
messageLeft = Utilities.dp(11);
avatarLeft = width - Utilities.dp(65);
messageLeft = AndroidUtilities.dp(11);
avatarLeft = width - AndroidUtilities.dp(65);
}
avatarImage.imageX = avatarLeft;
avatarImage.imageY = avatarTop;
avatarImage.imageW = Utilities.dp(54);
avatarImage.imageH = Utilities.dp(54);
avatarImage.imageW = AndroidUtilities.dp(54);
avatarImage.imageH = AndroidUtilities.dp(54);
if (drawError) {
int w = errorDrawable.getIntrinsicWidth() + Utilities.dp(8);
int w = errorDrawable.getIntrinsicWidth() + AndroidUtilities.dp(8);
messageWidth -= w;
if (!LocaleController.isRTL) {
errorLeft = width - errorDrawable.getIntrinsicWidth() - Utilities.dp(11);
errorLeft = width - errorDrawable.getIntrinsicWidth() - AndroidUtilities.dp(11);
} else {
errorLeft = Utilities.dp(11);
errorLeft = AndroidUtilities.dp(11);
messageLeft += w;
}
} else if (countString != null) {
countWidth = Math.max(Utilities.dp(12), (int)Math.ceil(countPaint.measureText(countString)));
countWidth = Math.max(AndroidUtilities.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);
int w = countWidth + AndroidUtilities.dp(18);
messageWidth -= w;
if (!LocaleController.isRTL) {
countLeft = width - countWidth - Utilities.dp(16);
countLeft = width - countWidth - AndroidUtilities.dp(16);
} else {
countLeft = Utilities.dp(16);
countLeft = AndroidUtilities.dp(16);
messageLeft += w;
}
drawCount = true;
@ -659,10 +660,10 @@ public class DialogCell extends BaseCell {
if (mess.length() > 150) {
mess = mess.substring(0, 150);
}
messageString = Emoji.replaceEmoji(mess, messagePaint.getFontMetricsInt(), Utilities.dp(20));
messageString = Emoji.replaceEmoji(mess, messagePaint.getFontMetricsInt(), AndroidUtilities.dp(20));
}
CharSequence messageStringFinal = TextUtils.ellipsize(messageString, currentMessagePaint, messageWidth - Utilities.dp(12), TextUtils.TruncateAt.END);
CharSequence messageStringFinal = TextUtils.ellipsize(messageString, currentMessagePaint, messageWidth - AndroidUtilities.dp(12), TextUtils.TruncateAt.END);
messageLayout = new StaticLayout(messageStringFinal, currentMessagePaint, messageWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
double widthpx = 0;

File diff suppressed because it is too large Load Diff

View File

@ -11,6 +11,7 @@ package org.telegram.ui;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Html;
@ -22,12 +23,13 @@ import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessagesStorage;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.LocaleController;
import org.telegram.android.MessagesStorage;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.MessagesController;
import org.telegram.android.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.UserConfig;
@ -256,8 +258,13 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
}
@Override
public void didSelectContact(TLRPC.User user) {
MessagesController.getInstance().addUserToChat(chat_id, user, info);
public void didSelectContact(TLRPC.User user, String param) {
MessagesController.getInstance().addUserToChat(chat_id, user, info, Utilities.parseInt(param));
}
@Override
public void onActivityResultFragment(int requestCode, int resultCode, Intent data) {
avatarUpdater.onActivityResult(requestCode, resultCode, data);
}
@Override
@ -293,7 +300,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
avatarImage.getLocationInWindow(coords);
PhotoViewer.PlaceProviderObject object = new PhotoViewer.PlaceProviderObject();
object.viewX = coords[0];
object.viewY = coords[1] - Utilities.statusBarHeight;
object.viewY = coords[1] - AndroidUtilities.statusBarHeight;
object.parentView = listView;
object.imageReceiver = avatarImage.imageReceiver;
object.thumb = object.imageReceiver.getBitmap();
@ -436,6 +443,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
if (action == 0) {
TLRPC.Chat chat = MessagesController.getInstance().chats.get(chat_id);
if (chat.photo != null && chat.photo.photo_big != null) {
PhotoViewer.getInstance().setParentActivity(getParentActivity());
PhotoViewer.getInstance().openPhoto(chat.photo.photo_big, this);
}
} else if (action == 1) {
@ -590,15 +598,15 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
avatarImage = (BackupImageView)view.findViewById(R.id.settings_avatar_image);
avatarImage.processDetach = false;
TextView textView = (TextView)view.findViewById(R.id.settings_name);
Typeface typeface = Utilities.getTypeface("fonts/rmedium.ttf");
Typeface typeface = AndroidUtilities.getTypeface("fonts/rmedium.ttf");
textView.setTypeface(typeface);
textView.setText(chat.title);
if (chat.participants_count != 0 && onlineCount > 0) {
onlineText.setText(Html.fromHtml(String.format("%d %s, <font color='#357aa8'>%d %s</font>", chat.participants_count, LocaleController.getString("Members", R.string.Members), onlineCount, LocaleController.getString("Online", R.string.Online))));
onlineText.setText(Html.fromHtml(String.format("%s, <font color='#357aa8'>%d %s</font>", LocaleController.formatPluralString("Members", chat.participants_count), onlineCount, LocaleController.getString("Online", R.string.Online))));
} else {
onlineText.setText(String.format("%d %s", chat.participants_count, LocaleController.getString("Members", R.string.Members)));
onlineText.setText(LocaleController.formatPluralString("Members", chat.participants_count));
}
TLRPC.FileLocation photo = null;
@ -622,7 +630,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
textView.setText(LocaleController.getString("SHAREDMEDIA", R.string.SHAREDMEDIA));
} else if (i == membersSectionRow) {
TLRPC.Chat chat = MessagesController.getInstance().chats.get(chat_id);
textView.setText(String.format("%d %s", chat.participants_count, LocaleController.getString("MEMBERS", R.string.MEMBERS)));
textView.setText(LocaleController.formatPluralString("Members", chat.participants_count).toUpperCase());
}
} else if (type == 2) {
if (view == null) {
@ -672,7 +680,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure));
builder.setMessage(LocaleController.getString("AreYouSureDeleteAndExit", R.string.AreYouSureDeleteAndExit));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
@Override

View File

@ -20,11 +20,11 @@ import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.telegram.messenger.LocaleController;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.LocaleController;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.MessagesController;
import org.telegram.android.MessagesController;
import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;
import org.telegram.ui.Views.ActionBar.BaseFragment;
public class ChatProfileChangeNameActivity extends BaseFragment {
@ -108,14 +108,14 @@ public class ChatProfileChangeNameActivity extends BaseFragment {
boolean animations = preferences.getBoolean("view_animations", true);
if (!animations) {
firstNameField.requestFocus();
Utilities.showKeyboard(firstNameField);
AndroidUtilities.showKeyboard(firstNameField);
}
}
@Override
public void onOpenAnimationEnd() {
firstNameField.requestFocus();
Utilities.showKeyboard(firstNameField);
AndroidUtilities.showKeyboard(firstNameField);
}
private void saveName() {

View File

@ -21,11 +21,12 @@ import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.telegram.android.AndroidUtilities;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.LocaleController;
import org.telegram.android.ContactsController;
import org.telegram.android.LocaleController;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.MessagesController;
import org.telegram.android.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;
@ -104,7 +105,7 @@ public class ContactAddActivity extends BaseFragment implements NotificationCent
avatarImage = (BackupImageView)fragmentView.findViewById(R.id.settings_avatar_image);
avatarImage.processDetach = false;
phoneText = (TextView)fragmentView.findViewById(R.id.settings_name);
Typeface typeface = Utilities.getTypeface("fonts/rmedium.ttf");
Typeface typeface = AndroidUtilities.getTypeface("fonts/rmedium.ttf");
phoneText.setTypeface(typeface);
firstNameField = (EditText)fragmentView.findViewById(R.id.first_name_field);
@ -183,13 +184,13 @@ public class ContactAddActivity extends BaseFragment implements NotificationCent
boolean animations = preferences.getBoolean("view_animations", true);
if (!animations) {
firstNameField.requestFocus();
Utilities.showKeyboard(firstNameField);
AndroidUtilities.showKeyboard(firstNameField);
}
}
@Override
public void onOpenAnimationEnd() {
firstNameField.requestFocus();
Utilities.showKeyboard(firstNameField);
AndroidUtilities.showKeyboard(firstNameField);
}
}

View File

@ -15,21 +15,26 @@ import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import org.telegram.messenger.LocaleController;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.LocaleController;
import org.telegram.messenger.TLObject;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.ContactsController;
import org.telegram.android.ContactsController;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.MessagesController;
import org.telegram.android.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.RPCRequest;
@ -70,7 +75,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
private ContactsActivityDelegate delegate;
public static interface ContactsActivityDelegate {
public abstract void didSelectContact(TLRPC.User user);
public abstract void didSelectContact(TLRPC.User user, String param);
}
public ContactsActivity(Bundle args) {
@ -148,9 +153,9 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
listView.setAdapter(listViewAdapter);
listViewAdapter.notifyDataSetChanged();
if (!LocaleController.isRTL) {
listView.setPadding(Utilities.dp(16), listView.getPaddingTop(), Utilities.dp(30), listView.getPaddingBottom());
listView.setPadding(AndroidUtilities.dp(16), listView.getPaddingTop(), AndroidUtilities.dp(30), listView.getPaddingBottom());
} else {
listView.setPadding(Utilities.dp(30), listView.getPaddingTop(), Utilities.dp(16), listView.getPaddingBottom());
listView.setPadding(AndroidUtilities.dp(30), listView.getPaddingTop(), AndroidUtilities.dp(16), listView.getPaddingBottom());
}
if (android.os.Build.VERSION.SDK_INT >= 11) {
listView.setFastScrollAlwaysVisible(true);
@ -170,7 +175,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
if (text.length() != 0) {
searchWas = true;
if (listView != null) {
listView.setPadding(Utilities.dp(16), listView.getPaddingTop(), Utilities.dp(16), listView.getPaddingBottom());
listView.setPadding(AndroidUtilities.dp(16), listView.getPaddingTop(), AndroidUtilities.dp(16), listView.getPaddingBottom());
listView.setAdapter(searchListViewAdapter);
searchListViewAdapter.notifyDataSetChanged();
if(android.os.Build.VERSION.SDK_INT >= 11) {
@ -214,7 +219,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
if (ignoreUsers != null && ignoreUsers.containsKey(user.id)) {
return;
}
didSelectResult(user, true);
didSelectResult(user, true, null);
} else {
if (createSecretChat) {
creatingChat = true;
@ -272,7 +277,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
if (ignoreUsers != null && ignoreUsers.containsKey(user.id)) {
return;
}
didSelectResult(user, true);
didSelectResult(user, true, null);
} else {
if (createSecretChat) {
creatingChat = true;
@ -320,7 +325,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
@Override
public void onScrollStateChanged(AbsListView absListView, int i) {
if (i == SCROLL_STATE_TOUCH_SCROLL && searching && searchWas) {
Utilities.hideKeyboard(getParentActivity().getCurrentFocus());
AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus());
}
}
@ -337,7 +342,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
return fragmentView;
}
private void didSelectResult(final TLRPC.User user, boolean useAlert) {
private void didSelectResult(final TLRPC.User user, boolean useAlert, String param) {
if (useAlert && selectAlertString != null) {
if (getParentActivity() == null) {
return;
@ -345,17 +350,36 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setMessage(LocaleController.formatStringSimple(selectAlertString, Utilities.formatName(user.first_name, user.last_name)));
final EditText editText = new EditText(getParentActivity());
if (android.os.Build.VERSION.SDK_INT < 11) {
editText.setBackgroundResource(android.R.drawable.editbox_background_normal);
}
editText.setTextSize(18);
editText.setText("50");
editText.setGravity(Gravity.CENTER);
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
editText.setImeOptions(EditorInfo.IME_ACTION_DONE);
builder.setView(editText);
builder.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
didSelectResult(user, false);
didSelectResult(user, false, editText.getText().toString());
}
});
builder.setNegativeButton(R.string.Cancel, null);
showAlertDialog(builder);
ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams)editText.getLayoutParams();
if (layoutParams != null) {
if (layoutParams instanceof FrameLayout.LayoutParams) {
((FrameLayout.LayoutParams)layoutParams).gravity = Gravity.CENTER_HORIZONTAL;
}
layoutParams.rightMargin = layoutParams.leftMargin = AndroidUtilities.dp(10);
editText.setLayoutParams(layoutParams);
}
editText.setSelection(editText.getText().length());
} else {
if (delegate != null) {
delegate.didSelectContact(user);
delegate.didSelectContact(user, param);
delegate = null;
}
finishFragment();
@ -419,7 +443,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
}
}
}
}, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors);
}, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors);
}
}

View File

@ -18,8 +18,9 @@ import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;
import org.telegram.android.AndroidUtilities;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.android.LocaleController;
import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;
import org.telegram.ui.Adapters.BaseFragmentAdapter;
@ -147,9 +148,9 @@ public class CountrySelectActivity extends BaseFragment {
ViewGroup group = (ViewGroup) listView.getParent();
listView.setAdapter(listViewAdapter);
if (!LocaleController.isRTL) {
listView.setPadding(Utilities.dp(16), listView.getPaddingTop(), Utilities.dp(30), listView.getPaddingBottom());
listView.setPadding(AndroidUtilities.dp(16), listView.getPaddingTop(), AndroidUtilities.dp(30), listView.getPaddingBottom());
} else {
listView.setPadding(Utilities.dp(30), listView.getPaddingTop(), Utilities.dp(16), listView.getPaddingBottom());
listView.setPadding(AndroidUtilities.dp(30), listView.getPaddingTop(), AndroidUtilities.dp(16), listView.getPaddingBottom());
}
if (android.os.Build.VERSION.SDK_INT >= 11) {
listView.setFastScrollAlwaysVisible(true);
@ -167,7 +168,7 @@ public class CountrySelectActivity extends BaseFragment {
if (text.length() != 0) {
searchWas = true;
if (listView != null) {
listView.setPadding(Utilities.dp(16), listView.getPaddingTop(), Utilities.dp(16), listView.getPaddingBottom());
listView.setPadding(AndroidUtilities.dp(16), listView.getPaddingTop(), AndroidUtilities.dp(16), listView.getPaddingBottom());
listView.setAdapter(searchListViewAdapter);
if(android.os.Build.VERSION.SDK_INT >= 11) {
listView.setFastScrollAlwaysVisible(false);
@ -228,7 +229,7 @@ public class CountrySelectActivity extends BaseFragment {
@Override
public void onScrollStateChanged(AbsListView absListView, int i) {
if (i == SCROLL_STATE_TOUCH_SCROLL && searching && searchWas) {
Utilities.hideKeyboard(getParentActivity().getCurrentFocus());
AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus());
}
}

View File

@ -24,7 +24,7 @@ import android.widget.ListView;
import android.widget.TextView;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.android.LocaleController;
import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;
import org.telegram.ui.Adapters.BaseFragmentAdapter;

View File

@ -32,13 +32,14 @@ import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import org.telegram.android.AndroidUtilities;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.LocaleController;
import org.telegram.android.LocaleController;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.ContactsController;
import org.telegram.android.ContactsController;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.MessagesController;
import org.telegram.android.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.UserConfig;
@ -72,7 +73,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
int sz = super.getSize(paint, text, start, end, fm);
int offset = Utilities.dp(6);
int offset = AndroidUtilities.dp(6);
int w = (fm.bottom - fm.top) / 2;
fm.top = -w - offset;
fm.bottom = w - offset;
@ -126,7 +127,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
actionBarLayer.setDisplayHomeAsUpEnabled(true, R.drawable.ic_ab_back);
actionBarLayer.setBackOverlay(R.layout.updating_state_layout);
actionBarLayer.setTitle(LocaleController.getString("NewGroup", R.string.NewGroup));
actionBarLayer.setSubtitle(String.format("%d/200 %s", selectedContacts.size(), LocaleController.getString("Members", R.string.Members)));
actionBarLayer.setSubtitle(LocaleController.formatString("MembersCount", R.string.MembersCount, selectedContacts.size(), 200));
actionBarLayer.setActionBarMenuOnItemClick(new ActionBarLayer.ActionBarMenuOnItemClick() {
@Override
@ -200,7 +201,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
selectedContacts.remove(sp.uid);
}
}
actionBarLayer.setSubtitle(String.format("%d/200 %s", selectedContacts.size(), LocaleController.getString("Members", R.string.Members)));
actionBarLayer.setSubtitle(LocaleController.formatString("MembersCount", R.string.MembersCount, selectedContacts.size(), 200));
listView.invalidateViews();
} else {
search = true;
@ -266,7 +267,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
span.uid = user.id;
ignoreChange = false;
}
actionBarLayer.setSubtitle(String.format("%d/200 %s", selectedContacts.size(), LocaleController.getString("Members", R.string.Members)));
actionBarLayer.setSubtitle(LocaleController.formatString("MembersCount", R.string.MembersCount, selectedContacts.size(), 200));
if (searching || searchWas) {
searching = false;
searchWas = false;
@ -293,7 +294,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
@Override
public void onScrollStateChanged(AbsListView absListView, int i) {
if (i == SCROLL_STATE_TOUCH_SCROLL) {
Utilities.hideKeyboard(userSelectEditText);
AndroidUtilities.hideKeyboard(userSelectEditText);
}
}

View File

@ -22,11 +22,11 @@ import android.widget.ImageButton;
import android.widget.TextView;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessagesStorage;
import org.telegram.android.LocaleController;
import org.telegram.android.MessagesStorage;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.MessagesController;
import org.telegram.android.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;
@ -407,11 +407,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
convertView.setBackgroundColor(0xffffffff);
}
TextView textView = (TextView)convertView.findViewById(R.id.settings_section_text);
if (selectedContacts.size() == 1) {
textView.setText(selectedContacts.size() + " " + LocaleController.getString("MEMBER", R.string.MEMBER));
} else {
textView.setText(selectedContacts.size() + " " + LocaleController.getString("MEMBERS", R.string.MEMBERS));
}
textView.setText(LocaleController.formatPluralString("Members", selectedContacts.size()).toUpperCase());
return convertView;
}
}

View File

@ -20,11 +20,11 @@ import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.telegram.messenger.LocaleController;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.LocaleController;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.MessagesController;
import org.telegram.android.MessagesController;
import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;
import org.telegram.ui.Views.ActionBar.ActionBarLayer;
import org.telegram.ui.Views.ActionBar.BaseFragment;
import org.telegram.ui.Views.IdenticonView;
@ -48,7 +48,7 @@ public class IdenticonActivity extends BaseFragment {
actionBarLayer.setDisplayHomeAsUpEnabled(true, R.drawable.ic_ab_back);
actionBarLayer.setBackOverlay(R.layout.updating_state_layout);
actionBarLayer.setTitle(LocaleController.getString("EncryptionKey", R.string.EncryptionKey));
actionBarLayer.setTitleIcon(R.drawable.ic_lock_white, Utilities.dp(4));
actionBarLayer.setTitleIcon(R.drawable.ic_lock_white, AndroidUtilities.dp(4));
actionBarLayer.setActionBarMenuOnItemClick(new ActionBarLayer.ActionBarMenuOnItemClick() {
@Override

View File

@ -24,7 +24,7 @@ import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import org.telegram.messenger.LocaleController;
import org.telegram.android.LocaleController;
import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;

View File

@ -20,8 +20,9 @@ import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import org.telegram.android.AndroidUtilities;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.android.LocaleController;
import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;
import org.telegram.ui.Adapters.BaseFragmentAdapter;
@ -86,7 +87,7 @@ public class LanguageSelectActivity extends BaseFragment {
if (text.length() != 0) {
searchWas = true;
if (listView != null) {
listView.setPadding(Utilities.dp(16), listView.getPaddingTop(), Utilities.dp(16), listView.getPaddingBottom());
listView.setPadding(AndroidUtilities.dp(16), listView.getPaddingTop(), AndroidUtilities.dp(16), listView.getPaddingBottom());
listView.setAdapter(searchListViewAdapter);
if(android.os.Build.VERSION.SDK_INT >= 11) {
listView.setFastScrollAlwaysVisible(false);
@ -176,7 +177,7 @@ public class LanguageSelectActivity extends BaseFragment {
@Override
public void onScrollStateChanged(AbsListView absListView, int i) {
if (i == SCROLL_STATE_TOUCH_SCROLL && searching && searchWas) {
Utilities.hideKeyboard(getParentActivity().getCurrentFocus());
AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus());
}
}

View File

@ -8,38 +8,31 @@
package org.telegram.ui;
import android.app.NotificationManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.ContactsContract;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.telegram.android.AndroidUtilities;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessagesController;
import org.telegram.android.LocaleController;
import org.telegram.android.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
import org.telegram.objects.MessageObject;
import org.telegram.ui.Views.ActionBar.ActionBarActivity;
import org.telegram.ui.Views.ActionBar.BaseFragment;
import org.telegram.ui.Views.NotificationView;
import java.io.BufferedReader;
import java.io.InputStream;
@ -49,7 +42,6 @@ import java.util.Map;
public class LaunchActivity extends ActionBarActivity implements NotificationCenter.NotificationCenterDelegate, MessagesActivity.MessagesActivityDelegate {
private boolean finished = false;
private NotificationView notificationView;
private String videoPath = null;
private String sendingText = null;
private ArrayList<Uri> photoPathsArray = null;
@ -86,11 +78,11 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
Utilities.statusBarHeight = getResources().getDimensionPixelSize(resourceId);
AndroidUtilities.statusBarHeight = getResources().getDimensionPixelSize(resourceId);
}
NotificationCenter.getInstance().postNotificationName(702, this);
currentConnectionState = ConnectionsManager.getInstance().connectionState;
currentConnectionState = ConnectionsManager.getInstance().getConnectionState();
NotificationCenter.getInstance().addObserver(this, 1234);
NotificationCenter.getInstance().addObserver(this, 658);
@ -148,8 +140,6 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
}
handleIntent(getIntent(), false, savedInstanceState != null);
PhotoViewer.getInstance().setParentActivity(this);
}
private void handleIntent(Intent intent, boolean isNew, boolean restore) {
@ -423,7 +413,7 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats);
Bundle args = new Bundle();
args.putBoolean("onlySelect", true);
args.putString("selectAlertString", LocaleController.getString("ForwardMessagesTo", R.string.ForwardMessagesTo));
args.putString("selectAlertString", LocaleController.getString("SendMessagesTo", R.string.SendMessagesTo));
MessagesActivity fragment = new MessagesActivity(args);
fragment.setDelegate(this);
presentFragment(fragment, false, true);
@ -447,7 +437,7 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
}
@Override
public void didSelectDialog(MessagesActivity messageFragment, long dialog_id) {
public void didSelectDialog(MessagesActivity messageFragment, long dialog_id, boolean param) {
if (dialog_id != 0) {
int lower_part = (int)dialog_id;
@ -504,18 +494,13 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
@Override
protected void onPause() {
super.onPause();
ConnectionsManager.setAppPaused(true);
if (notificationView != null) {
notificationView.hide(false);
}
View focusView = getCurrentFocus();
if (focusView instanceof EditText) {
focusView.clearFocus();
}
ApplicationLoader.mainInterfacePaused = true;
ConnectionsManager.getInstance().setAppPaused(true, false);
}
@Override
protected void onDestroy() {
PhotoViewer.getInstance().destroyPhotoViewer();
super.onDestroy();
onFinish();
}
@ -523,20 +508,11 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
@Override
protected void onResume() {
super.onResume();
if (notificationView == null && getLayoutInflater() != null) {
notificationView = (NotificationView) getLayoutInflater().inflate(R.layout.notification_layout, null);
}
Utilities.checkForCrashes(this);
Utilities.checkForUpdates(this);
ConnectionsManager.setAppPaused(false);
ApplicationLoader.mainInterfacePaused = false;
ConnectionsManager.getInstance().setAppPaused(false, false);
actionBar.setBackOverlayVisible(currentConnectionState != 0);
try {
NotificationManager mNotificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(1);
MessagesController.getInstance().currentPushMessage = null;
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
@Override
@ -550,32 +526,12 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
NotificationCenter.getInstance().removeObserver(this, 701);
NotificationCenter.getInstance().removeObserver(this, 702);
NotificationCenter.getInstance().removeObserver(this, 703);
if (notificationView != null) {
notificationView.hide(false);
notificationView.destroy();
notificationView = null;
}
}
@Override
public void onConfigurationChanged(android.content.res.Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Utilities.checkDisplaySize();
}
@Override
public void needLayout() {
super.needLayout();
if (notificationView != null) {
WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
int rotation = manager.getDefaultDisplay().getRotation();
int height = Utilities.dp(48);
if (!Utilities.isTablet(this) && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
height = Utilities.dp(40);
}
notificationView.applyOrientationPaddings(rotation == Surface.ROTATION_270 || rotation == Surface.ROTATION_90, height);
}
AndroidUtilities.checkDisplaySize();
}
@Override
@ -614,11 +570,6 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
args2.putInt("enc_id", push_enc_id);
presentFragment(new ChatActivity(args2), false, true);
}
} else if (id == 701) {
if (notificationView != null) {
MessageObject message = (MessageObject)args[0];
notificationView.show(message);
}
} else if (id == 702) {
if (args[0] != this) {
onFinish();
@ -696,4 +647,9 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
}
return super.onPreIme();
}
@Override
public void onLowMemory() {
super.onLowMemory();
}
}

View File

@ -26,10 +26,10 @@ import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.android.LocaleController;
import org.telegram.messenger.TLRPC;
import org.telegram.objects.MessageObject;
import org.telegram.messenger.MessagesController;
import org.telegram.android.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;
@ -133,6 +133,9 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
}
avatarImageView = (BackupImageView)fragmentView.findViewById(R.id.location_avatar_view);
if (avatarImageView != null) {
avatarImageView.processDetach = false;
}
nameTextView = (TextView)fragmentView.findViewById(R.id.location_name_label);
distanceTextView = (TextView)fragmentView.findViewById(R.id.location_distance_label);
View bottomView = fragmentView.findViewById(R.id.location_bottom_view);

View File

@ -22,8 +22,9 @@ import android.widget.FrameLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import org.telegram.android.AndroidUtilities;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.android.LocaleController;
import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;
import org.telegram.ui.Views.ActionBar.ActionBarLayer;
@ -265,7 +266,7 @@ public class LoginActivity extends BaseFragment implements SlideView.SlideViewDe
newView.setParams(params);
actionBarLayer.setTitle(newView.getHeaderName());
newView.onShow();
newView.setX(back ? -Utilities.displaySize.x : Utilities.displaySize.x);
newView.setX(back ? -AndroidUtilities.displaySize.x : AndroidUtilities.displaySize.x);
outView.animate().setInterpolator(new AccelerateDecelerateInterpolator()).setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
@ -284,7 +285,7 @@ public class LoginActivity extends BaseFragment implements SlideView.SlideViewDe
@Override
public void onAnimationRepeat(Animator animator) {
}
}).setDuration(300).translationX(back ? Utilities.displaySize.x : -Utilities.displaySize.x).start();
}).setDuration(300).translationX(back ? AndroidUtilities.displaySize.x : -AndroidUtilities.displaySize.x).start();
newView.animate().setInterpolator(new AccelerateDecelerateInterpolator()).setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {

View File

@ -21,9 +21,10 @@ import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;
import org.telegram.android.AndroidUtilities;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.BuildVars;
import org.telegram.messenger.LocaleController;
import org.telegram.android.LocaleController;
import org.telegram.messenger.TLObject;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.ConnectionsManager;
@ -250,10 +251,10 @@ public class LoginActivityPhoneView extends SlideView implements AdapterView.OnI
}
if (codeField.length() != 0) {
Utilities.showKeyboard(phoneField);
AndroidUtilities.showKeyboard(phoneField);
phoneField.requestFocus();
} else {
Utilities.showKeyboard(codeField);
AndroidUtilities.showKeyboard(codeField);
codeField.requestFocus();
}
phoneField.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@ -389,7 +390,7 @@ public class LoginActivityPhoneView extends SlideView implements AdapterView.OnI
}
});
}
}, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassWithoutLogin);
}, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassWithoutLogin | RPCRequest.RPCRequestClassTryDifferentDc | RPCRequest.RPCRequestClassEnableUnauthorized);
}
@Override

View File

@ -17,13 +17,13 @@ import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import org.telegram.messenger.LocaleController;
import org.telegram.android.LocaleController;
import org.telegram.messenger.TLObject;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage;
import org.telegram.android.ContactsController;
import org.telegram.android.MessagesController;
import org.telegram.android.MessagesStorage;
import org.telegram.messenger.R;
import org.telegram.messenger.RPCRequest;
import org.telegram.messenger.UserConfig;
@ -184,7 +184,7 @@ public class LoginActivityRegisterView extends SlideView {
}
});
}
}, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassWithoutLogin);
}, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassWithoutLogin);
}
@Override

View File

@ -9,6 +9,9 @@
package org.telegram.ui;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.util.AttributeSet;
@ -18,15 +21,16 @@ import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import org.telegram.android.AndroidUtilities;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.LocaleController;
import org.telegram.android.LocaleController;
import org.telegram.messenger.TLObject;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.ContactsController;
import org.telegram.android.ContactsController;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage;
import org.telegram.android.MessagesController;
import org.telegram.android.MessagesStorage;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.RPCRequest;
@ -35,6 +39,7 @@ import org.telegram.messenger.Utilities;
import org.telegram.ui.Views.SlideView;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
@ -45,6 +50,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
private EditText codeField;
private TextView confirmTextView;
private TextView timeText;
private TextView problemText;
private Bundle currentParams;
private Timer timeTimer;
@ -53,6 +59,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
private double lastCurrentTime;
private boolean waitingForSms = false;
private boolean nextPressed = false;
private String lastError = "";
public LoginActivitySmsView(Context context) {
super(context);
@ -74,8 +81,11 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
codeField = (EditText)findViewById(R.id.login_sms_code_field);
codeField.setHint(LocaleController.getString("Code", R.string.Code));
timeText = (TextView)findViewById(R.id.login_time_text);
problemText = (TextView)findViewById(R.id.login_problem);
TextView wrongNumber = (TextView) findViewById(R.id.wrong_number);
wrongNumber.setText(LocaleController.getString("WrongNumber", R.string.WrongNumber));
problemText.setText(LocaleController.getString("DidNotGetTheCode", R.string.DidNotGetTheCode));
problemText.setVisibility(time < 1000 ? VISIBLE : GONE);
wrongNumber.setOnClickListener(new OnClickListener() {
@Override
@ -85,6 +95,27 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
}
});
problemText.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
PackageInfo pInfo = ApplicationLoader.applicationContext.getPackageManager().getPackageInfo(ApplicationLoader.applicationContext.getPackageName(), 0);
String version = String.format(Locale.US, "%s (%d)", pInfo.versionName, pInfo.versionCode);
Intent mailer = new Intent(Intent.ACTION_SEND);
mailer.setType("message/rfc822");
mailer.putExtra(Intent.EXTRA_EMAIL, new String[]{"sms@telegram.org"});
mailer.putExtra(Intent.EXTRA_SUBJECT, "Android registration/login issue " + version + " " + requestPhone);
mailer.putExtra(Intent.EXTRA_TEXT, "Phone: " + requestPhone + "\nApp version: " + version + "\nOS version: SDK " + Build.VERSION.SDK_INT + "\nDevice Name: " + Build.MANUFACTURER + Build.MODEL + "\nLocale: " + Locale.getDefault() + "\nError: " + lastError);
getContext().startActivity(Intent.createChooser(mailer, "Send email..."));
} catch (Exception e) {
if (delegate != null) {
delegate.needShowAlert(LocaleController.getString("NoMailInstalled", R.string.NoMailInstalled));
}
}
}
});
codeField.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
@ -110,7 +141,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
return;
}
codeField.setText("");
Utilities.setWaitingForSms(true);
AndroidUtilities.setWaitingForSms(true);
NotificationCenter.getInstance().addObserver(this, 998);
currentParams = params;
waitingForSms = true;
@ -127,12 +158,13 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
String number = PhoneFormat.getInstance().format(phone);
confirmTextView.setText(Html.fromHtml(String.format(LocaleController.getString("SentSmsCode", R.string.SentSmsCode) + " <b>%s</b>", number)));
Utilities.showKeyboard(codeField);
AndroidUtilities.showKeyboard(codeField);
codeField.requestFocus();
destroyTimer();
timeText.setText(String.format("%s 1:00", LocaleController.getString("CallText", R.string.CallText)));
lastCurrentTime = System.currentTimeMillis();
problemText.setVisibility(time < 1000 ? VISIBLE : GONE);
createTimer();
}
@ -157,6 +189,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
int seconds = time / 1000 - minutes * 60;
timeText.setText(String.format("%s %d:%02d", LocaleController.getString("CallText", R.string.CallText), minutes, seconds));
} else {
problemText.setVisibility(VISIBLE);
timeText.setText(LocaleController.getString("Calling", R.string.Calling));
destroyTimer();
TLRPC.TL_auth_sendCall req = new TLRPC.TL_auth_sendCall();
@ -164,9 +197,17 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
req.phone_code_hash = phoneHash;
ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
public void run(TLObject response, final TLRPC.TL_error error) {
if (error != null && error.text != null) {
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
lastError = error.text;
}
});
}
}
}, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassWithoutLogin);
}, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassWithoutLogin);
}
}
});
@ -194,7 +235,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
}
nextPressed = true;
waitingForSms = false;
Utilities.setWaitingForSms(false);
AndroidUtilities.setWaitingForSms(false);
NotificationCenter.getInstance().removeObserver(this, 998);
final TLRPC.TL_auth_signIn req = new TLRPC.TL_auth_signIn();
req.phone_number = requestPhone;
@ -231,6 +272,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
delegate.needFinishActivity();
ConnectionsManager.getInstance().initPushConnection();
} else {
lastError = error.text;
if (error.text.contains("PHONE_NUMBER_UNOCCUPIED") && registered == null) {
Bundle params = new Bundle();
params.putString("phoneFormated", requestPhone);
@ -256,14 +298,14 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
}
});
}
}, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassWithoutLogin);
}, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassWithoutLogin);
}
@Override
public void onBackPressed() {
destroyTimer();
currentParams = null;
Utilities.setWaitingForSms(false);
AndroidUtilities.setWaitingForSms(false);
NotificationCenter.getInstance().removeObserver(this, 998);
waitingForSms = false;
}
@ -271,7 +313,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
@Override
public void onDestroyActivity() {
super.onDestroyActivity();
Utilities.setWaitingForSms(false);
AndroidUtilities.setWaitingForSms(false);
NotificationCenter.getInstance().removeObserver(this, 998);
destroyTimer();
waitingForSms = false;

View File

@ -23,11 +23,11 @@ import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import org.telegram.messenger.LocaleController;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.LocaleController;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.Utilities;
import org.telegram.objects.MessageObject;
import org.telegram.messenger.MessagesController;
import org.telegram.android.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.objects.PhotoObject;
@ -114,6 +114,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
PhotoViewer.getInstance().setParentActivity(getParentActivity());
PhotoViewer.getInstance().openPhoto(messages, i, MediaActivity.this);
}
});
@ -284,7 +285,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No
imageView.getLocationInWindow(coords);
PhotoViewer.PlaceProviderObject object = new PhotoViewer.PlaceProviderObject();
object.viewX = coords[0];
object.viewY = coords[1] - Utilities.statusBarHeight;
object.viewY = coords[1] - AndroidUtilities.statusBarHeight;
object.parentView = listView;
object.imageReceiver = imageView.imageReceiver;
object.thumb = object.imageReceiver.getBitmap();
@ -327,14 +328,14 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No
if (rotation == Surface.ROTATION_270 || rotation == Surface.ROTATION_90) {
listView.setNumColumns(6);
itemWidth = getParentActivity().getResources().getDisplayMetrics().widthPixels / 6 - Utilities.dp(2) * 5;
itemWidth = getParentActivity().getResources().getDisplayMetrics().widthPixels / 6 - AndroidUtilities.dp(2) * 5;
listView.setColumnWidth(itemWidth);
} else {
listView.setNumColumns(4);
itemWidth = getParentActivity().getResources().getDisplayMetrics().widthPixels / 4 - Utilities.dp(2) * 3;
itemWidth = getParentActivity().getResources().getDisplayMetrics().widthPixels / 4 - AndroidUtilities.dp(2) * 3;
listView.setColumnWidth(itemWidth);
}
listView.setPadding(listView.getPaddingLeft(), Utilities.dp(4), listView.getPaddingRight(), listView.getPaddingBottom());
listView.setPadding(listView.getPaddingLeft(), AndroidUtilities.dp(4), listView.getPaddingRight(), listView.getPaddingBottom());
listAdapter.notifyDataSetChanged();
if (listView != null) {

View File

@ -17,17 +17,19 @@ import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import org.telegram.messenger.LocaleController;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.LocaleController;
import org.telegram.messenger.TLObject;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.ContactsController;
import org.telegram.android.ContactsController;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage;
import org.telegram.android.MessagesController;
import org.telegram.android.MessagesStorage;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.UserConfig;
@ -74,7 +76,7 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
private final static int messages_list_menu_settings = 5;
public static interface MessagesActivityDelegate {
public abstract void didSelectDialog(MessagesActivity fragment, long dialog_id);
public abstract void didSelectDialog(MessagesActivity fragment, long dialog_id, boolean param);
}
public MessagesActivity(Bundle args) {
@ -276,7 +278,7 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
}
}
if (onlySelect) {
didSelectResult(dialog_id, true);
didSelectResult(dialog_id, true, false);
} else {
Bundle args = new Bundle();
int lower_part = (int)dialog_id;
@ -324,8 +326,18 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
if (which == 0) {
MessagesController.getInstance().deleteDialog(selectedDialog, 0, true);
} else if (which == 1) {
MessagesController.getInstance().deleteUserFromChat((int) -selectedDialog, MessagesController.getInstance().users.get(UserConfig.getClientUserId()), null);
MessagesController.getInstance().deleteDialog(selectedDialog, 0, false);
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setMessage(LocaleController.getString("AreYouSureDeleteAndExit", R.string.AreYouSureDeleteAndExit));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
MessagesController.getInstance().deleteUserFromChat((int) -selectedDialog, MessagesController.getInstance().users.get(UserConfig.getClientUserId()), null);
MessagesController.getInstance().deleteDialog(selectedDialog, 0, false);
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showAlertDialog(builder);
}
}
});
@ -333,7 +345,21 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
builder.setItems(new CharSequence[]{LocaleController.getString("ClearHistory", R.string.ClearHistory), LocaleController.getString("Delete", R.string.Delete)}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
MessagesController.getInstance().deleteDialog(selectedDialog, 0, which == 0);
if (which == 0) {
MessagesController.getInstance().deleteDialog(selectedDialog, 0, true);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setMessage(LocaleController.getString("AreYouSureDeleteThisChat", R.string.AreYouSureDeleteThisChat));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
MessagesController.getInstance().deleteDialog(selectedDialog, 0, false);
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showAlertDialog(builder);
}
}
});
}
@ -347,7 +373,7 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
@Override
public void onScrollStateChanged(AbsListView absListView, int i) {
if (i == SCROLL_STATE_TOUCH_SCROLL && searching && searchWas) {
Utilities.hideKeyboard(getParentActivity().getCurrentFocus());
AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus());
}
}
@ -363,11 +389,6 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
}
}
});
if (MessagesController.getInstance().loadingDialogs) {
progressView.setVisibility(View.VISIBLE);
}
} else {
ViewGroup parent = (ViewGroup)fragmentView.getParent();
if (parent != null) {
@ -453,7 +474,7 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
this.delegate = delegate;
}
private void didSelectResult(final long dialog_id, boolean useAlert) {
private void didSelectResult(final long dialog_id, boolean useAlert, final boolean param) {
if (useAlert && selectAlertString != null) {
if (getParentActivity() == null) {
return;
@ -484,17 +505,32 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
}
builder.setMessage(LocaleController.formatStringSimple(selectAlertString, Utilities.formatName(user.first_name, user.last_name)));
}
CheckBox checkBox = null;
/*if (delegate instanceof ChatActivity) {
checkBox = new CheckBox(getParentActivity());
checkBox.setText(LocaleController.getString("ForwardFromMyName", R.string.ForwardFromMyName));
checkBox.setChecked(false);
builder.setView(checkBox);
}*/
final CheckBox checkBoxFinal = checkBox;
builder.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
didSelectResult(dialog_id, false);
didSelectResult(dialog_id, false, checkBoxFinal != null && checkBoxFinal.isChecked());
}
});
builder.setNegativeButton(R.string.Cancel, null);
showAlertDialog(builder);
if (checkBox != null) {
ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams)checkBox.getLayoutParams();
if (layoutParams != null) {
layoutParams.rightMargin = layoutParams.leftMargin = AndroidUtilities.dp(10);
checkBox.setLayoutParams(layoutParams);
}
}
} else {
if (delegate != null) {
delegate.didSelectDialog(MessagesActivity.this, dialog_id);
delegate.didSelectDialog(MessagesActivity.this, dialog_id, param);
delegate = null;
} else {
finishFragment();

View File

@ -27,11 +27,11 @@ import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import org.telegram.android.AndroidUtilities;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.android.LocaleController;
import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;
import org.telegram.ui.Views.ActionBar.BaseFragment;
import java.io.File;
@ -72,7 +72,7 @@ public class PhotoCropActivity extends BaseFragment {
private void init() {
rectPaint = new Paint();
rectPaint.setColor(0xfffafafa);
rectPaint.setStrokeWidth(Utilities.dp(2));
rectPaint.setStrokeWidth(AndroidUtilities.dp(2));
rectPaint.setStyle(Paint.Style.STROKE);
circlePaint = new Paint();
circlePaint.setColor(0x7fffffff);
@ -85,7 +85,7 @@ public class PhotoCropActivity extends BaseFragment {
public boolean onTouch(View view, MotionEvent motionEvent) {
float x = motionEvent.getX();
float y = motionEvent.getY();
int cornerSide = Utilities.dp(14);
int cornerSide = AndroidUtilities.dp(14);
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
if (rectX - cornerSide < x && rectX + cornerSide > x && rectY - cornerSide < y && rectY + cornerSide > y) {
draggingState = 1;
@ -270,7 +270,7 @@ public class PhotoCropActivity extends BaseFragment {
canvas.drawRect(rectX, rectY, rectX + rectSize, rectY + rectSize, rectPaint);
int side = Utilities.dp(7);
int side = AndroidUtilities.dp(7);
canvas.drawRect(rectX - side, rectY - side, rectX + side, rectY + side, circlePaint);
canvas.drawRect(rectX + rectSize - side, rectY - side, rectX + rectSize + side, rectY + side, circlePaint);
canvas.drawRect(rectX - side, rectY + rectSize - side, rectX + side, rectY + rectSize + side, circlePaint);

View File

@ -23,13 +23,13 @@ import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MediaController;
import org.telegram.messenger.MessagesController;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.LocaleController;
import org.telegram.android.MediaController;
import org.telegram.android.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.Utilities;
import org.telegram.objects.MessageObject;
import org.telegram.ui.Adapters.BaseFragmentAdapter;
import org.telegram.ui.Views.ActionBar.ActionBarLayer;
@ -159,6 +159,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen
if (i < 0 || i >= selectedAlbum.photos.size()) {
return;
}
PhotoViewer.getInstance().setParentActivity(getParentActivity());
PhotoViewer.getInstance().openPhotoForSelect(selectedAlbum.photos, i, PhotoPickerActivity.this);
}
}
@ -252,7 +253,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen
imageView.getLocationInWindow(coords);
PhotoViewer.PlaceProviderObject object = new PhotoViewer.PlaceProviderObject();
object.viewX = coords[0];
object.viewY = coords[1] - Utilities.statusBarHeight;
object.viewY = coords[1] - AndroidUtilities.statusBarHeight;
object.parentView = listView;
object.imageReceiver = imageView.imageReceiver;
object.thumb = object.imageReceiver.getBitmap();
@ -405,7 +406,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen
}
}
listView.setNumColumns(columnsCount);
itemWidth = (getParentActivity().getResources().getDisplayMetrics().widthPixels - ((columnsCount + 1) * Utilities.dp(4))) / columnsCount;
itemWidth = (getParentActivity().getResources().getDisplayMetrics().widthPixels - ((columnsCount + 1) * AndroidUtilities.dp(4))) / columnsCount;
listView.setColumnWidth(itemWidth);
listAdapter.notifyDataSetChanged();

View File

@ -45,12 +45,13 @@ import android.widget.ProgressBar;
import android.widget.Scroller;
import android.widget.TextView;
import org.telegram.android.AndroidUtilities;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MediaController;
import org.telegram.messenger.MessagesController;
import org.telegram.android.LocaleController;
import org.telegram.android.MediaController;
import org.telegram.android.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.TLRPC;
@ -102,6 +103,8 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
private boolean overlayViewVisible = true;
private int animationInProgress = 0;
private long transitionAnimationStartTime = 0;
private Runnable animationEndRunnable = null;
private PlaceProviderObject showAfterAnimation;
private PlaceProviderObject hideAfterAnimation;
private boolean disableShowCheck = false;
@ -175,7 +178,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
private final static int gallery_menu_showall = 2;
private final static int gallery_menu_send = 3;
private final static int PAGE_SPACING = Utilities.dp(30);
private final static int PAGE_SPACING = AndroidUtilities.dp(30);
private static class OverlayView extends FrameLayout {
@ -186,7 +189,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
actionButton = new TextView(context);
actionButton.setBackgroundResource(R.drawable.system_black);
actionButton.setPadding(Utilities.dp(8), Utilities.dp(2), Utilities.dp(8), Utilities.dp(2));
actionButton.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(2), AndroidUtilities.dp(8), AndroidUtilities.dp(2));
actionButton.setTextColor(0xffffffff);
actionButton.setTextSize(26);
actionButton.setGravity(Gravity.CENTER);
@ -298,7 +301,17 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
if (currentFileName != null && currentFileName.equals(location)) {
Float progress = (Float)args[1];
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress((int)(progress * 100));
if (android.os.Build.VERSION.SDK_INT >= 11) {
progressBar.setProgress((int) (progress * 100));
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(
ObjectAnimator.ofInt(progressBar, "progress", (int) (progress * 100))
);
animatorSet.setDuration(400);
animatorSet.start();
} else {
progressBar.setProgress((int) (progress * 100));
}
}
} else if (id == MessagesController.userPhotosLoaded) {
int guid = (Integer)args[4];
@ -432,6 +445,9 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
}
public void setParentActivity(Activity activity) {
if (parentActivity == activity) {
return;
}
parentActivity = activity;
scroller = new Scroller(activity);
@ -530,7 +546,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
@Override
public boolean canOpenMenu() {
if (currentFileName != null) {
File f = new File(Utilities.getCacheDir(), currentFileName);
File f = new File(AndroidUtilities.getCacheDir(), currentFileName);
if (f.exists()) {
return true;
}
@ -548,7 +564,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
containerView.addView(bottomLayout);
layoutParams = (FrameLayout.LayoutParams)bottomLayout.getLayoutParams();
layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams.height = Utilities.dp(48);
layoutParams.height = AndroidUtilities.dp(48);
layoutParams.gravity = Gravity.BOTTOM | Gravity.LEFT;
bottomLayout.setLayoutParams(layoutParams);
bottomLayout.setBackgroundColor(0x7F000000);
@ -559,7 +575,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
shareButton.setBackgroundResource(R.drawable.bar_selector_white);
bottomLayout.addView(shareButton);
layoutParams = (FrameLayout.LayoutParams) shareButton.getLayoutParams();
layoutParams.width = Utilities.dp(50);
layoutParams.width = AndroidUtilities.dp(50);
layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT;
shareButton.setLayoutParams(layoutParams);
shareButton.setOnClickListener(new View.OnClickListener() {
@ -573,7 +589,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
if (fileName == null) {
return;
}
File f = new File(Utilities.getCacheDir(), fileName);
File f = new File(AndroidUtilities.getCacheDir(), fileName);
if (f.exists()) {
Intent intent = new Intent(Intent.ACTION_SEND);
if (fileName.endsWith("mp4")) {
@ -596,7 +612,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
deleteButton.setBackgroundResource(R.drawable.bar_selector_white);
bottomLayout.addView(deleteButton);
layoutParams = (FrameLayout.LayoutParams) deleteButton.getLayoutParams();
layoutParams.width = Utilities.dp(50);
layoutParams.width = AndroidUtilities.dp(50);
layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams.gravity = Gravity.RIGHT;
deleteButton.setLayoutParams(layoutParams);
@ -628,9 +644,9 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT;
layoutParams.gravity = Gravity.TOP;
layoutParams.leftMargin = Utilities.dp(60);
layoutParams.rightMargin = Utilities.dp(60);
layoutParams.topMargin = Utilities.dp(2);
layoutParams.leftMargin = AndroidUtilities.dp(60);
layoutParams.rightMargin = AndroidUtilities.dp(60);
layoutParams.topMargin = AndroidUtilities.dp(2);
nameTextView.setLayoutParams(layoutParams);
dateTextView = new TextView(containerView.getContext());
@ -645,9 +661,9 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT;
layoutParams.gravity = Gravity.TOP;
layoutParams.leftMargin = Utilities.dp(60);
layoutParams.rightMargin = Utilities.dp(60);
layoutParams.topMargin = Utilities.dp(26);
layoutParams.leftMargin = AndroidUtilities.dp(60);
layoutParams.rightMargin = AndroidUtilities.dp(60);
layoutParams.topMargin = AndroidUtilities.dp(26);
dateTextView.setLayoutParams(layoutParams);
pickerView = parentActivity.getLayoutInflater().inflate(R.layout.photo_picker_bottom_layout, null);
@ -675,7 +691,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
layoutParams = (FrameLayout.LayoutParams)pickerView.getLayoutParams();
layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams.height = Utilities.dp(48);
layoutParams.height = AndroidUtilities.dp(48);
layoutParams.gravity = Gravity.BOTTOM;
pickerView.setLayoutParams(layoutParams);
@ -691,11 +707,11 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
containerView.addView(progressBar);
layoutParams = (FrameLayout.LayoutParams)progressBar.getLayoutParams();
layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams.height = Utilities.dp(3);
layoutParams.height = AndroidUtilities.dp(3);
layoutParams.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
layoutParams.leftMargin = Utilities.dp(6);
layoutParams.rightMargin = Utilities.dp(6);
layoutParams.bottomMargin = Utilities.dp(48);
layoutParams.leftMargin = AndroidUtilities.dp(6);
layoutParams.rightMargin = AndroidUtilities.dp(6);
layoutParams.bottomMargin = AndroidUtilities.dp(48);
progressBar.setLayoutParams(layoutParams);
gestureDetector = new GestureDetector(containerView.getContext(), this);
@ -715,16 +731,16 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
checkImageView.setScaleType(ImageView.ScaleType.CENTER);
checkImageView.setImageResource(R.drawable.selectphoto_large);
layoutParams = (FrameLayout.LayoutParams)checkImageView.getLayoutParams();
layoutParams.width = Utilities.dp(46);
layoutParams.height = Utilities.dp(46);
layoutParams.width = AndroidUtilities.dp(46);
layoutParams.height = AndroidUtilities.dp(46);
layoutParams.gravity = Gravity.RIGHT;
layoutParams.rightMargin = Utilities.dp(10);
layoutParams.rightMargin = AndroidUtilities.dp(10);
WindowManager manager = (WindowManager)ApplicationLoader.applicationContext.getSystemService(Activity.WINDOW_SERVICE);
int rotation = manager.getDefaultDisplay().getRotation();
if (rotation == Surface.ROTATION_270 || rotation == Surface.ROTATION_90) {
layoutParams.topMargin = Utilities.dp(48);
layoutParams.topMargin = AndroidUtilities.dp(48);
} else {
layoutParams.topMargin = Utilities.dp(58);
layoutParams.topMargin = AndroidUtilities.dp(58);
}
checkImageView.setLayoutParams(layoutParams);
checkImageView.setOnClickListener(new View.OnClickListener() {
@ -988,7 +1004,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
load = true;
}
} else {
File cacheFile = new File(Utilities.getCacheDir(), currentFileName);
File cacheFile = new File(AndroidUtilities.getCacheDir(), currentFileName);
if (cacheFile.exists()) {
currentOverlay.actionButton.setText(LocaleController.getString("ViewVideo", R.string.ViewVideo));
} else {
@ -996,10 +1012,13 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
}
}
if (load) {
Float progress = FileLoader.getInstance().fileProgresses.get(currentFileName);
if (FileLoader.getInstance().isLoadingFile(currentFileName)) {
Float progress = FileLoader.getInstance().fileProgresses.get(currentFileName);
currentOverlay.actionButton.setText(LocaleController.getString("CancelDownload", R.string.CancelDownload));
progressBar.setVisibility(View.VISIBLE);
if (progress != null) {
progressBar.setProgress((int)(progress * 100));
}
} else {
currentOverlay.actionButton.setText(String.format("%s %s", LocaleController.getString("DOWNLOAD", R.string.DOWNLOAD), Utilities.formatFileSize(currentMessageObject.messageOwner.media.video.size)));
progressBar.setVisibility(View.GONE);
@ -1226,7 +1245,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
}
if (currentFileName != null) {
File f = new File(Utilities.getCacheDir(), currentFileName);
File f = new File(AndroidUtilities.getCacheDir(), currentFileName);
if (f.exists()) {
progressBar.setVisibility(View.GONE);
} else {
@ -1260,7 +1279,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
if (currentThumb != null && imageReceiver == centerImage) {
placeHolder = currentThumb;
}
int size = (int)(800 / Utilities.density);
int size = (int)(800 / AndroidUtilities.density);
imageReceiver.setImage(photoEntry.path, String.format(Locale.US, "%d_%d", size, size), placeHolder != null ? new BitmapDrawable(null, placeHolder) : null);
} else {
imageReceiver.setImageBitmap((Bitmap) null);
@ -1335,8 +1354,21 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
openPhoto(null, null, null, photos, index, provider);
}
private boolean checkAnimation() {
if (animationInProgress != 0) {
if (Math.abs(transitionAnimationStartTime - System.currentTimeMillis()) >= 500) {
if (animationEndRunnable != null) {
animationEndRunnable.run();
animationEndRunnable = null;
}
animationInProgress = 0;
}
}
return animationInProgress != 0;
}
public void openPhoto(final MessageObject messageObject, final TLRPC.FileLocation fileLocation, final ArrayList<MessageObject> messages, final ArrayList<MediaController.PhotoEntry> photos, final int index, final PhotoViewerProvider provider) {
if (parentActivity == null || isVisible || provider == null || animationInProgress != 0 || messageObject == null && fileLocation == null && messages == null && photos == null) {
if (parentActivity == null || isVisible || provider == null || checkAnimation() || messageObject == null && fileLocation == null && messages == null && photos == null) {
return;
}
final PlaceProviderObject object = provider.getPlaceForPhoto(messageObject, fileLocation, index);
@ -1369,7 +1401,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
overlayViewVisible = true;
if(android.os.Build.VERSION.SDK_INT >= 11) {
Utilities.lockOrientation(parentActivity);
AndroidUtilities.lockOrientation(parentActivity);
animatingImageView.setVisibility(View.VISIBLE);
animatingImageView.setImageBitmap(object.thumb);
@ -1391,23 +1423,23 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
public boolean onPreDraw() {
containerView.getViewTreeObserver().removeOnPreDrawListener(this);
float scaleX = (float) Utilities.displaySize.x / layoutParams.width;
float scaleY = (float) (Utilities.displaySize.y - Utilities.statusBarHeight) / layoutParams.height;
float scaleX = (float) AndroidUtilities.displaySize.x / layoutParams.width;
float scaleY = (float) (AndroidUtilities.displaySize.y - AndroidUtilities.statusBarHeight) / layoutParams.height;
float scale = scaleX > scaleY ? scaleY : scaleX;
float width = layoutParams.width * scale;
float height = layoutParams.height * scale;
float xPos = (Utilities.displaySize.x - width) / 2.0f;
float yPos = (Utilities.displaySize.y - Utilities.statusBarHeight - height) / 2.0f;
float xPos = (AndroidUtilities.displaySize.x - width) / 2.0f;
float yPos = (AndroidUtilities.displaySize.y - AndroidUtilities.statusBarHeight - height) / 2.0f;
int clipHorizontal = Math.abs(object.imageReceiver.drawRegion.left - object.imageReceiver.imageX);
int clipVertical = Math.abs(object.imageReceiver.drawRegion.top - object.imageReceiver.imageY);
int coords2[] = new int[2];
object.parentView.getLocationInWindow(coords2);
int clipTop = coords2[1] - Utilities.statusBarHeight - (object.viewY + object.imageReceiver.drawRegion.top);
int clipTop = coords2[1] - AndroidUtilities.statusBarHeight - (object.viewY + object.imageReceiver.drawRegion.top);
if (clipTop < 0) {
clipTop = 0;
}
int clipBottom = (object.viewY + object.imageReceiver.drawRegion.top + layoutParams.height) - (coords2[1] + object.parentView.getHeight() - Utilities.statusBarHeight);
int clipBottom = (object.viewY + object.imageReceiver.drawRegion.top + layoutParams.height) - (coords2[1] + object.parentView.getHeight() - AndroidUtilities.statusBarHeight);
if (clipBottom < 0) {
clipBottom = 0;
}
@ -1428,14 +1460,14 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
ObjectAnimator.ofFloat(currentOverlay, "alpha", 1.0f)
);
animatorSet.setDuration(250);
animatorSet.addListener(new AnimatorListenerAdapter() {
animationEndRunnable = new Runnable() {
@Override
public void onAnimationEnd(Animator animation) {
public void run() {
animationInProgress = 0;
transitionAnimationStartTime = 0;
containerView.invalidate();
animatingImageView.setVisibility(View.GONE);
Utilities.unlockOrientation(parentActivity);
AndroidUtilities.unlockOrientation(parentActivity);
if (showAfterAnimation != null) {
showAfterAnimation.imageReceiver.setVisible(true, true);
}
@ -1443,7 +1475,24 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
hideAfterAnimation.imageReceiver.setVisible(false, true);
}
}
};
animatorSet.setDuration(250);
animatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (animationEndRunnable != null) {
animationEndRunnable.run();
animationEndRunnable = null;
}
}
@Override
public void onAnimationCancel(Animator animation) {
onAnimationEnd(animation);
}
});
transitionAnimationStartTime = System.currentTimeMillis();
animatorSet.start();
animatingImageView.setOnDrawListener(new ClippingImageView.onDrawListener() {
@ -1461,6 +1510,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
});
} else {
animationInProgress = 0;
transitionAnimationStartTime = 0;
containerView.invalidate();
AnimationSet animationSet = new AnimationSet(true);
AlphaAnimation animation = new AlphaAnimation(0.0f, 1.0f);
@ -1478,7 +1528,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
}
public void closePhoto(boolean animated) {
if (parentActivity == null || !isVisible || animationInProgress != 0) {
if (parentActivity == null || !isVisible || checkAnimation()) {
return;
}
@ -1502,7 +1552,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
final PlaceProviderObject object = placeProvider.getPlaceForPhoto(currentMessageObject, currentFileLocation, currentIndex);
if(android.os.Build.VERSION.SDK_INT >= 11 && animated) {
Utilities.lockOrientation(parentActivity);
AndroidUtilities.lockOrientation(parentActivity);
animationInProgress = 1;
animatingImageView.setVisibility(View.VISIBLE);
@ -1522,13 +1572,13 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
}
animatingImageView.setLayoutParams(layoutParams);
float scaleX = (float) Utilities.displaySize.x / layoutParams.width;
float scaleY = (float) (Utilities.displaySize.y - Utilities.statusBarHeight) / layoutParams.height;
float scaleX = (float) AndroidUtilities.displaySize.x / layoutParams.width;
float scaleY = (float) (AndroidUtilities.displaySize.y - AndroidUtilities.statusBarHeight) / layoutParams.height;
float scale2 = scaleX > scaleY ? scaleY : scaleX;
float width = layoutParams.width * scale * scale2;
float height = layoutParams.height * scale * scale2;
float xPos = (Utilities.displaySize.x - width) / 2.0f;
float yPos = (Utilities.displaySize.y - Utilities.statusBarHeight - height) / 2.0f;
float xPos = (AndroidUtilities.displaySize.x - width) / 2.0f;
float yPos = (AndroidUtilities.displaySize.y - AndroidUtilities.statusBarHeight - height) / 2.0f;
animatingImageView.setTranslationX(xPos + translationX);
animatingImageView.setTranslationY(yPos + translationY);
animatingImageView.setScaleX(scale * scale2);
@ -1543,11 +1593,11 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
int coords2[] = new int[2];
object.parentView.getLocationInWindow(coords2);
int clipTop = coords2[1] - Utilities.statusBarHeight - (object.viewY + object.imageReceiver.drawRegion.top);
int clipTop = coords2[1] - AndroidUtilities.statusBarHeight - (object.viewY + object.imageReceiver.drawRegion.top);
if (clipTop < 0) {
clipTop = 0;
}
int clipBottom = (object.viewY + object.imageReceiver.drawRegion.top + (object.imageReceiver.drawRegion.bottom - object.imageReceiver.drawRegion.top)) - (coords2[1] + object.parentView.getHeight() - Utilities.statusBarHeight);
int clipBottom = (object.viewY + object.imageReceiver.drawRegion.top + (object.imageReceiver.drawRegion.bottom - object.imageReceiver.drawRegion.top)) - (coords2[1] + object.parentView.getHeight() - AndroidUtilities.statusBarHeight);
if (clipBottom < 0) {
clipBottom = 0;
}
@ -1570,20 +1620,36 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
animatorSet.playTogether(
ObjectAnimator.ofInt(backgroundDrawable, "alpha", 0),
ObjectAnimator.ofFloat(animatingImageView, "alpha", 0.0f),
ObjectAnimator.ofFloat(animatingImageView, "translationY", translationY >= 0 ? Utilities.displaySize.y : -Utilities.displaySize.y),
ObjectAnimator.ofFloat(animatingImageView, "translationY", translationY >= 0 ? AndroidUtilities.displaySize.y : -AndroidUtilities.displaySize.y),
ObjectAnimator.ofFloat(containerView, "alpha", 0.0f)
);
}
animationEndRunnable = new Runnable() {
@Override
public void run() {
AndroidUtilities.unlockOrientation(parentActivity);
animationInProgress = 0;
onPhotoClosed(object);
}
};
animatorSet.setDuration(250);
animatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
Utilities.unlockOrientation(parentActivity);
animationInProgress = 0;
onPhotoClosed(object);
if (animationEndRunnable != null) {
animationEndRunnable.run();
animationEndRunnable = null;
}
}
@Override
public void onAnimationCancel(Animator animation) {
onAnimationEnd(animation);
}
});
transitionAnimationStartTime = System.currentTimeMillis();
animatorSet.start();
} else {
AnimationSet animationSet = new AnimationSet(true);
@ -1597,6 +1663,16 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
animationSet.addAnimation(scaleAnimation);
animationSet.setDuration(150);
animationInProgress = 2;
animationEndRunnable = new Runnable() {
@Override
public void run() {
if (animationListener != null) {
animationInProgress = 0;
onPhotoClosed(object);
animationListener = null;
}
}
};
animationSet.setAnimationListener(animationListener = new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
@ -1605,10 +1681,9 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
@Override
public void onAnimationEnd(Animation animation) {
if (animationListener != null) {
animationInProgress = 0;
onPhotoClosed(object);
animationListener = null;
if (animationEndRunnable != null) {
animationEndRunnable.run();
animationEndRunnable = null;
}
}
@ -1617,10 +1692,27 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
}
});
transitionAnimationStartTime = System.currentTimeMillis();
containerView.startAnimation(animationSet);
}
}
public void destroyPhotoViewer() {
if (parentActivity == null || windowView == null) {
return;
}
try {
WindowManager wm = (WindowManager) parentActivity.getSystemService(Context.WINDOW_SERVICE);
if (windowView.getParent() != null) {
wm.removeViewImmediate(windowView);
}
windowView = null;
} catch (Exception e) {
FileLog.e("tmessages", e);
}
Instance = null;
}
private void onPhotoClosed(PlaceProviderObject object) {
disableShowCheck = true;
currentMessageObject = null;
@ -1678,7 +1770,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
private boolean onTouchEvent(MotionEvent ev) {
if (animationInProgress != 0 || animationStartTime != 0) {
if (animationStartTime == 0) {
Utilities.unlockOrientation(parentActivity);
AndroidUtilities.unlockOrientation(parentActivity);
}
return false;
}
@ -1713,7 +1805,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
dragY = moveStartY = ev.getY();
draggingDown = false;
canDragDown = true;
Utilities.lockOrientation(parentActivity);
AndroidUtilities.lockOrientation(parentActivity);
if (velocityTracker != null) {
velocityTracker.clear();
}
@ -1732,7 +1824,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
}
float dx = Math.abs(ev.getX() - moveStartX);
float dy = Math.abs(ev.getY() - dragY);
if (canDragDown && !draggingDown && scale == 1 && dy >= Utilities.dp(30) && dy / 2 > dx) {
if (canDragDown && !draggingDown && scale == 1 && dy >= AndroidUtilities.dp(30) && dy / 2 > dx) {
draggingDown = true;
moving = false;
dragY = ev.getY();
@ -1747,7 +1839,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
} else if (!invalidCoords && animationStartTime == 0) {
float moveDx = moveStartX - ev.getX();
float moveDy = moveStartY - ev.getY();
if (moving || scale == 1 && Math.abs(moveDy) + Utilities.dp(12) < Math.abs(moveDx) || scale != 1) {
if (moving || scale == 1 && Math.abs(moveDy) + AndroidUtilities.dp(12) < Math.abs(moveDx) || scale != 1) {
if (!moving) {
moveDx = 0;
moveDy = 0;
@ -1834,11 +1926,11 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
velocity = velocityTracker.getXVelocity();
}
if((translationX < minX - containerView.getWidth() / 3 || velocity < -Utilities.dp(650)) && rightImage.hasImage()){
if((translationX < minX - containerView.getWidth() / 3 || velocity < -AndroidUtilities.dp(650)) && rightImage.hasImage()){
goToNext();
return true;
}
if((translationX > maxX + containerView.getWidth() / 3 || velocity > Utilities.dp(650)) && leftImage.hasImage()){
if((translationX > maxX + containerView.getWidth() / 3 || velocity > AndroidUtilities.dp(650)) && leftImage.hasImage()){
goToPrev();
return true;
}
@ -1855,7 +1947,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
}
animateTo(scale, moveToX, moveToY);
} else {
Utilities.unlockOrientation(parentActivity);
AndroidUtilities.unlockOrientation(parentActivity);
}
}
return false;
@ -1905,7 +1997,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
toggleOverlayView(true);
}
if (scale == newScale && translationX == newTx && translationY == newTy) {
Utilities.unlockOrientation(parentActivity);
AndroidUtilities.unlockOrientation(parentActivity);
return;
}
zoomAnimation = isZoom;
@ -1915,7 +2007,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
animationStartTime = System.currentTimeMillis();
animationDuration = 250;
containerView.postInvalidate();
Utilities.lockOrientation(parentActivity);
AndroidUtilities.lockOrientation(parentActivity);
}
private void onDraw(Canvas canvas) {
@ -1962,7 +2054,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
scale = animateToScale;
animationStartTime = 0;
updateMinMax(scale);
Utilities.unlockOrientation(parentActivity);
AndroidUtilities.unlockOrientation(parentActivity);
zoomAnimation = false;
}
if (!scroller.isFinished()) {
@ -2023,10 +2115,10 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
if (scale >= 1.0f) {
ImageReceiver sideImage = null;
float k = 1;
if (currentTranslationX > maxX + Utilities.dp(20)) {
if (currentTranslationX > maxX + AndroidUtilities.dp(20)) {
k = -1;
sideImage = leftImage;
} else if (currentTranslationX < minX - Utilities.dp(20)) {
} else if (currentTranslationX < minX - AndroidUtilities.dp(20)) {
sideImage = rightImage;
}
@ -2078,9 +2170,9 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
WindowManager manager = (WindowManager)ApplicationLoader.applicationContext.getSystemService(Activity.WINDOW_SERVICE);
int rotation = manager.getDefaultDisplay().getRotation();
if (rotation == Surface.ROTATION_270 || rotation == Surface.ROTATION_90) {
layoutParams.topMargin = Utilities.dp(48);
layoutParams.topMargin = AndroidUtilities.dp(48);
} else {
layoutParams.topMargin = Utilities.dp(58);
layoutParams.topMargin = AndroidUtilities.dp(58);
}
checkImageView.setLayoutParams(layoutParams);
return false;
@ -2105,7 +2197,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
loadFile = true;
}
} else {
File cacheFile = new File(Utilities.getCacheDir(), currentFileName);
File cacheFile = new File(AndroidUtilities.getCacheDir(), currentFileName);
if (cacheFile.exists()) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(cacheFile), "video/mp4");

View File

@ -0,0 +1,977 @@
/*
* This is the source code of Telegram for Android v. 1.4.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2014.
*/
package org.telegram.ui;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.ContactsController;
import org.telegram.android.LocaleController;
import org.telegram.android.MediaController;
import org.telegram.android.MessagesController;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.android.NotificationsController;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.Utilities;
import org.telegram.objects.MessageObject;
import org.telegram.objects.PhotoObject;
import org.telegram.ui.Views.ActionBar.ActionBar;
import org.telegram.ui.Views.ActionBar.ActionBarLayer;
import org.telegram.ui.Views.ActionBar.ActionBarMenu;
import org.telegram.ui.Views.BackupImageView;
import org.telegram.ui.Views.ChatActivityEnterView;
import org.telegram.ui.Views.FrameLayoutFixed;
import org.telegram.ui.Views.PopupAudioView;
import java.io.File;
import java.util.ArrayList;
public class PopupNotificationActivity extends Activity implements NotificationCenter.NotificationCenterDelegate {
private ActionBarLayer actionBarLayer;
private ChatActivityEnterView chatActivityEnterView;
private BackupImageView avatarImageView;
private TextView countText;
private ViewGroup messageContainer;
private ViewGroup centerView;
private ViewGroup leftView;
private ViewGroup rightView;
private ArrayList<ViewGroup> textViews = new ArrayList<ViewGroup>();
private ArrayList<ViewGroup> imageViews = new ArrayList<ViewGroup>();
private ArrayList<ViewGroup> audioViews = new ArrayList<ViewGroup>();
private VelocityTracker velocityTracker = null;
private int classGuid;
private TLRPC.User currentUser;
private TLRPC.Chat currentChat;
private boolean finished = false;
private CharSequence lastPrintString;
private MessageObject currentMessageObject = null;
private int currentMessageNum = 0;
private PowerManager.WakeLock wakeLock = null;
private int downloadAudios = 0;
private int downloadPhotos = 0;
private boolean animationInProgress = false;
private long animationStartTime = 0;
private float moveStartX = -1;
private boolean startedMoving = false;
private Runnable onAnimationEndRunnable = null;
private class FrameLayoutTouch extends FrameLayoutFixed {
public FrameLayoutTouch(Context context) {
super(context);
}
public FrameLayoutTouch(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FrameLayoutTouch(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return checkTransitionAnimation() || ((PopupNotificationActivity) getContext()).onTouchEventMy(ev);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
return checkTransitionAnimation() || ((PopupNotificationActivity) getContext()).onTouchEventMy(ev);
}
@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
((PopupNotificationActivity)getContext()).onTouchEventMy(null);
super.requestDisallowInterceptTouchEvent(disallowIntercept);
}
}
public class FrameLayoutAnimationListener extends FrameLayoutFixed {
public FrameLayoutAnimationListener(Context context) {
super(context);
}
public FrameLayoutAnimationListener(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FrameLayoutAnimationListener(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onAnimationEnd() {
super.onAnimationEnd();
if (onAnimationEndRunnable != null) {
onAnimationEndRunnable.run();
onAnimationEndRunnable = null;
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
classGuid = ConnectionsManager.getInstance().generateClassGuid();
NotificationCenter.getInstance().addObserver(this, 1234);
NotificationCenter.getInstance().addObserver(this, NotificationsController.pushMessagesUpdated);
NotificationCenter.getInstance().addObserver(this, MessagesController.updateInterfaces);
NotificationCenter.getInstance().addObserver(this, MediaController.audioProgressDidChanged);
NotificationCenter.getInstance().addObserver(this, MediaController.audioDidReset);
NotificationCenter.getInstance().addObserver(this, MessagesController.contactsDidLoaded);
NotificationCenter.getInstance().addObserver(this, 999);
chatActivityEnterView = new ChatActivityEnterView();
chatActivityEnterView.setDelegate(new ChatActivityEnterView.ChatActivityEnterViewDelegate() {
@Override
public void onMessageSend() {
if (currentMessageObject == null) {
return;
}
NotificationsController.getInstance().popupMessages.remove(currentMessageNum);
MessagesController.getInstance().markDialogAsRead(currentMessageObject.getDialogId(), currentMessageObject.messageOwner.id, Math.max(0, currentMessageObject.messageOwner.id), 0, currentMessageObject.messageOwner.date, true);
currentMessageObject = null;
getNewMessage();
}
@Override
public void needSendTyping() {
if (currentMessageObject != null) {
MessagesController.getInstance().sendTyping(currentMessageObject.getDialogId(), classGuid);
}
}
});
setContentView(R.layout.popup_notification_layout);
RelativeLayout popupContainer = (RelativeLayout) findViewById(R.id.popup_container);
messageContainer = new FrameLayoutTouch(this);
popupContainer.addView(messageContainer, 0);
ActionBar actionBar = new ActionBar(this);
popupContainer.addView(actionBar);
ViewGroup.LayoutParams layoutParams = actionBar.getLayoutParams();
layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
actionBar.setLayoutParams(layoutParams);
actionBarLayer = actionBar.createLayer();
actionBarLayer.setDisplayHomeAsUpEnabled(true, R.drawable.ic_ab_back);
actionBarLayer.setBackgroundResource(R.color.header);
actionBarLayer.setItemsBackground(R.drawable.bar_selector);
actionBar.setCurrentActionBarLayer(actionBarLayer);
ActionBarMenu menu = actionBarLayer.createMenu();
View view = menu.addItemResource(2, R.layout.popup_count_layout);
countText = (TextView) view.findViewById(R.id.count_text);
view = menu.addItemResource(1, R.layout.chat_header_layout);
avatarImageView = (BackupImageView)view.findViewById(R.id.chat_avatar_image);
avatarImageView.processDetach = false;
actionBarLayer.setActionBarMenuOnItemClick(new ActionBarLayer.ActionBarMenuOnItemClick() {
@Override
public void onItemClick(int id) {
if (id == -1) {
onFinish();
finish();
} else if (id == 1) {
openCurrentMessage();
} else if (id == 2) {
switchToNextMessage();
}
}
});
chatActivityEnterView.setContainerView(this, findViewById(R.id.chat_layout));
PowerManager pm = (PowerManager)ApplicationLoader.applicationContext.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "screen");
wakeLock.setReferenceCounted(false);
handleIntent(getIntent());
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
AndroidUtilities.checkDisplaySize();
fixLayout();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleIntent(intent);
}
private void switchToNextMessage() {
if (NotificationsController.getInstance().popupMessages.size() > 1) {
if (currentMessageNum < NotificationsController.getInstance().popupMessages.size() - 1) {
currentMessageNum++;
} else {
currentMessageNum = 0;
}
currentMessageObject = NotificationsController.getInstance().popupMessages.get(currentMessageNum);
updateInterfaceForCurrentMessage(2);
countText.setText(String.format("%d/%d", currentMessageNum + 1, NotificationsController.getInstance().popupMessages.size()));
}
}
private void switchToPreviousMessage() {
if (NotificationsController.getInstance().popupMessages.size() > 1) {
if (currentMessageNum > 0) {
currentMessageNum--;
} else {
currentMessageNum = NotificationsController.getInstance().popupMessages.size() - 1;
}
currentMessageObject = NotificationsController.getInstance().popupMessages.get(currentMessageNum);
updateInterfaceForCurrentMessage(1);
countText.setText(String.format("%d/%d", currentMessageNum + 1, NotificationsController.getInstance().popupMessages.size()));
}
}
public boolean checkTransitionAnimation() {
if (animationInProgress && animationStartTime < System.currentTimeMillis() - 400) {
animationInProgress = false;
if (onAnimationEndRunnable != null) {
onAnimationEndRunnable.run();
onAnimationEndRunnable = null;
}
}
return animationInProgress;
}
public boolean onTouchEventMy(MotionEvent motionEvent) {
if (checkTransitionAnimation()) {
return false;
}
if (motionEvent != null && motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
moveStartX = motionEvent.getX();
} else if (motionEvent != null && motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
float x = motionEvent.getX();
int diff = (int)(x - moveStartX);
if (moveStartX != -1 && !startedMoving) {
if (Math.abs(diff) > AndroidUtilities.dp(10)) {
startedMoving = true;
moveStartX = x;
AndroidUtilities.lockOrientation(this);
diff = 0;
if (velocityTracker == null) {
velocityTracker = VelocityTracker.obtain();
} else {
velocityTracker.clear();
}
}
}
if (startedMoving) {
if (leftView == null && diff > 0) {
diff = 0;
}
if (rightView == null && diff < 0) {
diff = 0;
}
if (velocityTracker != null) {
velocityTracker.addMovement(motionEvent);
}
applyViewsLayoutParams(diff);
}
} else if (motionEvent == null || motionEvent.getAction() == MotionEvent.ACTION_UP || motionEvent.getAction() == MotionEvent.ACTION_CANCEL) {
if (motionEvent != null && startedMoving) {
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) centerView.getLayoutParams();
int diff = (int)(motionEvent.getX() - moveStartX);
int width = AndroidUtilities.displaySize.x - AndroidUtilities.dp(24);
int moveDiff = 0;
int forceMove = 0;
View otherView = null;
if (velocityTracker != null) {
velocityTracker.computeCurrentVelocity(1000);
if (velocityTracker.getXVelocity() >= 3500) {
forceMove = 1;
} else if (velocityTracker.getXVelocity() <= -3500) {
forceMove = 2;
}
}
if ((forceMove == 1 || diff > width / 3) && leftView != null) {
moveDiff = width - layoutParams.leftMargin;
otherView = leftView;
onAnimationEndRunnable = new Runnable() {
@Override
public void run() {
animationInProgress = false;
switchToPreviousMessage();
AndroidUtilities.unlockOrientation(PopupNotificationActivity.this);
}
};
} else if ((forceMove == 2 || diff < -width / 3) && rightView != null) {
moveDiff = -width - layoutParams.leftMargin;
otherView = rightView;
onAnimationEndRunnable = new Runnable() {
@Override
public void run() {
animationInProgress = false;
switchToNextMessage();
AndroidUtilities.unlockOrientation(PopupNotificationActivity.this);
}
};
} else if (layoutParams.leftMargin != 0) {
moveDiff = -layoutParams.leftMargin;
otherView = diff > 0 ? leftView : rightView;
onAnimationEndRunnable = new Runnable() {
@Override
public void run() {
animationInProgress = false;
applyViewsLayoutParams(0);
AndroidUtilities.unlockOrientation(PopupNotificationActivity.this);
}
};
}
if (moveDiff != 0) {
int time = (int)(Math.abs((float)moveDiff / (float)width) * 200);
TranslateAnimation animation = new TranslateAnimation(0, moveDiff, 0, 0);
animation.setDuration(time);
centerView.startAnimation(animation);
if (otherView != null) {
animation = new TranslateAnimation(0, moveDiff, 0, 0);
animation.setDuration(time);
otherView.startAnimation(animation);
}
animationInProgress = true;
animationStartTime = System.currentTimeMillis();
}
} else {
applyViewsLayoutParams(0);
}
if (velocityTracker != null) {
velocityTracker.recycle();
velocityTracker = null;
}
startedMoving = false;
moveStartX = -1;
}
return startedMoving;
}
private void applyViewsLayoutParams(int xOffset) {
FrameLayout.LayoutParams layoutParams = null;
int widht = AndroidUtilities.displaySize.x - AndroidUtilities.dp(24);
if (leftView != null) {
layoutParams = (FrameLayout.LayoutParams) leftView.getLayoutParams();
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
layoutParams.width = widht;
layoutParams.leftMargin = -widht + xOffset;
leftView.setLayoutParams(layoutParams);
}
if (centerView != null) {
layoutParams = (FrameLayout.LayoutParams) centerView.getLayoutParams();
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
layoutParams.width = widht;
layoutParams.leftMargin = xOffset;
centerView.setLayoutParams(layoutParams);
}
if (rightView != null) {
layoutParams = (FrameLayout.LayoutParams) rightView.getLayoutParams();
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
layoutParams.width = widht;
layoutParams.leftMargin = widht + xOffset;
rightView.setLayoutParams(layoutParams);
}
messageContainer.invalidate();
}
private ViewGroup getViewForMessage(int num, boolean applyOffset) {
if (NotificationsController.getInstance().popupMessages.size() == 1 && (num < 0 || num >= NotificationsController.getInstance().popupMessages.size())) {
return null;
}
if (num == -1) {
num = NotificationsController.getInstance().popupMessages.size() - 1;
} else if (num == NotificationsController.getInstance().popupMessages.size()) {
num = 0;
}
ViewGroup view = null;
MessageObject messageObject = NotificationsController.getInstance().popupMessages.get(num);
if (messageObject.type == 1) {
if (imageViews.size() > 0) {
view = imageViews.get(0);
imageViews.remove(0);
} else {
view = new FrameLayoutAnimationListener(this);
view.addView(getLayoutInflater().inflate(R.layout.popup_image_layout, null));
view.setTag(2);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openCurrentMessage();
}
});
}
TextView messageText = (TextView)view.findViewById(R.id.message_text);
BackupImageView imageView = (BackupImageView) view.findViewById(R.id.message_image);
imageView.imageReceiver.isAspectFit = true;
PhotoObject currentPhotoObject = PhotoObject.getClosestImageWithSize(messageObject.photoThumbs, 800, 800);
boolean photoSet = false;
if (currentPhotoObject != null) {
boolean photoExist = true;
String fileName = MessageObject.getAttachFileName(currentPhotoObject.photoOwner);
if (messageObject.type == 1) {
File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName);
if (!cacheFile.exists()) {
photoExist = false;
}
}
if (photoExist || downloadPhotos == 0 || downloadPhotos == 2 && ConnectionsManager.isConnectedToWiFi()) {
imageView.setImage(currentPhotoObject.photoOwner.location, "100_100", messageObject.imagePreview, currentPhotoObject.photoOwner.size);
photoSet = true;
} else {
if (messageObject.imagePreview != null) {
imageView.setImageBitmap(messageObject.imagePreview);
photoSet = true;
}
}
}
if (!photoSet) {
imageView.setVisibility(View.GONE);
messageText.setVisibility(View.VISIBLE);
messageText.setTextSize(TypedValue.COMPLEX_UNIT_SP, MessagesController.getInstance().fontSize);
messageText.setText(messageObject.messageText);
} else {
imageView.setVisibility(View.VISIBLE);
messageText.setVisibility(View.GONE);
}
} else if (messageObject.type == 2) {
PopupAudioView cell = null;
if (audioViews.size() > 0) {
view = audioViews.get(0);
audioViews.remove(0);
cell = (PopupAudioView)view.findViewWithTag(300);
} else {
view = new FrameLayoutAnimationListener(this);
view.addView(getLayoutInflater().inflate(R.layout.popup_audio_layout, null));
view.setTag(3);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openCurrentMessage();
}
});
ViewGroup audioContainer = (ViewGroup)view.findViewById(R.id.audio_container);
cell = new PopupAudioView(this);
cell.setTag(300);
audioContainer.addView(cell);
}
cell.setMessageObject(messageObject);
if ((downloadAudios == 0 || downloadAudios == 2 && ConnectionsManager.isConnectedToWiFi())) {
cell.downloadAudioIfNeed();
}
} else {
if (textViews.size() > 0) {
view = textViews.get(0);
textViews.remove(0);
} else {
view = new FrameLayoutAnimationListener(this);
view.addView(getLayoutInflater().inflate(R.layout.popup_text_layout, null));
view.setTag(1);
View textContainer = view.findViewById(R.id.text_container);
textContainer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openCurrentMessage();
}
});
}
TextView messageText = (TextView)view.findViewById(R.id.message_text);
messageText.setTextSize(TypedValue.COMPLEX_UNIT_SP, MessagesController.getInstance().fontSize);
messageText.setText(messageObject.messageText);
}
if (view.getParent() == null) {
messageContainer.addView(view);
}
view.setVisibility(View.VISIBLE);
if (applyOffset) {
int widht = AndroidUtilities.displaySize.x - AndroidUtilities.dp(24);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) view.getLayoutParams();
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
layoutParams.width = widht;
if (num == currentMessageNum) {
layoutParams.leftMargin = 0;
} else if (num == currentMessageNum - 1) {
layoutParams.leftMargin = -widht;
} else if (num == currentMessageNum + 1) {
layoutParams.leftMargin = widht;
}
view.setLayoutParams(layoutParams);
view.invalidate();
}
return view;
}
private void reuseView(ViewGroup view) {
if (view == null) {
return;
}
int tag = (Integer)view.getTag();
view.setVisibility(View.GONE);
if (tag == 1) {
textViews.add(view);
} else if (tag == 2) {
imageViews.add(view);
} else if (tag == 3) {
audioViews.add(view);
}
}
private void prepareLayouts(int move) {
if (move == 0) {
reuseView(centerView);
reuseView(leftView);
reuseView(rightView);
for (int a = currentMessageNum - 1; a < currentMessageNum + 2; a++) {
if (a == currentMessageNum - 1) {
leftView = getViewForMessage(a, true);
} else if (a == currentMessageNum) {
centerView = getViewForMessage(a, true);
} else if (a == currentMessageNum + 1) {
rightView = getViewForMessage(a, true);
}
}
} else if (move == 1) {
reuseView(rightView);
rightView = centerView;
centerView = leftView;
leftView = getViewForMessage(currentMessageNum - 1, true);
} else if (move == 2) {
reuseView(leftView);
leftView = centerView;
centerView = rightView;
rightView = getViewForMessage(currentMessageNum + 1, true);
} else if (move == 3) {
if (rightView != null) {
int offset = ((FrameLayout.LayoutParams) rightView.getLayoutParams()).leftMargin;
reuseView(rightView);
rightView = getViewForMessage(currentMessageNum + 1, false);
int widht = AndroidUtilities.displaySize.x - AndroidUtilities.dp(24);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) rightView.getLayoutParams();
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
layoutParams.width = widht;
layoutParams.leftMargin = offset;
rightView.setLayoutParams(layoutParams);
rightView.invalidate();
}
} else if (move == 4) {
if (leftView != null) {
int offset = ((FrameLayout.LayoutParams) leftView.getLayoutParams()).leftMargin;
reuseView(leftView);
leftView = getViewForMessage(0, false);
int widht = AndroidUtilities.displaySize.x - AndroidUtilities.dp(24);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) leftView.getLayoutParams();
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
layoutParams.width = widht;
layoutParams.leftMargin = offset;
leftView.setLayoutParams(layoutParams);
leftView.invalidate();
}
}
}
private void fixLayout() {
messageContainer.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
messageContainer.getViewTreeObserver().removeOnPreDrawListener(this);
if (!checkTransitionAnimation() && !startedMoving) {
ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams)messageContainer.getLayoutParams();
if (!Utilities.isTablet(PopupNotificationActivity.this) && PopupNotificationActivity.this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
layoutParams.topMargin = AndroidUtilities.dp(40);
} else {
layoutParams.topMargin = AndroidUtilities.dp(48);
}
layoutParams.bottomMargin = AndroidUtilities.dp(48);
layoutParams.width = ViewGroup.MarginLayoutParams.MATCH_PARENT;
layoutParams.height = ViewGroup.MarginLayoutParams.MATCH_PARENT;
messageContainer.setLayoutParams(layoutParams);
applyViewsLayoutParams(0);
}
return false;
}
});
}
private void handleIntent(Intent intent) {
KeyguardManager km = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
if (km.inKeyguardRestrictedInputMode() || !ApplicationLoader.isScreenOn) {
getWindow().addFlags(
WindowManager.LayoutParams.FLAG_DIM_BEHIND |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
} else {
getWindow().addFlags(
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
}
if (currentMessageObject == null) {
currentMessageNum = 0;
}
getNewMessage();
}
private void getNewMessage() {
if (NotificationsController.getInstance().popupMessages.isEmpty()) {
onFinish();
finish();
return;
}
boolean found = false;
if ((currentMessageNum != 0 || chatActivityEnterView.hasText() || startedMoving) && currentMessageObject != null) {
for (int a = 0; a < NotificationsController.getInstance().popupMessages.size(); a++) {
if (NotificationsController.getInstance().popupMessages.get(a).messageOwner.id == currentMessageObject.messageOwner.id) {
currentMessageNum = a;
found = true;
break;
}
}
}
if (!found) {
currentMessageNum = 0;
currentMessageObject = NotificationsController.getInstance().popupMessages.get(0);
updateInterfaceForCurrentMessage(0);
} else if (startedMoving) {
if (currentMessageNum == NotificationsController.getInstance().popupMessages.size() - 1) {
prepareLayouts(3);
} else if (currentMessageNum == 1) {
prepareLayouts(4);
}
}
countText.setText(String.format("%d/%d", currentMessageNum + 1, NotificationsController.getInstance().popupMessages.size()));
}
private void openCurrentMessage() {
if (currentMessageObject == null) {
return;
}
Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
long dialog_id = currentMessageObject.getDialogId();
if ((int)dialog_id != 0) {
int lower_id = (int)dialog_id;
if (lower_id < 0) {
intent.putExtra("chatId", -lower_id);
} else {
intent.putExtra("userId", lower_id);
}
} else {
intent.putExtra("encId", (int)(dialog_id >> 32));
}
intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE);
intent.setFlags(0x00008000);
startActivity(intent);
onFinish();
finish();
}
private void updateInterfaceForCurrentMessage(int move) {
if (actionBarLayer == null) {
return;
}
currentChat = null;
currentUser = null;
long dialog_id = currentMessageObject.getDialogId();
chatActivityEnterView.setDialogId(dialog_id);
if ((int)dialog_id != 0) {
int lower_id = (int)dialog_id;
if (lower_id > 0) {
currentUser = MessagesController.getInstance().users.get(lower_id);
} else {
currentChat = MessagesController.getInstance().chats.get(-lower_id);
currentUser = MessagesController.getInstance().users.get(currentMessageObject.messageOwner.from_id);
}
} else {
TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance().encryptedChats.get((int)(dialog_id >> 32));
currentUser = MessagesController.getInstance().users.get(encryptedChat.user_id);
}
if (currentChat != null && currentUser != null) {
actionBarLayer.setTitle(currentChat.title);
actionBarLayer.setSubtitle(Utilities.formatName(currentUser.first_name, currentUser.last_name));
actionBarLayer.setTitleIcon(0, 0);
} else if (currentUser != null) {
actionBarLayer.setTitle(Utilities.formatName(currentUser.first_name, currentUser.last_name));
if ((int)dialog_id == 0) {
actionBarLayer.setTitleIcon(R.drawable.ic_lock_white, AndroidUtilities.dp(4));
} else {
actionBarLayer.setTitleIcon(0, 0);
}
}
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
if (currentChat != null) {
downloadPhotos = preferences.getInt("photo_download_chat2", 0);
downloadAudios = preferences.getInt("audio_download_chat2", 0);
} else {
downloadPhotos = preferences.getInt("photo_download_user2", 0);
downloadAudios = preferences.getInt("audio_download_user2", 0);
}
prepareLayouts(move);
updateSubtitle();
checkAndUpdateAvatar();
applyViewsLayoutParams(0);
}
private void updateSubtitle() {
if (actionBarLayer == null) {
return;
}
if (currentChat != null || currentUser == null) {
return;
}
if (currentUser.id / 1000 != 777 && currentUser.id / 1000 != 333 && ContactsController.getInstance().contactsDict.get(currentUser.id) == null && (ContactsController.getInstance().contactsDict.size() != 0 || !ContactsController.getInstance().isLoadingContacts())) {
if (currentUser.phone != null && currentUser.phone.length() != 0) {
actionBarLayer.setTitle(PhoneFormat.getInstance().format("+" + currentUser.phone));
} else {
actionBarLayer.setTitle(Utilities.formatName(currentUser.first_name, currentUser.last_name));
}
} else {
actionBarLayer.setTitle(Utilities.formatName(currentUser.first_name, currentUser.last_name));
}
CharSequence printString = MessagesController.getInstance().printingStrings.get(currentMessageObject.getDialogId());
if (printString == null || printString.length() == 0) {
lastPrintString = null;
setTypingAnimation(false);
TLRPC.User user = MessagesController.getInstance().users.get(currentUser.id);
if (user != null) {
currentUser = user;
}
actionBarLayer.setSubtitle(LocaleController.formatUserStatus(currentUser));
} else {
lastPrintString = printString;
actionBarLayer.setSubtitle(printString);
setTypingAnimation(true);
}
}
private void checkAndUpdateAvatar() {
TLRPC.FileLocation newPhoto = null;
int placeHolderId = 0;
if (currentChat != null) {
TLRPC.Chat chat = MessagesController.getInstance().chats.get(currentChat.id);
if (chat == null) {
return;
}
currentChat = chat;
if (currentChat.photo != null) {
newPhoto = currentChat.photo.photo_small;
}
placeHolderId = Utilities.getGroupAvatarForId(currentChat.id);
} else if (currentUser != null) {
TLRPC.User user = MessagesController.getInstance().users.get(currentUser.id);
if (user == null) {
return;
}
currentUser = user;
if (currentUser.photo != null) {
newPhoto = currentUser.photo.photo_small;
}
placeHolderId = Utilities.getUserAvatarForId(currentUser.id);
}
if (avatarImageView != null) {
avatarImageView.setImage(newPhoto, "50_50", placeHolderId);
}
}
private void setTypingAnimation(boolean start) {
if (actionBarLayer == null) {
return;
}
if (start) {
try {
actionBarLayer.setSubTitleIcon(R.drawable.typing_dots, AndroidUtilities.dp(4));
AnimationDrawable mAnim = (AnimationDrawable)actionBarLayer.getSubTitleIcon();
mAnim.setAlpha(200);
mAnim.start();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
} else {
actionBarLayer.setSubTitleIcon(0, 0);
}
}
@Override
public void onBackPressed() {
if (chatActivityEnterView.isEmojiPopupShowing()) {
chatActivityEnterView.hideEmojiPopup();
return;
}
super.onBackPressed();
}
@Override
protected void onResume() {
super.onResume();
if (chatActivityEnterView != null) {
chatActivityEnterView.setFieldFocused(true);
}
ConnectionsManager.getInstance().setAppPaused(false, false);
fixLayout();
wakeLock.acquire(7000);
}
@Override
protected void onPause() {
super.onPause();
overridePendingTransition(0, 0);
if (chatActivityEnterView != null) {
chatActivityEnterView.hideEmojiPopup();
chatActivityEnterView.setFieldFocused(false);
}
ConnectionsManager.getInstance().setAppPaused(true, false);
if (wakeLock.isHeld()) {
wakeLock.release();
}
}
@Override
public void didReceivedNotification(int id, Object... args) {
if (id == 1234) {
onFinish();
finish();
} else if (id == NotificationsController.pushMessagesUpdated) {
getNewMessage();
} else if (id == MessagesController.updateInterfaces) {
if (currentMessageObject == null) {
return;
}
int updateMask = (Integer)args[0];
if ((updateMask & MessagesController.UPDATE_MASK_NAME) != 0 || (updateMask & MessagesController.UPDATE_MASK_STATUS) != 0 || (updateMask & MessagesController.UPDATE_MASK_CHAT_NAME) != 0 || (updateMask & MessagesController.UPDATE_MASK_CHAT_MEMBERS) != 0) {
updateSubtitle();
}
if ((updateMask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (updateMask & MessagesController.UPDATE_MASK_CHAT_AVATAR) != 0) {
checkAndUpdateAvatar();
}
if ((updateMask & MessagesController.UPDATE_MASK_USER_PRINT) != 0) {
CharSequence printString = MessagesController.getInstance().printingStrings.get(currentMessageObject.getDialogId());
if (lastPrintString != null && printString == null || lastPrintString == null && printString != null || lastPrintString != null && printString != null && !lastPrintString.equals(printString)) {
updateSubtitle();
}
}
} else if (id == MediaController.audioDidReset) {
Integer mid = (Integer)args[0];
if (messageContainer != null) {
int count = messageContainer.getChildCount();
for (int a = 0; a < count; a++) {
View view = messageContainer.getChildAt(a);
if ((Integer)view.getTag() == 3) {
PopupAudioView cell = (PopupAudioView)view.findViewWithTag(300);
if (cell.getMessageObject() != null && cell.getMessageObject().messageOwner.id == mid) {
cell.updateButtonState();
break;
}
}
}
}
} else if (id == MediaController.audioProgressDidChanged) {
Integer mid = (Integer)args[0];
if (messageContainer != null) {
int count = messageContainer.getChildCount();
for (int a = 0; a < count; a++) {
View view = messageContainer.getChildAt(a);
if ((Integer)view.getTag() == 3) {
PopupAudioView cell = (PopupAudioView)view.findViewWithTag(300);
if (cell.getMessageObject() != null && cell.getMessageObject().messageOwner.id == mid) {
cell.updateProgress();
break;
}
}
}
}
} else if (id == 999) {
if (messageContainer != null) {
int count = messageContainer.getChildCount();
for (int a = 0; a < count; a++) {
View view = messageContainer.getChildAt(a);
view.invalidate();
}
}
} else if (id == MessagesController.contactsDidLoaded) {
updateSubtitle();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
onFinish();
if (wakeLock.isHeld()) {
wakeLock.release();
}
}
protected void onFinish() {
if (finished) {
return;
}
finished = true;
NotificationCenter.getInstance().removeObserver(this, 1234);
NotificationCenter.getInstance().removeObserver(this, NotificationsController.pushMessagesUpdated);
NotificationCenter.getInstance().removeObserver(this, MessagesController.updateInterfaces);
NotificationCenter.getInstance().removeObserver(this, MediaController.audioProgressDidChanged);
NotificationCenter.getInstance().removeObserver(this, MediaController.audioDidReset);
NotificationCenter.getInstance().removeObserver(this, MessagesController.contactsDidLoaded);
NotificationCenter.getInstance().removeObserver(this, 999);
if (chatActivityEnterView != null) {
chatActivityEnterView.onDestroy();
}
if (wakeLock.isHeld()) {
wakeLock.release();
}
}
}

View File

@ -26,15 +26,21 @@ import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import org.telegram.android.MessagesController;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.android.LocaleController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.RPCRequest;
import org.telegram.messenger.TLObject;
import org.telegram.messenger.TLRPC;
import org.telegram.ui.Adapters.BaseFragmentAdapter;
import org.telegram.ui.Views.ActionBar.ActionBarLayer;
import org.telegram.ui.Views.ActionBar.BaseFragment;
import org.telegram.ui.Views.ColorPickerView;
public class ProfileNotificationsActivity extends BaseFragment {
public class ProfileNotificationsActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate {
private ListView listView;
private long dialog_id;
@ -50,20 +56,22 @@ public class ProfileNotificationsActivity extends BaseFragment {
dialog_id = args.getLong("dialog_id");
}
@Override
public void onFragmentDestroy() {
super.onFragmentDestroy();
}
@Override
public boolean onFragmentCreate() {
settingsNotificationsRow = rowCount++;
settingsVibrateRow = rowCount++;
settingsLedRow = rowCount++;
settingsSoundRow = rowCount++;
NotificationCenter.getInstance().addObserver(this, MessagesController.notificationsSettingsUpdated);
return super.onFragmentCreate();
}
@Override
public void onFragmentDestroy() {
super.onFragmentDestroy();
NotificationCenter.getInstance().removeObserver(this, MessagesController.notificationsSettingsUpdated);
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
if (fragmentView == null) {
@ -112,6 +120,9 @@ public class ProfileNotificationsActivity extends BaseFragment {
if (listView != null) {
listView.invalidateViews();
}
if (i == settingsNotificationsRow) {
updateServerNotificationsSettings();
}
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
@ -211,6 +222,45 @@ public class ProfileNotificationsActivity extends BaseFragment {
return fragmentView;
}
public void updateServerNotificationsSettings() {
if ((int)dialog_id == 0) {
return;
}
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
TLRPC.TL_account_updateNotifySettings req = new TLRPC.TL_account_updateNotifySettings();
req.settings = new TLRPC.TL_inputPeerNotifySettings();
req.settings.sound = "default";
req.settings.events_mask = 0;
req.settings.mute_until = preferences.getInt("notify2_" + dialog_id, 0) != 2 ? 0 : Integer.MAX_VALUE;
req.settings.show_previews = preferences.getBoolean("preview_" + dialog_id, true);
req.peer = new TLRPC.TL_inputNotifyPeer();
if ((int)dialog_id < 0) {
((TLRPC.TL_inputNotifyPeer)req.peer).peer = new TLRPC.TL_inputPeerChat();
((TLRPC.TL_inputNotifyPeer)req.peer).peer.chat_id = -(int)dialog_id;
} else {
TLRPC.User user = MessagesController.getInstance().users.get((int)dialog_id);
if (user == null) {
return;
}
if (user instanceof TLRPC.TL_userForeign || user instanceof TLRPC.TL_userRequest) {
((TLRPC.TL_inputNotifyPeer)req.peer).peer = new TLRPC.TL_inputPeerForeign();
((TLRPC.TL_inputNotifyPeer)req.peer).peer.access_hash = user.access_hash;
} else {
((TLRPC.TL_inputNotifyPeer)req.peer).peer = new TLRPC.TL_inputPeerContact();
}
((TLRPC.TL_inputNotifyPeer)req.peer).peer.user_id = (int)dialog_id;
}
ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
}
});
}
@Override
public void onActivityResultFragment(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
@ -248,6 +298,13 @@ public class ProfileNotificationsActivity extends BaseFragment {
}
}
@Override
public void didReceivedNotification(int id, Object... args) {
if (id == MessagesController.notificationsSettingsUpdated) {
listView.invalidateViews();
}
}
private class ListAdapter extends BaseFragmentAdapter {
private Context mContext;

View File

@ -34,17 +34,19 @@ import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.ContactsController;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.BuildVars;
import org.telegram.messenger.LocaleController;
import org.telegram.android.LocaleController;
import org.telegram.messenger.SerializedData;
import org.telegram.messenger.TLClassStore;
import org.telegram.messenger.TLObject;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage;
import org.telegram.android.MessagesController;
import org.telegram.android.MessagesStorage;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.RPCRequest;
@ -167,7 +169,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
});
}
}
}, null, true, RPCRequest.RPCRequestClassGeneric);
});
}
};
NotificationCenter.getInstance().addObserver(this, MessagesController.updateInterfaces);
@ -245,7 +247,26 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("TextSize", R.string.TextSize));
builder.setItems(new CharSequence[]{String.format("%d", 12), String.format("%d", 13), String.format("%d", 14), String.format("%d", 15), String.format("%d", 16), String.format("%d", 17), String.format("%d", 18), String.format("%d", 19), String.format("%d", 20), String.format("%d", 21), String.format("%d", 22), String.format("%d", 23), String.format("%d", 24)}, new DialogInterface.OnClickListener() {
builder.setItems(new CharSequence[] {
String.format("%d", 12),
String.format("%d", 13),
String.format("%d", 14),
String.format("%d", 15),
String.format("%d", 16),
String.format("%d", 17),
String.format("%d", 18),
String.format("%d", 19),
String.format("%d", 20),
String.format("%d", 21),
String.format("%d", 22),
String.format("%d", 23),
String.format("%d", 24),
String.format("%d", 25),
String.format("%d", 26),
String.format("%d", 27),
String.format("%d", 28),
String.format("%d", 29),
String.format("%d", 30)}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
@ -272,7 +293,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
} else if (i == notificationRow) {
presentFragment(new SettingsNotificationsActivity());
} else if (i == blockedRow) {
presentFragment(new SettingsBlockedUsers());
presentFragment(new SettingsBlockedUsersActivity());
} else if (i == backgroundRow) {
presentFragment(new SettingsWallpapersActivity());
} else if (i == askQuestionRow) {
@ -282,7 +303,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
final TextView message = new TextView(getParentActivity());
message.setText(Html.fromHtml(LocaleController.getString("AskAQuestionInfo", R.string.AskAQuestionInfo)));
message.setTextSize(18);
message.setPadding(Utilities.dp(8), Utilities.dp(5), Utilities.dp(8), Utilities.dp(6));
message.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(5), AndroidUtilities.dp(8), AndroidUtilities.dp(6));
message.setMovementMethod(new LinkMovementMethodMy());
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
@ -313,7 +334,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure));
builder.setMessage(LocaleController.getString("AreYouSureSessions", R.string.AreYouSureSessions));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
@Override
@ -343,7 +364,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
MessagesController.getInstance().registerForPush(UserConfig.pushString);
ConnectionsManager.getInstance().initPushConnection();
}
}, null, true, RPCRequest.RPCRequestClassGeneric);
});
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
@ -460,7 +481,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
avatarImage.getLocationInWindow(coords);
PhotoViewer.PlaceProviderObject object = new PhotoViewer.PlaceProviderObject();
object.viewX = coords[0];
object.viewY = coords[1] - Utilities.statusBarHeight;
object.viewY = coords[1] - AndroidUtilities.statusBarHeight;
object.parentView = listView;
object.imageReceiver = avatarImage.imageReceiver;
object.user_id = UserConfig.getClientUserId();
@ -509,7 +530,9 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
if (datacentersBytes != null) {
SerializedData data = new SerializedData(datacentersBytes);
supportUser = (TLRPC.User)TLClassStore.Instance().TLdeserialize(data, data.readInt32());
if (supportUser != null && supportUser.id == 333000) {
supportUser = null;
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
@ -564,7 +587,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
});
}
}
}, null, true, RPCRequest.RPCRequestClassGeneric);
});
} else {
MessagesController.getInstance().users.putIfAbsent(supportUser.id, supportUser);
Bundle args = new Bundle();
@ -725,6 +748,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
if (i == 0 && full) {
TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.getClientUserId());
if (user != null && user.photo != null && user.photo.photo_big != null) {
PhotoViewer.getInstance().setParentActivity(getParentActivity());
PhotoViewer.getInstance().openPhoto(user.photo.photo_big, SettingsActivity.this);
}
} else if (i == 0 && !full || i == 1 && full) {
@ -775,7 +799,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
});
}
}
}, null, true, RPCRequest.RPCRequestClassGeneric);
});
}
}
});
@ -787,7 +811,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
textView.setText(LocaleController.getString("Online", R.string.Online));
textView = (TextView)view.findViewById(R.id.settings_name);
Typeface typeface = Utilities.getTypeface("fonts/rmedium.ttf");
Typeface typeface = AndroidUtilities.getTypeface("fonts/rmedium.ttf");
textView.setTypeface(typeface);
TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.getClientUserId());
if (user == null) {
@ -926,17 +950,21 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure));
builder.setMessage(LocaleController.getString("AreYouSureLogout", R.string.AreYouSureLogout));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear().commit();
NotificationCenter.getInstance().postNotificationName(1234);
MessagesController.getInstance().unregistedPush();
MessagesController.getInstance().logOut();
UserConfig.clearConfig();
MessagesStorage.getInstance().cleanUp();
MessagesController.getInstance().cleanUp();
ContactsController.getInstance().deleteAllAppAccounts();
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);

View File

@ -20,11 +20,11 @@ import android.widget.ListView;
import android.widget.TextView;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.LocaleController;
import org.telegram.android.LocaleController;
import org.telegram.messenger.TLObject;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.MessagesController;
import org.telegram.android.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.RPCRequest;
@ -38,7 +38,7 @@ import org.telegram.ui.Views.ActionBar.BaseFragment;
import java.util.ArrayList;
import java.util.HashMap;
public class SettingsBlockedUsers extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, ContactsActivity.ContactsActivityDelegate {
public class SettingsBlockedUsersActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, ContactsActivity.ContactsActivityDelegate {
private ListView listView;
private ListAdapter listViewAdapter;
private boolean loading;
@ -82,7 +82,7 @@ public class SettingsBlockedUsers extends BaseFragment implements NotificationCe
args.putBoolean("usersAsSections", true);
args.putBoolean("returnAsResult", true);
ContactsActivity fragment = new ContactsActivity(args);
fragment.setDelegate(SettingsBlockedUsers.this);
fragment.setDelegate(SettingsBlockedUsersActivity.this);
presentFragment(fragment);
}
}
@ -148,7 +148,7 @@ public class SettingsBlockedUsers extends BaseFragment implements NotificationCe
public void run(TLObject response, TLRPC.TL_error error) {
}
}, null, true, RPCRequest.RPCRequestClassGeneric);
});
}
}
});
@ -220,7 +220,7 @@ public class SettingsBlockedUsers extends BaseFragment implements NotificationCe
}
});
}
}, null, true, RPCRequest.RPCRequestClassGeneric);
});
ConnectionsManager.getInstance().bindRequestToGuid(requestId, classGuid);
}
@ -256,7 +256,7 @@ public class SettingsBlockedUsers extends BaseFragment implements NotificationCe
}
@Override
public void didSelectContact(TLRPC.User user) {
public void didSelectContact(TLRPC.User user, String param) {
if (user == null || blockedContactsDict.containsKey(user.id)) {
return;
}
@ -273,7 +273,7 @@ public class SettingsBlockedUsers extends BaseFragment implements NotificationCe
public void run(TLObject response, TLRPC.TL_error error) {
}
}, null, true, RPCRequest.RPCRequestClassGeneric);
});
}
private class ListAdapter extends BaseFragmentAdapter {

View File

@ -19,16 +19,16 @@ import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.telegram.messenger.LocaleController;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.LocaleController;
import org.telegram.messenger.TLObject;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.MessagesController;
import org.telegram.android.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.RPCRequest;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
import org.telegram.ui.Views.ActionBar.BaseFragment;
public class SettingsChangeNameActivity extends BaseFragment {
@ -120,7 +120,7 @@ public class SettingsChangeNameActivity extends BaseFragment {
boolean animations = preferences.getBoolean("view_animations", true);
if (!animations) {
firstNameField.requestFocus();
Utilities.showKeyboard(firstNameField);
AndroidUtilities.showKeyboard(firstNameField);
}
}
@ -143,12 +143,12 @@ public class SettingsChangeNameActivity extends BaseFragment {
public void run(TLObject response, TLRPC.TL_error error) {
}
}, null, true, RPCRequest.RPCRequestClassGeneric);
});
}
@Override
public void onOpenAnimationEnd() {
firstNameField.requestFocus();
Utilities.showKeyboard(firstNameField);
AndroidUtilities.showKeyboard(firstNameField);
}
}

View File

@ -27,12 +27,14 @@ import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.telegram.messenger.LocaleController;
import org.telegram.android.LocaleController;
import org.telegram.android.NotificationsController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.TLObject;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.MessagesController;
import org.telegram.android.MessagesController;
import org.telegram.messenger.R;
import org.telegram.messenger.RPCRequest;
import org.telegram.messenger.Utilities;
@ -41,7 +43,7 @@ import org.telegram.ui.Views.ActionBar.ActionBarLayer;
import org.telegram.ui.Views.ActionBar.BaseFragment;
import org.telegram.ui.Views.ColorPickerView;
public class SettingsNotificationsActivity extends BaseFragment {
public class SettingsNotificationsActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate {
private ListView listView;
private boolean reseting = false;
@ -52,19 +54,22 @@ public class SettingsNotificationsActivity extends BaseFragment {
private int messageVibrateRow;
private int messageSoundRow;
private int messageLedRow;
private int messagePopupNotificationRow;
private int groupSectionRow;
private int groupAlertRow;
private int groupPreviewRow;
private int groupVibrateRow;
private int groupSoundRow;
private int groupLedRow;
private int groupPopupNotificationRow;
private int inappSectionRow;
private int inappSoundRow;
private int inappVibrateRow;
private int inappPreviewRow;
private int eventsSectionRow;
private int contactJoinedRow;
private int pebbleSectionRow;
private int otherSectionRow;
private int badgeNumberRow;
private int pebbleAlertRow;
private int resetSectionRow;
private int resetNotificationsRow;
@ -78,12 +83,14 @@ public class SettingsNotificationsActivity extends BaseFragment {
messagePreviewRow = rowCount++;
messageVibrateRow = rowCount++;
messageLedRow = rowCount++;
messagePopupNotificationRow = rowCount++;
messageSoundRow = rowCount++;
groupSectionRow = rowCount++;
groupAlertRow = rowCount++;
groupPreviewRow = rowCount++;
groupVibrateRow = rowCount++;
groupLedRow = rowCount++;
groupPopupNotificationRow = rowCount++;
groupSoundRow = rowCount++;
inappSectionRow = rowCount++;
inappSoundRow = rowCount++;
@ -91,14 +98,23 @@ public class SettingsNotificationsActivity extends BaseFragment {
inappPreviewRow = rowCount++;
eventsSectionRow = rowCount++;
contactJoinedRow = rowCount++;
pebbleSectionRow = rowCount++;
otherSectionRow = rowCount++;
badgeNumberRow = rowCount++;
pebbleAlertRow = rowCount++;
resetSectionRow = rowCount++;
resetNotificationsRow = rowCount++;
NotificationCenter.getInstance().addObserver(this, MessagesController.notificationsSettingsUpdated);
return super.onFragmentCreate();
}
@Override
public void onFragmentDestroy() {
super.onFragmentDestroy();
NotificationCenter.getInstance().removeObserver(this, MessagesController.notificationsSettingsUpdated);
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
if (fragmentView == null) {
@ -134,10 +150,10 @@ public class SettingsNotificationsActivity extends BaseFragment {
}
editor.commit();
listView.invalidateViews();
updateServerNotificationsSettings(i == groupAlertRow);
} else if (i == messagePreviewRow || i == groupPreviewRow) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
boolean enabledAll = true;
boolean enabled;
if (i == messagePreviewRow) {
enabled = preferences.getBoolean("EnablePreviewAll", true);
@ -148,6 +164,7 @@ public class SettingsNotificationsActivity extends BaseFragment {
}
editor.commit();
listView.invalidateViews();
updateServerNotificationsSettings(i == groupPreviewRow);
} else if (i == messageVibrateRow || i == groupVibrateRow) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
@ -228,7 +245,7 @@ public class SettingsNotificationsActivity extends BaseFragment {
}
});
}
}, null, true, RPCRequest.RPCRequestClassGeneric);
});
} else if (i == inappSoundRow) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
@ -265,6 +282,14 @@ public class SettingsNotificationsActivity extends BaseFragment {
editor.putBoolean("EnablePebbleNotifications", !enabled);
editor.commit();
listView.invalidateViews();
} else if (i == badgeNumberRow) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
boolean enabled = preferences.getBoolean("badgeNumber", true);
editor.putBoolean("badgeNumber", !enabled);
editor.commit();
listView.invalidateViews();
NotificationsController.getInstance().setBadgeEnabled(!enabled);
} else if (i == notificationsServiceRow) {
final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
boolean enabled = preferences.getBoolean("pushService", true);
@ -342,6 +367,32 @@ public class SettingsNotificationsActivity extends BaseFragment {
}
});
showAlertDialog(builder);
} else if (i == messagePopupNotificationRow || i == groupPopupNotificationRow) {
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("PopupNotification", R.string.PopupNotification));
builder.setItems(new CharSequence[] {
LocaleController.getString("NoPopup", R.string.NoPopup),
LocaleController.getString("OnlyWhenScreenOn", R.string.OnlyWhenScreenOn),
LocaleController.getString("OnlyWhenScreenOff", R.string.OnlyWhenScreenOff),
LocaleController.getString("AlwaysShowPopup", R.string.AlwaysShowPopup)
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
if (i == messagePopupNotificationRow) {
editor.putInt("popupAll", which);
} else if (i == groupPopupNotificationRow) {
editor.putInt("popupGroup", which);
}
editor.commit();
if (listView != null) {
listView.invalidateViews();
}
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showAlertDialog(builder);
}
}
});
@ -354,6 +405,29 @@ public class SettingsNotificationsActivity extends BaseFragment {
return fragmentView;
}
public void updateServerNotificationsSettings(boolean group) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
TLRPC.TL_account_updateNotifySettings req = new TLRPC.TL_account_updateNotifySettings();
req.settings = new TLRPC.TL_inputPeerNotifySettings();
req.settings.sound = "default";
req.settings.events_mask = 0;
if (!group) {
req.peer = new TLRPC.TL_inputNotifyUsers();
req.settings.mute_until = preferences.getBoolean("EnableAll", true) ? 0 : Integer.MAX_VALUE;
req.settings.show_previews = preferences.getBoolean("EnablePreviewAll", true);
} else {
req.peer = new TLRPC.TL_inputNotifyChats();
req.settings.mute_until = preferences.getBoolean("EnableGroup", true) ? 0 : Integer.MAX_VALUE;
req.settings.show_previews = preferences.getBoolean("EnablePreviewGroup", true);
}
ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
}
});
}
@Override
public void onActivityResultFragment(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
@ -396,6 +470,13 @@ public class SettingsNotificationsActivity extends BaseFragment {
}
}
@Override
public void didReceivedNotification(int id, Object... args) {
if (id == MessagesController.notificationsSettingsUpdated) {
listView.invalidateViews();
}
}
private class ListAdapter extends BaseFragmentAdapter {
private Context mContext;
@ -410,7 +491,7 @@ public class SettingsNotificationsActivity extends BaseFragment {
@Override
public boolean isEnabled(int i) {
return !(i == messageSectionRow || i == groupSectionRow || i == inappSectionRow || i == eventsSectionRow || i == pebbleSectionRow || i == resetSectionRow);
return !(i == messageSectionRow || i == groupSectionRow || i == inappSectionRow || i == eventsSectionRow || i == otherSectionRow || i == resetSectionRow);
}
@Override
@ -450,8 +531,8 @@ public class SettingsNotificationsActivity extends BaseFragment {
textView.setText(LocaleController.getString("InAppNotifications", R.string.InAppNotifications));
} else if (i == eventsSectionRow) {
textView.setText(LocaleController.getString("Events", R.string.Events));
} else if (i == pebbleSectionRow) {
textView.setText(LocaleController.getString("Pebble", R.string.Pebble));
} else if (i == otherSectionRow) {
textView.setText(LocaleController.getString("PhoneOther", R.string.PhoneOther));
} else if (i == resetSectionRow) {
textView.setText(LocaleController.getString("Reset", R.string.Reset));
}
@ -511,12 +592,16 @@ public class SettingsNotificationsActivity extends BaseFragment {
divider.setVisibility(View.INVISIBLE);
} else if (i == pebbleAlertRow) {
enabled = preferences.getBoolean("EnablePebbleNotifications", false);
textView.setText(LocaleController.getString("Alert", R.string.Alert));
textView.setText(LocaleController.getString("Pebble", R.string.Pebble));
divider.setVisibility(View.INVISIBLE);
} else if (i == notificationsServiceRow) {
enabled = preferences.getBoolean("pushService", true);
textView.setText(LocaleController.getString("NotificationsService", R.string.NotificationsService));
divider.setVisibility(View.INVISIBLE);
} else if (i == badgeNumberRow) {
enabled = preferences.getBoolean("badgeNumber", true);
textView.setText(LocaleController.getString("BadgeNumber", R.string.BadgeNumber));
divider.setVisibility(View.VISIBLE);
}
if (enabled) {
checkButton.setImageResource(R.drawable.btn_check_on);
@ -553,6 +638,24 @@ public class SettingsNotificationsActivity extends BaseFragment {
textView.setText(LocaleController.getString("ResetAllNotifications", R.string.ResetAllNotifications));
textViewDetail.setText(LocaleController.getString("UndoAllCustom", R.string.UndoAllCustom));
divider.setVisibility(View.INVISIBLE);
} else if (i == messagePopupNotificationRow || i == groupPopupNotificationRow) {
textView.setText(LocaleController.getString("PopupNotification", R.string.PopupNotification));
int option = 0;
if (i == messagePopupNotificationRow) {
option = preferences.getInt("popupAll", 0);
} else if (i == groupPopupNotificationRow) {
option = preferences.getInt("popupGroup", 0);
}
if (option == 0) {
textViewDetail.setText(LocaleController.getString("NoPopup", R.string.NoPopup));
} else if (option == 1) {
textViewDetail.setText(LocaleController.getString("OnlyWhenScreenOn", R.string.OnlyWhenScreenOn));
} else if (option == 2) {
textViewDetail.setText(LocaleController.getString("OnlyWhenScreenOff", R.string.OnlyWhenScreenOff));
} else if (option == 3) {
textViewDetail.setText(LocaleController.getString("AlwaysShowPopup", R.string.AlwaysShowPopup));
}
divider.setVisibility(View.VISIBLE);
}
} else if (type == 3) {
if (view == null) {
@ -576,13 +679,13 @@ public class SettingsNotificationsActivity extends BaseFragment {
@Override
public int getItemViewType(int i) {
if (i == messageSectionRow || i == groupSectionRow || i == inappSectionRow || i == eventsSectionRow || i == pebbleSectionRow || i == resetSectionRow) {
if (i == messageSectionRow || i == groupSectionRow || i == inappSectionRow || i == eventsSectionRow || i == otherSectionRow || i == resetSectionRow) {
return 0;
} else if (i == messageAlertRow || i == messagePreviewRow || i == messageVibrateRow ||
i == groupAlertRow || i == groupPreviewRow || i == groupVibrateRow ||
i == inappSoundRow || i == inappVibrateRow || i == inappPreviewRow ||
i == contactJoinedRow ||
i == pebbleAlertRow || i == notificationsServiceRow) {
i == pebbleAlertRow || i == notificationsServiceRow || i == badgeNumberRow) {
return 1;
} else if (i == messageLedRow || i == groupLedRow) {
return 3;

View File

@ -29,13 +29,14 @@ import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.telegram.messenger.LocaleController;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.LocaleController;
import org.telegram.messenger.TLObject;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.MessagesStorage;
import org.telegram.android.MessagesStorage;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.RPCRequest;
@ -111,8 +112,8 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica
boolean done;
TLRPC.WallPaper wallPaper = wallpappersByIds.get(selectedBackground);
if (wallPaper != null && wallPaper.id != 1000001 && wallPaper instanceof TLRPC.TL_wallPaper) {
int width = Utilities.displaySize.x;
int height = Utilities.displaySize.y;
int width = AndroidUtilities.displaySize.x;
int height = AndroidUtilities.displaySize.y;
if (width > height) {
int temp = width;
width = height;
@ -120,7 +121,7 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica
}
TLRPC.PhotoSize size = PhotoObject.getClosestPhotoSizeWithSize(wallPaper.sizes, width, height);
String fileName = size.location.volume_id + "_" + size.location.local_id + ".jpg";
File f = new File(Utilities.getCacheDir(), fileName);
File f = new File(AndroidUtilities.getCacheDir(), fileName);
File toFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "wallpaper.jpg");
try {
done = Utilities.copyFile(f, toFile);
@ -216,7 +217,7 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica
if (requestCode == 10) {
Utilities.addMediaToGallery(currentPicturePath);
try {
Bitmap bitmap = FileLoader.loadBitmap(currentPicturePath, null, Utilities.dp(320), Utilities.dp(480));
Bitmap bitmap = FileLoader.loadBitmap(currentPicturePath, null, AndroidUtilities.dp(320), AndroidUtilities.dp(480));
File toFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "wallpaper-temp.jpg");
FileOutputStream stream = new FileOutputStream(toFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 87, stream);
@ -232,7 +233,7 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica
return;
}
try {
Bitmap bitmap = FileLoader.loadBitmap(null, data.getData(), Utilities.dp(320), Utilities.dp(480));
Bitmap bitmap = FileLoader.loadBitmap(null, data.getData(), AndroidUtilities.dp(320), AndroidUtilities.dp(480));
File toFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "wallpaper-temp.jpg");
FileOutputStream stream = new FileOutputStream(toFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 87, stream);
@ -261,8 +262,8 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica
private void processSelectedBackground() {
TLRPC.WallPaper wallPaper = wallpappersByIds.get(selectedBackground);
if (selectedBackground != -1 && selectedBackground != 1000001 && wallPaper != null && wallPaper instanceof TLRPC.TL_wallPaper) {
int width = Utilities.displaySize.x;
int height = Utilities.displaySize.y;
int width = AndroidUtilities.displaySize.x;
int height = AndroidUtilities.displaySize.y;
if (width > height) {
int temp = width;
width = height;
@ -270,7 +271,7 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica
}
TLRPC.PhotoSize size = PhotoObject.getClosestPhotoSizeWithSize(wallPaper.sizes, width, height);
String fileName = size.location.volume_id + "_" + size.location.local_id + ".jpg";
File f = new File(Utilities.getCacheDir(), fileName);
File f = new File(AndroidUtilities.getCacheDir(), fileName);
if (!f.exists()) {
progressBar.setProgress(0);
loadingFile = fileName;
@ -413,7 +414,7 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica
}
});
}
}, null, true, RPCRequest.RPCRequestClassGeneric);
});
ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid);
}
@ -528,7 +529,7 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica
BackupImageView image = (BackupImageView)view.findViewById(R.id.image);
View selection = view.findViewById(R.id.selection);
TLRPC.WallPaper wallPaper = wallPapers.get(i - 1);
TLRPC.PhotoSize size = PhotoObject.getClosestPhotoSizeWithSize(wallPaper.sizes, Utilities.dp(100), Utilities.dp(100));
TLRPC.PhotoSize size = PhotoObject.getClosestPhotoSizeWithSize(wallPaper.sizes, AndroidUtilities.dp(100), AndroidUtilities.dp(100));
if (size != null && size.location != null) {
image.setImage(size.location, "100_100", 0);
}

View File

@ -23,15 +23,16 @@ import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import org.telegram.android.AndroidUtilities;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.LocaleController;
import org.telegram.android.LocaleController;
import org.telegram.messenger.TLObject;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.ContactsController;
import org.telegram.android.ContactsController;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage;
import org.telegram.android.MessagesController;
import org.telegram.android.MessagesStorage;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.RPCRequest;
@ -51,7 +52,6 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
private ListView listView;
private ListAdapter listAdapter;
private int user_id;
private String selectedPhone;
private int totalMediaCount = -1;
private boolean creatingChat = false;
private long dialog_id;
@ -129,7 +129,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
actionBarLayer.setBackOverlay(R.layout.updating_state_layout);
if (dialog_id != 0) {
actionBarLayer.setTitle(LocaleController.getString("SecretTitle", R.string.SecretTitle));
actionBarLayer.setTitleIcon(R.drawable.ic_lock_white, Utilities.dp(4));
actionBarLayer.setTitleIcon(R.drawable.ic_lock_white, AndroidUtilities.dp(4));
} else {
actionBarLayer.setTitle(LocaleController.getString("ContactInfo", R.string.ContactInfo));
}
@ -140,7 +140,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
finishFragment();
} else if (id == block_contact) {
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure));
builder.setMessage(LocaleController.getString("AreYouSureBlockContact", R.string.AreYouSureBlockContact));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
@Override
@ -159,7 +159,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
public void run(TLObject response, TLRPC.TL_error error) {
}
}, null, true, RPCRequest.RPCRequestClassGeneric);
});
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
@ -186,7 +186,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure));
builder.setMessage(LocaleController.getString("AreYouSureDeleteContact", R.string.AreYouSureDeleteContact));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
@Override
@ -218,7 +218,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure));
builder.setMessage(LocaleController.getString("AreYouSureSecretChat", R.string.AreYouSureSecretChat));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
@Override
@ -384,7 +384,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
avatarImage.getLocationInWindow(coords);
PhotoViewer.PlaceProviderObject object = new PhotoViewer.PlaceProviderObject();
object.viewX = coords[0];
object.viewY = coords[1] - Utilities.statusBarHeight;
object.viewY = coords[1] - AndroidUtilities.statusBarHeight;
object.parentView = listView;
object.imageReceiver = avatarImage.imageReceiver;
object.user_id = user_id;
@ -445,7 +445,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
}
@Override
public void didSelectDialog(MessagesActivity messageFragment, long dialog_id) {
public void didSelectDialog(MessagesActivity messageFragment, long dialog_id, boolean param) {
if (dialog_id != 0) {
Bundle args = new Bundle();
args.putBoolean("scrollToTopOnResume", true);
@ -524,6 +524,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
public void onClick(View view) {
TLRPC.User user = MessagesController.getInstance().users.get(user_id);
if (user.photo != null && user.photo.photo_big != null) {
PhotoViewer.getInstance().setParentActivity(getParentActivity());
PhotoViewer.getInstance().openPhoto(user.photo.photo_big, UserProfileActivity.this);
}
}
@ -533,7 +534,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
onlineText = (TextView)view.findViewById(R.id.settings_online);
}
TextView textView = (TextView)view.findViewById(R.id.settings_name);
Typeface typeface = Utilities.getTypeface("fonts/rmedium.ttf");
Typeface typeface = AndroidUtilities.getTypeface("fonts/rmedium.ttf");
textView.setTypeface(typeface);
textView.setText(Utilities.formatName(user.first_name, user.last_name));
@ -572,29 +573,20 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
if (user.phone == null || user.phone.length() == 0 || getParentActivity() == null) {
return;
}
selectedPhone = user.phone;
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setItems(new CharSequence[] {LocaleController.getString("Copy", R.string.Copy), LocaleController.getString("Call", R.string.Call)}, new DialogInterface.OnClickListener() {
builder.setItems(new CharSequence[] {LocaleController.getString("Copy", R.string.Copy)}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 1) {
try {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:+" + selectedPhone));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getParentActivity().startActivity(intent);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
} else if (i == 0) {
if (i == 0) {
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager)ApplicationLoader.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(selectedPhone);
clipboard.setText(user.phone);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager)ApplicationLoader.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("label", selectedPhone);
android.content.ClipData clip = android.content.ClipData.newPlainText("label", user.phone);
clipboard.setPrimaryClip(clip);
}
}
@ -603,21 +595,37 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
showAlertDialog(builder);
}
});
}
ImageButton button = (ImageButton)view.findViewById(R.id.settings_edit_name);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TLRPC.User user = MessagesController.getInstance().users.get(user_id);
if (user == null || user instanceof TLRPC.TL_userEmpty) {
return;
ImageButton button = (ImageButton)view.findViewById(R.id.settings_edit_name);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TLRPC.User user = MessagesController.getInstance().users.get(user_id);
if (user == null || user instanceof TLRPC.TL_userEmpty) {
return;
}
NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats);
Bundle args = new Bundle();
args.putInt("user_id", user_id);
presentFragment(new ChatActivity(args), true);
}
NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats);
Bundle args = new Bundle();
args.putInt("user_id", user_id);
presentFragment(new ChatActivity(args), true);
}
});
});
button = (ImageButton)view.findViewById(R.id.settings_call_phone);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:+" + user.phone));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getParentActivity().startActivity(intent);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
}
ImageButton button = (ImageButton)view.findViewById(R.id.settings_call_phone);
button.setVisibility(user.phone == null || user.phone.length() == 0 ? View.GONE : View.VISIBLE);
TextView textView = (TextView)view.findViewById(R.id.settings_row_text);
TextView detailTextView = (TextView)view.findViewById(R.id.settings_row_text_detail);
View divider = view.findViewById(R.id.settings_row_divider);

View File

@ -0,0 +1,552 @@
/*
* This is the source code of Telegram for Android v. 1.7.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2014.
*/
package org.telegram.ui;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.coremedia.iso.boxes.Container;
import com.googlecode.mp4parser.authoring.Movie;
import com.googlecode.mp4parser.authoring.Track;
import com.googlecode.mp4parser.authoring.builder.DefaultMp4Builder;
import com.googlecode.mp4parser.authoring.container.mp4.MovieCreator;
import com.googlecode.mp4parser.authoring.tracks.CroppedTrack;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.LocaleController;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.R;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
import org.telegram.ui.Views.ActionBar.ActionBarLayer;
import org.telegram.ui.Views.ActionBar.ActionBarMenu;
import org.telegram.ui.Views.ActionBar.BaseFragment;
import org.telegram.ui.Views.VideoSeekBarView;
import org.telegram.ui.Views.VideoTimelineView;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class VideoEditorActivity extends BaseFragment implements SurfaceHolder.Callback {
private MediaPlayer videoPlayer = null;
private SurfaceHolder surfaceHolder = null;
private VideoTimelineView videoTimelineView = null;
private View videoContainerView = null;
private TextView originalSizeTextView = null;
private TextView editedSizeTextView = null;
private View textContainerView = null;
private ImageView playButton = null;
private VideoSeekBarView videoSeekBarView = null;
private boolean initied = false;
private String videoPath = null;
private int videoWidth;
private int videoHeight;
private float lastProgress = 0;
private boolean needSeek = false;
private VideoEditorActivityDelegate delegate;
public interface VideoEditorActivityDelegate {
public abstract void didFinishedVideoConverting(String videoPath);
}
private Runnable progressRunnable = new Runnable() {
@Override
public void run() {
while (videoPlayer.isPlaying()) {
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
if (videoPlayer.isPlaying()) {
float startTime = videoTimelineView.getLeftProgress() * videoPlayer.getDuration();
float endTime = videoTimelineView.getRightProgress() * videoPlayer.getDuration();
if (startTime == endTime) {
startTime = endTime - 0.01f;
}
float progress = (videoPlayer.getCurrentPosition() - startTime) / (endTime - startTime);
if (progress > lastProgress) {
videoSeekBarView.setProgress(progress);
lastProgress = progress;
}
if (videoPlayer.getCurrentPosition() >= endTime) {
try {
videoPlayer.pause();
onPlayComplete();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
}
}
});
try {
Thread.sleep(50);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
}
};
public VideoEditorActivity(Bundle args) {
super(args);
videoPath = args.getString("videoPath");
}
@Override
public boolean onFragmentCreate() {
if (videoPath == null) {
return false;
}
videoPlayer = new MediaPlayer();
videoPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
onPlayComplete();
}
});
}
});
return super.onFragmentCreate();
}
@Override
public void onFragmentDestroy() {
if (videoTimelineView != null) {
videoTimelineView.destroy();
}
super.onFragmentDestroy();
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
if (fragmentView == null) {
actionBarLayer.setBackgroundColor(0xff333333);
actionBarLayer.setItemsBackground(R.drawable.bar_selector_white);
actionBarLayer.setDisplayHomeAsUpEnabled(true, R.drawable.photo_back);
actionBarLayer.setTitle(LocaleController.getString("EditVideo", R.string.EditVideo));
actionBarLayer.setActionBarMenuOnItemClick(new ActionBarLayer.ActionBarMenuOnItemClick() {
@Override
public void onItemClick(int id) {
if (id == -1) {
finishFragment();
} else if (id == 1) {
try {
startConvert();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
}
});
ActionBarMenu menu = actionBarLayer.createMenu();
View doneItem = menu.addItemResource(1, R.layout.group_create_done_layout);
TextView doneTextView = (TextView)doneItem.findViewById(R.id.done_button);
doneTextView.setText(LocaleController.getString("Done", R.string.Done).toUpperCase());
fragmentView = inflater.inflate(R.layout.video_editor_layout, container, false);
originalSizeTextView = (TextView)fragmentView.findViewById(R.id.original_size);
editedSizeTextView = (TextView)fragmentView.findViewById(R.id.edited_size);
videoContainerView = fragmentView.findViewById(R.id.video_container);
textContainerView = fragmentView.findViewById(R.id.info_container);
videoTimelineView = (VideoTimelineView)fragmentView.findViewById(R.id.video_timeline_view);
videoTimelineView.setVideoPath(videoPath);
videoTimelineView.setDelegate(new VideoTimelineView.VideoTimelineViewDelegate() {
@Override
public void onLeftProgressChanged(float progress) {
try {
if (videoPlayer.isPlaying()) {
videoPlayer.pause();
playButton.setImageResource(R.drawable.video_play);
}
videoPlayer.setOnSeekCompleteListener(null);
videoPlayer.seekTo((int)(videoPlayer.getDuration() * progress));
} catch (Exception e) {
FileLog.e("tmessages", e);
}
needSeek = true;
videoSeekBarView.setProgress(0);
updateVideoEditedInfo();
}
@Override
public void onRifhtProgressChanged(float progress) {
try {
if (videoPlayer.isPlaying()) {
videoPlayer.pause();
playButton.setImageResource(R.drawable.video_play);
}
videoPlayer.setOnSeekCompleteListener(null);
videoPlayer.seekTo((int)(videoPlayer.getDuration() * progress));
} catch (Exception e) {
FileLog.e("tmessages", e);
}
needSeek = true;
videoSeekBarView.setProgress(0);
updateVideoEditedInfo();
}
});
videoSeekBarView = (VideoSeekBarView)fragmentView.findViewById(R.id.video_seekbar);
videoSeekBarView.delegate = new VideoSeekBarView.SeekBarDelegate() {
@Override
public void onSeekBarDrag(float progress) {
if (videoPlayer.isPlaying()) {
try {
float prog = videoTimelineView.getLeftProgress() + (videoTimelineView.getRightProgress() - videoTimelineView.getLeft()) * progress;
videoPlayer.seekTo((int)(videoPlayer.getDuration() * prog));
lastProgress = progress;
} catch (Exception e) {
FileLog.e("tmessages", e);
}
} else {
lastProgress = progress;
needSeek = true;
}
}
};
playButton = (ImageView)fragmentView.findViewById(R.id.play_button);
playButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (surfaceHolder.isCreating()) {
return;
}
play();
}
});
SurfaceView surfaceView = (SurfaceView) fragmentView.findViewById(R.id.video_view);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
surfaceHolder.setFixedSize(270, 480);
updateVideoOriginalInfo();
updateVideoEditedInfo();
} else {
ViewGroup parent = (ViewGroup)fragmentView.getParent();
if (parent != null) {
parent.removeView(fragmentView);
}
}
return fragmentView;
}
@Override
public void onResume() {
super.onResume();
fixLayout();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
fixLayout();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
videoPlayer.setDisplay(holder);
try {
videoPlayer.setDataSource(videoPath);
videoPlayer.prepare();
videoWidth = videoPlayer.getVideoWidth();
videoHeight = videoPlayer.getVideoHeight();
fixVideoSize();
videoPlayer.seekTo((int) (videoTimelineView.getLeftProgress() * videoPlayer.getDuration()));
initied = true;
} catch (Exception e) {
FileLog.e("tmessages", e);
}
updateVideoOriginalInfo();
updateVideoEditedInfo();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
videoPlayer.setDisplay(null);
}
private void onPlayComplete() {
playButton.setImageResource(R.drawable.video_play);
videoSeekBarView.setProgress(0);
try {
videoPlayer.seekTo((int) (videoTimelineView.getLeftProgress() * videoPlayer.getDuration()));
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
private void updateVideoOriginalInfo() {
if (!initied || originalSizeTextView == null) {
return;
}
File file = new File(videoPath);
String videoDimension = String.format("%dx%d", videoPlayer.getVideoWidth(), videoPlayer.getVideoHeight());
int minutes = videoPlayer.getDuration() / 1000 / 60;
int seconds = (int)Math.ceil(videoPlayer.getDuration() / 1000) - minutes * 60;
String videoTimeSize = String.format("%d:%02d, %s", minutes, seconds, Utilities.formatFileSize(file.length()));
originalSizeTextView.setText(String.format("%s: %s, %s", LocaleController.getString("OriginalVideo", R.string.OriginalVideo), videoDimension, videoTimeSize));
}
private void updateVideoEditedInfo() {
if (!initied || editedSizeTextView == null) {
return;
}
File file = new File(videoPath);
long size = file.length();
float videoWidth = videoPlayer.getVideoWidth();
float videoHeight = videoPlayer.getVideoHeight();
if (videoWidth > 640 || videoHeight > 640) {
float scale = videoWidth > videoHeight ? 640.0f / videoWidth : 640.0f / videoHeight;
videoWidth *= scale;
videoHeight *= scale;
size *= (scale * scale);
}
String videoDimension = String.format("%dx%d", (int)videoWidth, (int)videoHeight);
int minutes = videoPlayer.getDuration() / 1000 / 60;
int seconds = (int)Math.ceil(videoPlayer.getDuration() / 1000) - minutes * 60;
String videoTimeSize = String.format("%d:%02d, ~%s", minutes, seconds, Utilities.formatFileSize(size));
editedSizeTextView.setText(String.format("%s: %s, %s", LocaleController.getString("EditedVideo", R.string.EditedVideo), videoDimension, videoTimeSize));
}
private void fixVideoSize() {
if (videoWidth == 0 || videoHeight == 0 || fragmentView == null || getParentActivity() == null) {
return;
}
int viewHeight = 0;
if (!Utilities.isTablet(getParentActivity()) && getParentActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
viewHeight = AndroidUtilities.displaySize.y - AndroidUtilities.statusBarHeight - AndroidUtilities.dp(40);
} else {
viewHeight = AndroidUtilities.displaySize.y - AndroidUtilities.statusBarHeight - AndroidUtilities.dp(48);
}
int width = 0;
int height = 0;
if (getParentActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
width = AndroidUtilities.displaySize.x - AndroidUtilities.displaySize.x / 2 - AndroidUtilities.dp(24);
height = viewHeight - AndroidUtilities.dp(32);
} else {
width = AndroidUtilities.displaySize.x;
height = viewHeight - AndroidUtilities.dp(176);
}
float wr = (float)width / (float)videoWidth;
float hr = (float)height / (float)videoHeight;
float ar = (float)videoWidth / (float)videoHeight;
if (wr > hr) {
width = (int) (height * ar);
} else {
height = (int) (width / ar);
}
surfaceHolder.setFixedSize(width, height);
}
private void fixLayout() {
if (originalSizeTextView == null) {
return;
}
originalSizeTextView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
originalSizeTextView.getViewTreeObserver().removeOnPreDrawListener(this);
if (getParentActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams)videoContainerView.getLayoutParams();
layoutParams.topMargin = AndroidUtilities.dp(16);
layoutParams.bottomMargin = AndroidUtilities.dp(16);
layoutParams.width = AndroidUtilities.displaySize.x / 2 - AndroidUtilities.dp(24);
layoutParams.leftMargin = AndroidUtilities.dp(16);
videoContainerView.setLayoutParams(layoutParams);
layoutParams = (FrameLayout.LayoutParams)textContainerView.getLayoutParams();
layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams.width = AndroidUtilities.displaySize.x / 2 - AndroidUtilities.dp(24);
layoutParams.leftMargin = AndroidUtilities.displaySize.x / 2 + AndroidUtilities.dp(8);
layoutParams.rightMargin = AndroidUtilities.dp(16);
layoutParams.topMargin = AndroidUtilities.dp(16);
textContainerView.setLayoutParams(layoutParams);
} else {
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams)videoContainerView.getLayoutParams();
layoutParams.topMargin = AndroidUtilities.dp(16);
layoutParams.bottomMargin = AndroidUtilities.dp(160);
layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams.leftMargin = 0;
videoContainerView.setLayoutParams(layoutParams);
layoutParams = (FrameLayout.LayoutParams)textContainerView.getLayoutParams();
layoutParams.height = AndroidUtilities.dp(143);
layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams.leftMargin = 0;
layoutParams.rightMargin = 0;
layoutParams.topMargin = 0;
textContainerView.setLayoutParams(layoutParams);
}
fixVideoSize();
videoTimelineView.clearFrames();
return false;
}
});
}
private void play() {
if (videoPlayer.isPlaying()) {
videoPlayer.pause();
playButton.setImageResource(R.drawable.video_play);
} else {
try {
playButton.setImageDrawable(null);
lastProgress = 0;
if (needSeek) {
float prog = videoTimelineView.getLeftProgress() + (videoTimelineView.getRightProgress() - videoTimelineView.getLeft()) * videoSeekBarView.getProgress();
videoPlayer.seekTo((int)(videoPlayer.getDuration() * prog));
needSeek = false;
}
videoPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
@Override
public void onSeekComplete(MediaPlayer mp) {
float startTime = videoTimelineView.getLeftProgress() * videoPlayer.getDuration();
float endTime = videoTimelineView.getRightProgress() * videoPlayer.getDuration();
if (startTime == endTime) {
startTime = endTime - 0.01f;
}
lastProgress = (videoPlayer.getCurrentPosition() - startTime) / (endTime - startTime);
videoSeekBarView.setProgress(lastProgress);
}
});
videoPlayer.start();
new Thread(progressRunnable).start();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
}
public void setDelegate(VideoEditorActivityDelegate delegate) {
this.delegate = delegate;
}
private void startConvert() throws Exception {
Movie movie = MovieCreator.build(videoPath);
List<Track> tracks = movie.getTracks();
movie.setTracks(new LinkedList<Track>());
double startTime = videoTimelineView.getLeftProgress() * videoPlayer.getDuration() / 1000.0;
double endTime = videoTimelineView.getRightProgress() * videoPlayer.getDuration() / 1000.0;
boolean timeCorrected = false;
for (Track track : tracks) {
if (track.getSyncSamples() != null && track.getSyncSamples().length > 0) {
if (timeCorrected) {
throw new RuntimeException("The startTime has already been corrected by another track with SyncSample. Not Supported.");
}
startTime = correctTimeToSyncSample(track, startTime, false);
endTime = correctTimeToSyncSample(track, endTime, true);
timeCorrected = true;
}
}
for (Track track : tracks) {
long currentSample = 0;
double currentTime = 0;
double lastTime = 0;
long startSample = -1;
long endSample = -1;
for (int i = 0; i < track.getSampleDurations().length; i++) {
long delta = track.getSampleDurations()[i];
if (currentTime > lastTime && currentTime <= startTime) {
startSample = currentSample;
}
if (currentTime > lastTime && currentTime <= endTime) {
endSample = currentSample;
}
lastTime = currentTime;
currentTime += (double) delta / (double) track.getTrackMetaData().getTimescale();
currentSample++;
}
movie.addTrack(new CroppedTrack(track, startSample, endSample));
}
long start1 = System.currentTimeMillis();
Container out = new DefaultMp4Builder().build(movie);
long start2 = System.currentTimeMillis();
String fileName = Integer.MIN_VALUE + "_" + UserConfig.lastLocalId + ".mp4";
UserConfig.lastLocalId--;
File cacheFile = new File(AndroidUtilities.getCacheDir(), fileName);
UserConfig.saveConfig(false);
FileOutputStream fos = new FileOutputStream(cacheFile);
FileChannel fc = fos.getChannel();
out.writeContainer(fc);
fc.close();
fos.close();
if (delegate != null) {
delegate.didFinishedVideoConverting(cacheFile.getAbsolutePath());
finishFragment();
}
}
private static double correctTimeToSyncSample(Track track, double cutHere, boolean next) {
double[] timeOfSyncSamples = new double[track.getSyncSamples().length];
long currentSample = 0;
double currentTime = 0;
for (int i = 0; i < track.getSampleDurations().length; i++) {
long delta = track.getSampleDurations()[i];
if (Arrays.binarySearch(track.getSyncSamples(), currentSample + 1) >= 0) {
timeOfSyncSamples[Arrays.binarySearch(track.getSyncSamples(), currentSample + 1)] = currentTime;
}
currentTime += (double) delta / (double) track.getTrackMetaData().getTimescale();
currentSample++;
}
double previous = 0;
for (double timeOfSyncSample : timeOfSyncSamples) {
if (timeOfSyncSample > cutHere) {
if (next) {
return timeOfSyncSample;
} else {
return previous;
}
}
previous = timeOfSyncSample;
}
return timeOfSyncSamples[timeOfSyncSamples.length - 1];
}
}

View File

@ -19,6 +19,7 @@ import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import org.telegram.android.AndroidUtilities;
import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;
@ -52,7 +53,7 @@ public class ActionBar extends FrameLayout {
addView(shadowView);
shadowView.setVisibility(INVISIBLE);
ViewGroup.LayoutParams layoutParams = shadowView.getLayoutParams();
layoutParams.width = Utilities.dp(2);
layoutParams.width = AndroidUtilities.dp(2);
layoutParams.height = LayoutParams.MATCH_PARENT;
shadowView.setLayoutParams(layoutParams);
shadowView.setBackgroundResource(R.drawable.shadow);
@ -116,7 +117,7 @@ public class ActionBar extends FrameLayout {
layoutParams.width = LayoutParams.MATCH_PARENT;
layoutParams.height = LayoutParams.MATCH_PARENT;
layer.setLayoutParams(layoutParams);
shadowView.setX(-Utilities.dp(2));
shadowView.setX(-AndroidUtilities.dp(2));
shadowView.setVisibility(VISIBLE);
previousLayer.setBackOverlayVisible(isBackOverlayVisible);
}
@ -143,7 +144,7 @@ public class ActionBar extends FrameLayout {
return;
}
currentLayer.setX(dx);
shadowView.setX(dx - Utilities.dp(2));
shadowView.setX(dx - AndroidUtilities.dp(2));
if (dx != 0) {
if (previousLayer != null) {
previousLayer.setAlpha(Math.min(1, (float) dx / (float) currentLayer.getMeasuredWidth()));
@ -159,11 +160,11 @@ public class ActionBar extends FrameLayout {
public void setupAnimations(ArrayList<Animator> animators, boolean back) {
if (back) {
animators.add(ObjectAnimator.ofFloat(currentLayer, "x", 0));
animators.add(ObjectAnimator.ofFloat(shadowView, "x", -Utilities.dp(2)));
animators.add(ObjectAnimator.ofFloat(shadowView, "x", -AndroidUtilities.dp(2)));
animators.add(ObjectAnimator.ofFloat(previousLayer, "alpha", 0));
} else {
animators.add(ObjectAnimator.ofFloat(currentLayer, "x", getMeasuredWidth()));
animators.add(ObjectAnimator.ofFloat(shadowView, "x", getMeasuredWidth() - Utilities.dp(2)));
animators.add(ObjectAnimator.ofFloat(shadowView, "x", getMeasuredWidth() - AndroidUtilities.dp(2)));
animators.add(ObjectAnimator.ofFloat(previousLayer, "alpha", 1.0f));
}
}
@ -171,9 +172,9 @@ public class ActionBar extends FrameLayout {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (!Utilities.isTablet(getContext()) && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(Utilities.dp(40), MeasureSpec.EXACTLY));
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(40), MeasureSpec.EXACTLY));
} else {
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(Utilities.dp(48), MeasureSpec.EXACTLY));
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(48), MeasureSpec.EXACTLY));
}
}

View File

@ -32,6 +32,7 @@ import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import org.telegram.android.AndroidUtilities;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;
@ -139,7 +140,7 @@ public class ActionBarActivity extends Activity {
contentView.addView(shadowView);
shadowView.setBackgroundResource(R.drawable.shadow);
ViewGroup.LayoutParams layoutParams = shadowView.getLayoutParams();
layoutParams.width = Utilities.dp(2);
layoutParams.width = AndroidUtilities.dp(2);
layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT;
shadowView.setLayoutParams(layoutParams);
shadowView.setVisibility(View.INVISIBLE);
@ -202,7 +203,7 @@ public class ActionBarActivity extends Activity {
containerViewBack.setX(0);
actionBar.stopMoving(backAnimation);
shadowView.setVisibility(View.INVISIBLE);
shadowView.setX(-Utilities.dp(2));
shadowView.setX(-AndroidUtilities.dp(2));
if (!backAnimation) {
BaseFragment lastFragment = fragmentsStack.get(fragmentsStack.size() - 1);
lastFragment.onPause();
@ -229,7 +230,7 @@ public class ActionBarActivity extends Activity {
}
}
containerViewBack.setVisibility(View.GONE);
Utilities.unlockOrientation(this);
AndroidUtilities.unlockOrientation(this);
startedTracking = false;
animationInProgress = false;
}
@ -239,7 +240,7 @@ public class ActionBarActivity extends Activity {
startedTracking = true;
startedTrackingX = (int) ev.getX();
shadowView.setVisibility(View.VISIBLE);
shadowView.setX(-Utilities.dp(2));
shadowView.setX(-AndroidUtilities.dp(2));
containerViewBack.setVisibility(View.VISIBLE);
beginTrackingSent = false;
@ -260,7 +261,7 @@ public class ActionBarActivity extends Activity {
}
lastFragment.onResume();
Utilities.lockOrientation(this);
AndroidUtilities.lockOrientation(this);
}
public boolean onTouchEvent(MotionEvent ev) {
@ -284,12 +285,12 @@ public class ActionBarActivity extends Activity {
int dx = Math.max(0, (int) (ev.getX() - startedTrackingX));
int dy = Math.abs((int)ev.getY() - startedTrackingY);
velocityTracker.addMovement(ev);
if (maybeStartTracking && !startedTracking && dx >= Utilities.dp(10) && Math.abs(dx) / 3 > dy) {
if (maybeStartTracking && !startedTracking && dx >= AndroidUtilities.dp(10) && Math.abs(dx) / 3 > dy) {
prepareForMoving(ev);
} else if (startedTracking) {
if (!beginTrackingSent) {
if (getCurrentFocus() != null) {
Utilities.hideKeyboard(getCurrentFocus());
AndroidUtilities.hideKeyboard(getCurrentFocus());
}
BaseFragment currentFragment = fragmentsStack.get(fragmentsStack.size() - 1);
currentFragment.onBeginSlide();
@ -297,7 +298,7 @@ public class ActionBarActivity extends Activity {
}
actionBar.moveActionBarByX(dx);
containerView.setX(dx);
shadowView.setX(dx - Utilities.dp(2));
shadowView.setX(dx - AndroidUtilities.dp(2));
}
} else if (ev != null && ev.getPointerId(0) == startedTrackingPointerId && (ev.getAction() == MotionEvent.ACTION_CANCEL || ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_POINTER_UP)) {
if (velocityTracker == null) {
@ -321,11 +322,11 @@ public class ActionBarActivity extends Activity {
if (!backAnimation) {
distToMove = containerView.getMeasuredWidth() - x;
animators.add(ObjectAnimator.ofFloat(containerView, "x", containerView.getMeasuredWidth()));
animators.add(ObjectAnimator.ofFloat(shadowView, "x", containerView.getMeasuredWidth() - Utilities.dp(2)));
animators.add(ObjectAnimator.ofFloat(shadowView, "x", containerView.getMeasuredWidth() - AndroidUtilities.dp(2)));
} else {
distToMove = x;
animators.add(ObjectAnimator.ofFloat(containerView, "x", 0));
animators.add(ObjectAnimator.ofFloat(shadowView, "x", -Utilities.dp(2)));
animators.add(ObjectAnimator.ofFloat(shadowView, "x", -AndroidUtilities.dp(2)));
}
actionBar.setupAnimations(animators, backAnimation);
@ -439,9 +440,9 @@ public class ActionBarActivity extends Activity {
int height = 0;
if (actionBar.getVisibility() == View.VISIBLE) {
if (!Utilities.isTablet(this) && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
height = Utilities.dp(40);
height = AndroidUtilities.dp(40);
} else {
height = Utilities.dp(48);
height = AndroidUtilities.dp(48);
}
}
@ -500,7 +501,7 @@ public class ActionBarActivity extends Activity {
return false;
}
if (getCurrentFocus() != null) {
Utilities.hideKeyboard(getCurrentFocus());
AndroidUtilities.hideKeyboard(getCurrentFocus());
}
boolean needAnimation = openAnimation != null && !forceWithoutAnimation && getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).getBoolean("view_animations", true);
@ -575,7 +576,7 @@ public class ActionBarActivity extends Activity {
return;
}
if (getCurrentFocus() != null) {
Utilities.hideKeyboard(getCurrentFocus());
AndroidUtilities.hideKeyboard(getCurrentFocus());
}
boolean needAnimation = animated && closeAnimation != null && getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).getBoolean("view_animations", true);
final BaseFragment currentFragment = fragmentsStack.get(fragmentsStack.size() - 1);
@ -634,6 +635,7 @@ public class ActionBarActivity extends Activity {
}
public void removeFragmentFromStack(BaseFragment fragment) {
fragment.onPause();
fragment.onFragmentDestroy();
fragment.setParentActivity(null);
fragmentsStack.remove(fragment);

View File

@ -21,6 +21,7 @@ import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import org.telegram.android.AndroidUtilities;
import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;
@ -65,7 +66,7 @@ public class ActionBarLayer extends FrameLayout {
layoutParams.height = LayoutParams.FILL_PARENT;
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
backButtonFrameLayout.setLayoutParams(layoutParams);
backButtonFrameLayout.setPadding(0, 0, Utilities.dp(4), 0);
backButtonFrameLayout.setPadding(0, 0, AndroidUtilities.dp(4), 0);
backButtonFrameLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
@ -99,7 +100,7 @@ public class ActionBarLayer extends FrameLayout {
layoutParams.width = LayoutParams.WRAP_CONTENT;
layoutParams.height = LayoutParams.WRAP_CONTENT;
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
layoutParams.setMargins(Utilities.dp(3), (height - backButtonImageView.getDrawable().getIntrinsicHeight()) / 2, 0, 0);
layoutParams.setMargins(AndroidUtilities.dp(3), (height - backButtonImageView.getDrawable().getIntrinsicHeight()) / 2, 0, 0);
backButtonImageView.setLayoutParams(layoutParams);
}
}
@ -110,11 +111,11 @@ public class ActionBarLayer extends FrameLayout {
if (!Utilities.isTablet(getContext()) && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
layoutParams.width = (int)(logoImageView.getDrawable().getIntrinsicWidth() / 1.3f);
layoutParams.height = (int)(logoImageView.getDrawable().getIntrinsicHeight() / 1.3f);
layoutParams.setMargins(Utilities.dp(12), (height - layoutParams.height) / 2, 0, 0);
layoutParams.setMargins(AndroidUtilities.dp(12), (height - layoutParams.height) / 2, 0, 0);
} else {
layoutParams.width = logoImageView.getDrawable().getIntrinsicWidth();
layoutParams.height = logoImageView.getDrawable().getIntrinsicHeight();
layoutParams.setMargins(Utilities.dp(12), (height - layoutParams.width) / 2, 0, 0);
layoutParams.setMargins(AndroidUtilities.dp(12), (height - layoutParams.width) / 2, 0, 0);
}
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
logoImageView.setLayoutParams(layoutParams);
@ -122,9 +123,9 @@ public class ActionBarLayer extends FrameLayout {
}
private void positionTitle(int width, int height) {
int offset = Utilities.dp(2);
int offset = AndroidUtilities.dp(2);
if (!Utilities.isTablet(getContext()) && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
offset = Utilities.dp(1);
offset = AndroidUtilities.dp(1);
}
int maxTextWidth = 0;
@ -163,17 +164,17 @@ public class ActionBarLayer extends FrameLayout {
int x = 0;
if (logoImageView == null || logoImageView.getVisibility() == GONE) {
x = Utilities.dp(16);
x = AndroidUtilities.dp(16);
} else {
if (!Utilities.isTablet(getContext()) && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
x = Utilities.dp(22) + (int)(logoImageView.getDrawable().getIntrinsicWidth() / 1.3f);
x = AndroidUtilities.dp(22) + (int)(logoImageView.getDrawable().getIntrinsicWidth() / 1.3f);
} else {
x = Utilities.dp(22) + logoImageView.getDrawable().getIntrinsicWidth();
x = AndroidUtilities.dp(22) + logoImageView.getDrawable().getIntrinsicWidth();
}
}
if (menu != null) {
maxTextWidth = Math.min(maxTextWidth, width - menu.getMeasuredWidth() - Utilities.dp(16));
maxTextWidth = Math.min(maxTextWidth, width - menu.getMeasuredWidth() - AndroidUtilities.dp(16));
}
if (titleTextView != null && titleTextView.getVisibility() == VISIBLE) {
@ -196,7 +197,7 @@ public class ActionBarLayer extends FrameLayout {
}
ViewGroup.LayoutParams layoutParams1 = backButtonFrameLayout.getLayoutParams();
layoutParams1.width = x + maxTextWidth + (isSearchFieldVisible ? 0 : Utilities.dp(6));
layoutParams1.width = x + maxTextWidth + (isSearchFieldVisible ? 0 : AndroidUtilities.dp(6));
backButtonFrameLayout.setLayoutParams(layoutParams1);
}
@ -206,7 +207,7 @@ public class ActionBarLayer extends FrameLayout {
}
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams)menu.getLayoutParams();
layoutParams.width = isSearchFieldVisible ? LayoutParams.MATCH_PARENT : LayoutParams.WRAP_CONTENT;
layoutParams.leftMargin = isSearchFieldVisible ? Utilities.dp(26) + logoImageView.getDrawable().getIntrinsicWidth() : 0;
layoutParams.leftMargin = isSearchFieldVisible ? AndroidUtilities.dp(26) + logoImageView.getDrawable().getIntrinsicWidth() : 0;
menu.setLayoutParams(layoutParams);
menu.measure(width, height);
}
@ -402,7 +403,7 @@ public class ActionBarLayer extends FrameLayout {
if (subTitleTextView != null) {
subTitleTextView.setVisibility(visible ? GONE : VISIBLE);
}
backButtonFrameLayout.setPadding(0, 0, visible ? 0 : Utilities.dp(4), 0);
backButtonFrameLayout.setPadding(0, 0, visible ? 0 : AndroidUtilities.dp(4), 0);
if (visible) {
oldUseLogo = logoImageView != null && logoImageView.getVisibility() == VISIBLE;
setDisplayUseLogoEnabled(true, R.drawable.ic_ab_search);
@ -495,7 +496,7 @@ public class ActionBarLayer extends FrameLayout {
layoutParams.height = LayoutParams.MATCH_PARENT;
actionOverlay.setLayoutParams(layoutParams);
actionOverlay.measure(widthMeasureSpec, heightMeasureSpec);
layoutParams.width = Math.min(actionOverlay.getMeasuredWidth() + Utilities.dp(4), widthMeasureSpec - (menu != null ? menu.getMeasuredWidth() : 0));
layoutParams.width = Math.min(actionOverlay.getMeasuredWidth() + AndroidUtilities.dp(4), widthMeasureSpec - (menu != null ? menu.getMeasuredWidth() : 0));
actionOverlay.setLayoutParams(layoutParams);
}
}

View File

@ -16,7 +16,7 @@ import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import org.telegram.messenger.Utilities;
import org.telegram.android.AndroidUtilities;
public class ActionBarMenu extends LinearLayout {
@ -68,7 +68,7 @@ public class ActionBarMenu extends LinearLayout {
addView(menuItem);
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams)menuItem.getLayoutParams();
layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams.width = Utilities.dp(56);
layoutParams.width = AndroidUtilities.dp(56);
menuItem.setLayoutParams(layoutParams);
menuItem.setOnClickListener(new OnClickListener() {
@Override

View File

@ -26,6 +26,7 @@ import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.telegram.android.AndroidUtilities;
import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;
@ -151,8 +152,8 @@ public class ActionBarMenuItem extends ImageView {
delimeter.setBackgroundColor(0xffdcdcdc);
popupLayout.addView(delimeter);
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams)delimeter.getLayoutParams();
layoutParams.width = Utilities.dp(196);
layoutParams.height = Utilities.density >= 3 ? 2 : 1;
layoutParams.width = AndroidUtilities.dp(196);
layoutParams.height = AndroidUtilities.density >= 3 ? 2 : 1;
delimeter.setLayoutParams(layoutParams);
delimeter.setTag(100 + id);
}
@ -160,19 +161,19 @@ public class ActionBarMenuItem extends ImageView {
textView.setTextColor(0xff000000);
textView.setBackgroundResource(R.drawable.list_selector);
textView.setGravity(Gravity.CENTER_VERTICAL);
textView.setPadding(Utilities.dp(16), 0, Utilities.dp(16), 0);
textView.setPadding(AndroidUtilities.dp(16), 0, AndroidUtilities.dp(16), 0);
textView.setTextSize(18);
textView.setMinWidth(Utilities.dp(196));
textView.setMinWidth(AndroidUtilities.dp(196));
textView.setTag(id);
textView.setText(text);
if (icon != 0) {
textView.setCompoundDrawablePadding(Utilities.dp(12));
textView.setCompoundDrawablePadding(AndroidUtilities.dp(12));
textView.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(icon), null, null, null);
}
popupLayout.addView(textView);
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams)textView.getLayoutParams();
layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
layoutParams.height = Utilities.dp(48);
layoutParams.height = AndroidUtilities.dp(48);
textView.setLayoutParams(layoutParams);
textView.setOnClickListener(new OnClickListener() {
@Override
@ -201,7 +202,7 @@ public class ActionBarMenuItem extends ImageView {
popupWindow.setClippingEnabled(true);
popupWindow.setInputMethodMode(ActionBarPopupWindow.INPUT_METHOD_NOT_NEEDED);
popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
popupLayout.measure(MeasureSpec.makeMeasureSpec(Utilities.dp(1000), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(Utilities.dp(1000), MeasureSpec.AT_MOST));
popupLayout.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), MeasureSpec.AT_MOST));
}
popupWindow.setFocusable(true);
if (popupLayout.getMeasuredWidth() == 0) {
@ -219,7 +220,7 @@ public class ActionBarMenuItem extends ImageView {
if (searchField.getVisibility() == VISIBLE) {
searchField.setVisibility(GONE);
setVisibility(VISIBLE);
Utilities.hideKeyboard(searchField);
AndroidUtilities.hideKeyboard(searchField);
if (listener != null) {
listener.onSearchCollapse();
}
@ -229,7 +230,7 @@ public class ActionBarMenuItem extends ImageView {
setVisibility(GONE);
searchField.setText("");
searchField.requestFocus();
Utilities.showKeyboard(searchField);
AndroidUtilities.showKeyboard(searchField);
if (listener != null) {
listener.onSearchExpand();
}
@ -254,13 +255,13 @@ public class ActionBarMenuItem extends ImageView {
searchField.setTextColor(0xffffffff);
searchField.setSingleLine(true);
searchField.setBackgroundResource(R.drawable.search_light_states);
searchField.setPadding(Utilities.dp(6), 0, Utilities.dp(6), 0);
searchField.setPadding(AndroidUtilities.dp(6), 0, AndroidUtilities.dp(6), 0);
searchField.setInputType(EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
searchField.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH || event != null && event.getAction() == KeyEvent.ACTION_UP && event.getKeyCode() == KeyEvent.KEYCODE_SEARCH) {
Utilities.hideKeyboard(searchField);
AndroidUtilities.hideKeyboard(searchField);
}
return false;
}
@ -308,8 +309,8 @@ public class ActionBarMenuItem extends ImageView {
layoutParams.weight = 1;
layoutParams.width = 0;
layoutParams.gravity = Gravity.CENTER_VERTICAL;
layoutParams.height = Utilities.dp(36);
layoutParams.rightMargin = Utilities.dp(4);
layoutParams.height = AndroidUtilities.dp(36);
layoutParams.rightMargin = AndroidUtilities.dp(4);
searchField.setLayoutParams(layoutParams);
searchField.setVisibility(GONE);
}

View File

@ -15,6 +15,7 @@ import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import org.telegram.android.AndroidUtilities;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
@ -117,8 +118,8 @@ public class AvatarUpdater implements NotificationCenter.NotificationCenterDeleg
if (bitmap == null) {
return;
}
smallPhoto = FileLoader.scaleAndSaveImage(bitmap, 100, 100, 87, false);
bigPhoto = FileLoader.scaleAndSaveImage(bitmap, 800, 800, 87, false);
smallPhoto = FileLoader.scaleAndSaveImage(bitmap, 100, 100, 80, false);
bigPhoto = FileLoader.scaleAndSaveImage(bitmap, 800, 800, 80, false);
if (bigPhoto != null && smallPhoto != null) {
if (returnOnly) {
if (delegate != null) {
@ -126,7 +127,7 @@ public class AvatarUpdater implements NotificationCenter.NotificationCenterDeleg
}
} else {
UserConfig.saveConfig(false);
uploadingAvatar = Utilities.getCacheDir() + "/" + bigPhoto.location.volume_id + "_" + bigPhoto.location.local_id + ".jpg";
uploadingAvatar = AndroidUtilities.getCacheDir() + "/" + bigPhoto.location.volume_id + "_" + bigPhoto.location.local_id + ".jpg";
NotificationCenter.getInstance().addObserver(AvatarUpdater.this, FileLoader.FileDidUpload);
NotificationCenter.getInstance().addObserver(AvatarUpdater.this, FileLoader.FileDidFailUpload);
FileLoader.getInstance().uploadFile(uploadingAvatar, false);

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