Update to 4.2.0

source before release? how this even possible?
This commit is contained in:
DrKLO 2017-07-23 15:56:38 +03:00
parent bcc13a5cb9
commit 56e22d4c59
306 changed files with 11017 additions and 5141 deletions

View File

@ -602,7 +602,8 @@ LOCAL_C_INCLUDES := \
./jni/boringssl/include \
./jni/breakpad/common/android/include \
./jni/breakpad \
./jni/ffmpeg/include
./jni/ffmpeg/include \
./jni/intro
LOCAL_SRC_FILES += \
./libyuv/source/compare_common.cc \
@ -660,6 +661,7 @@ LOCAL_SRC_FILES += \
./utils.c \
./image.c \
./video.c \
./intro/IntroRenderer.c \
./gifvideo.cpp \
./SqliteWrapper.cpp \
./TgNetWrapper.cpp \

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,113 @@
#ifndef TMESSAGES_INTRO_RENDERER_H
#define TMESSAGES_INTRO_RENDERER_H
#include <GLES2/gl2.h>
extern float scale_factor;
extern int width, height;
extern int y_offset_absolute;
typedef enum {
Default = 0,
EaseIn = 1,
EaseOut = 2,
EaseInEaseOut = 3,
Linear = 4,
Sin = 5,
EaseOutBounce,
TIMING_NUM
} timing_type;
typedef float vec2[2];
typedef float vec4[4];
typedef vec4 mat4x4[4];
typedef enum {NORMAL, NORMAL_ONE, RED, BLUE, LIGHT_RED, LIGHT_BLUE} texture_program_type;
typedef struct {
float x;
float y;
} CPoint;
typedef struct {
float width;
float height;
} CSize;
typedef struct {
float x;
float y;
float z;
} xyz;
typedef struct {
GLuint program;
GLint a_position_location;
GLint a_texture_coordinates_location;
GLint u_mvp_matrix_location;
GLint u_texture_unit_location;
GLint u_alpha_loaction;
} TextureProgram;
typedef struct {
GLuint program;
GLint a_position_location;
GLint u_mvp_matrix_location;
GLint u_color_location;
GLint u_alpha_loaction;
} ColorProgram;
typedef struct {
float side_length;
float start_angle;
float end_angle;
float angle;
CSize size;
float radius;
float width;
} VarParams;
typedef struct {
size_t datasize;
int round_count;
GLenum triangle_mode;
int is_star;
} ConstParams;
typedef struct {
xyz anchor;
xyz position;
float rotation;
xyz scale;
} LayerParams;
typedef struct {
xyz anchor;
xyz position;
float rotation;
xyz scale;
float alpha;
VarParams var_params;
ConstParams const_params;
LayerParams layer_params;
} Params;
typedef struct {
vec4 color;
CPoint *data;
GLuint buffer;
int num_points;
Params params;
} Shape;
typedef struct {
GLuint texture;
CPoint *data;
GLuint buffer;
int num_points;
Params params;
} TexturedShape;
#endif

View File

@ -72,6 +72,37 @@ JNIEXPORT jint Java_org_telegram_messenger_Utilities_aesCtrDecryption(JNIEnv *en
return num;
}
JNIEXPORT jint Java_org_telegram_messenger_Utilities_aesCtrDecryptionByteArray(JNIEnv *env, jclass class, jbyteArray buffer, jbyteArray key, jbyteArray iv, int offset, int length, int fileOffset) {
unsigned char *bufferBuff = (unsigned char *)(*env)->GetByteArrayElements(env, buffer, NULL);
unsigned char *keyBuff = (unsigned char *)(*env)->GetByteArrayElements(env, key, NULL);
unsigned char *ivBuff = (unsigned char *)(*env)->GetByteArrayElements(env, iv, NULL);
AES_KEY akey;
uint8_t count[16];
AES_set_encrypt_key(keyBuff, 32 * 8, &akey);
unsigned int num = (unsigned int) (fileOffset % 16);
int o = fileOffset / 16;
ivBuff[15] = (uint8_t) (o & 0xff);
ivBuff[14] = (uint8_t) ((o >> 8) & 0xff);
ivBuff[13] = (uint8_t) ((o >> 16) & 0xff);
ivBuff[12] = (uint8_t) ((o >> 24) & 0xff);
AES_encrypt(ivBuff, count, &akey);
o = (fileOffset + 15) / 16;
ivBuff[15] = (uint8_t) (o & 0xff);
ivBuff[14] = (uint8_t) ((o >> 8) & 0xff);
ivBuff[13] = (uint8_t) ((o >> 16) & 0xff);
ivBuff[12] = (uint8_t) ((o >> 24) & 0xff);
AES_ctr128_encrypt(bufferBuff + offset, bufferBuff + offset, length, &akey, ivBuff, count, &num);
(*env)->ReleaseByteArrayElements(env, key, keyBuff, JNI_ABORT);
(*env)->ReleaseByteArrayElements(env, iv, ivBuff, JNI_ABORT);
(*env)->ReleaseByteArrayElements(env, buffer, bufferBuff, 0);
return num;
}
JNIEXPORT jstring Java_org_telegram_messenger_Utilities_readlink(JNIEnv *env, jclass class, jstring path) {
static char buf[1000];
char *fileName = (*env)->GetStringUTFChars(env, path, NULL);

View File

@ -162,6 +162,7 @@
</activity>
<activity
android:name="org.telegram.ui.IntroActivity"
android:launchMode="singleTask"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
</activity>
<activity
@ -179,15 +180,6 @@
android:resizeableActivity="false"
android:windowSoftInputMode="adjustResize|stateHidden">
</activity>
<activity
android:name=".GoogleVoiceClientActivity"
android:exported="true">
<intent-filter>
<action android:name="com.google.android.voicesearch.SEND_MESSAGE_TO_CONTACTS" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
<activity
android:name="org.telegram.ui.VoIPActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
@ -266,7 +258,6 @@
<service android:name=".ClearCacheService" android:exported="false"/>
<service android:name=".VideoEncodingService" android:enabled="true"/>
<service android:name=".voip.VoIPService" android:enabled="true"/>
<service android:name=".GoogleVoiceClientService"/>
<service android:name=".MusicPlayerService" android:exported="true" android:enabled="true"/>
<service android:name=".MusicBrowserService" android:exported="true">
<intent-filter>

View File

@ -60,6 +60,8 @@ import android.view.Display;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.OvershootInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.webkit.MimeTypeMap;
import android.widget.EdgeEffect;
@ -120,6 +122,9 @@ public class AndroidUtilities {
public static boolean usingHardwareInput;
public static boolean isInMultiwindow;
public static DecelerateInterpolator decelerateInterpolator = new DecelerateInterpolator();
public static OvershootInterpolator overshootInterpolator = new OvershootInterpolator();
private static Boolean isTablet = null;
private static int adjustOwnerClassGuid = 0;
@ -637,11 +642,7 @@ public class AndroidUtilities {
public static int getPhotoSize() {
if (photoSize == null) {
if (Build.VERSION.SDK_INT >= 16) {
photoSize = 1280;
} else {
photoSize = 800;
}
photoSize = 1280;
}
return photoSize;
}
@ -1134,7 +1135,8 @@ public class AndroidUtilities {
ForegroundDetector.getInstance().resetBackgroundVar();
}
return UserConfig.passcodeHash.length() > 0 && wasInBackground &&
(UserConfig.appLocked || UserConfig.autoLockIn != 0 && UserConfig.lastPauseTime != 0 && !UserConfig.appLocked && (UserConfig.lastPauseTime + UserConfig.autoLockIn) <= ConnectionsManager.getInstance().getCurrentTime());
(UserConfig.appLocked || UserConfig.autoLockIn != 0 && UserConfig.lastPauseTime != 0 && !UserConfig.appLocked &&
(UserConfig.lastPauseTime + UserConfig.autoLockIn) <= ConnectionsManager.getInstance().getCurrentTime() || ConnectionsManager.getInstance().getCurrentTime() + 5 < UserConfig.lastPauseTime);
}
public static void shakeView(final View view, final float x, final int num) {

View File

@ -11,8 +11,8 @@ package org.telegram.messenger;
public class BuildVars {
public static boolean DEBUG_VERSION = false;
public static boolean DEBUG_PRIVATE_VERSION = false;
public static int BUILD_VERSION = 1030;
public static String BUILD_VERSION_STRING = "4.1";
public static int BUILD_VERSION = 1040;
public static String BUILD_VERSION_STRING = "4.2";
public static int APP_ID = 0; //obtain your own APP_ID at https://core.telegram.org/api/obtaining_api_id
public static String APP_HASH = ""; //obtain your own APP_HASH at https://core.telegram.org/api/obtaining_api_id
public static String HOCKEY_APP_HASH = "your-hockeyapp-api-key-here";

View File

@ -14,4 +14,5 @@ public class DownloadObject {
public TLObject object;
public int type;
public long id;
public boolean secret;
}

View File

@ -18,6 +18,8 @@ import java.io.RandomAccessFile;
import java.io.File;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class FileLoadOperation {
@ -37,6 +39,7 @@ public class FileLoadOperation {
private final static int downloadChunkSize = 1024 * 32;
private final static int downloadChunkSizeBig = 1024 * 128;
private final static int cdnChunkCheckSize = 1024 * 128;
private final static int maxDownloadRequests = 4;
private final static int maxDownloadRequestsBig = 2;
private final static int bigFileSizeFrom = 1024 * 1024;
@ -57,12 +60,23 @@ public class FileLoadOperation {
private int requestsCount;
private int renameRetryCount;
private boolean encryptFile;
private HashMap<Integer, TLRPC.TL_cdnFileHash> cdnHashes;
private byte[] encryptKey;
private byte[] encryptIv;
private boolean isCdn;
private byte[] cdnIv;
private byte[] cdnKey;
private byte[] cdnToken;
private int cdnDatacenterId;
private boolean reuploadingCdn;
private int lastCheckedCdnPart;
private RandomAccessFile fileReadStream;
private byte[] cdnCheckBytes;
private boolean requestingCdnOffsets;
private int nextDownloadOffset;
private ArrayList<RequestInfo> requestInfos;
@ -190,6 +204,10 @@ public class FileLoadOperation {
}
}
public void setEncryptFile(boolean value) {
encryptFile = value;
}
public void setForceRequest(boolean forceRequest) {
isForceRequest = forceRequest;
}
@ -233,10 +251,18 @@ public class FileLoadOperation {
String fileNameIv = null;
if (webLocation != null) {
String md5 = Utilities.MD5(webLocation.url);
fileNameTemp = md5 + ".temp";
fileNameFinal = md5 + "." + ext;
if (key != null) {
fileNameIv = md5 + ".iv";
if (encryptFile) {
fileNameTemp = md5 + ".temp.enc";
fileNameFinal = md5 + "." + ext + ".enc";
if (key != null) {
fileNameIv = md5 + ".iv.enc";
}
} else {
fileNameTemp = md5 + ".temp";
fileNameFinal = md5 + "." + ext;
if (key != null) {
fileNameIv = md5 + ".iv";
}
}
} else {
if (location.volume_id != 0 && location.local_id != 0) {
@ -245,21 +271,36 @@ public class FileLoadOperation {
return false;
}
fileNameTemp = location.volume_id + "_" + location.local_id + ".temp";
fileNameFinal = location.volume_id + "_" + location.local_id + "." + ext;
if (key != null) {
fileNameIv = location.volume_id + "_" + location.local_id + ".iv";
if (encryptFile) {
fileNameTemp = location.volume_id + "_" + location.local_id + ".temp.enc";
fileNameFinal = location.volume_id + "_" + location.local_id + "." + ext + ".enc";
if (key != null) {
fileNameIv = location.volume_id + "_" + location.local_id + ".iv.enc";
}
} else {
fileNameTemp = location.volume_id + "_" + location.local_id + ".temp";
fileNameFinal = location.volume_id + "_" + location.local_id + "." + ext;
if (key != null) {
fileNameIv = location.volume_id + "_" + location.local_id + ".iv";
}
}
} else {
if (datacenter_id == 0 || location.id == 0) {
onFail(true, 0);
return false;
}
fileNameTemp = datacenter_id + "_" + location.id + ".temp";
fileNameFinal = datacenter_id + "_" + location.id + ext;
if (key != null) {
fileNameIv = datacenter_id + "_" + location.id + ".iv";
if (encryptFile) {
fileNameTemp = datacenter_id + "_" + location.id + ".temp.enc";
fileNameFinal = datacenter_id + "_" + location.id + ext + ".enc";
if (key != null) {
fileNameIv = datacenter_id + "_" + location.id + ".iv.enc";
}
} else {
fileNameTemp = datacenter_id + "_" + location.id + ".temp";
fileNameFinal = datacenter_id + "_" + location.id + ext;
if (key != null) {
fileNameIv = datacenter_id + "_" + location.id + ".iv";
}
}
}
}
@ -277,9 +318,43 @@ public class FileLoadOperation {
if (!cacheFileFinal.exists()) {
cacheFileTemp = new File(tempPath, fileNameTemp);
boolean newKeyGenerated = false;
if (encryptFile) {
File keyFile = new File(FileLoader.getInternalCacheDir(), fileNameFinal + ".key");
try {
RandomAccessFile file = new RandomAccessFile(keyFile, "rws");
long len = keyFile.length();
encryptKey = new byte[32];
encryptIv = new byte[16];
if (len > 0 && len % 48 == 0) {
file.read(encryptKey, 0, 32);
file.read(encryptIv, 0, 16);
} else {
Utilities.random.nextBytes(encryptKey);
Utilities.random.nextBytes(encryptIv);
file.write(encryptKey);
file.write(encryptIv);
newKeyGenerated = true;
}
try {
file.getChannel().close();
} catch (Exception e) {
FileLog.e(e);
}
file.close();
} catch (Exception e) {
FileLog.e(e);
}
}
if (cacheFileTemp.exists()) {
downloadedBytes = (int) cacheFileTemp.length();
nextDownloadOffset = downloadedBytes = downloadedBytes / currentDownloadChunkSize * currentDownloadChunkSize;
if (newKeyGenerated) {
cacheFileTemp.delete();
} else {
downloadedBytes = (int) cacheFileTemp.length();
nextDownloadOffset = downloadedBytes = downloadedBytes / currentDownloadChunkSize * currentDownloadChunkSize;
}
}
if (BuildVars.DEBUG_VERSION) {
@ -290,11 +365,13 @@ public class FileLoadOperation {
cacheIvTemp = new File(tempPath, fileNameIv);
try {
fiv = new RandomAccessFile(cacheIvTemp, "rws");
long len = cacheIvTemp.length();
if (len > 0 && len % 32 == 0) {
fiv.read(iv, 0, 32);
} else {
downloadedBytes = 0;
if (!newKeyGenerated) {
long len = cacheIvTemp.length();
if (len > 0 && len % 32 == 0) {
fiv.read(iv, 0, 32);
} else {
downloadedBytes = 0;
}
}
} catch (Exception e) {
FileLog.e(e);
@ -373,6 +450,19 @@ public class FileLoadOperation {
} catch (Exception e) {
FileLog.e(e);
}
try {
if (fileReadStream != null) {
try {
fileReadStream.getChannel().close();
} catch (Exception e) {
FileLog.e(e);
}
fileReadStream.close();
fileReadStream = null;
}
} catch (Exception e) {
FileLog.e(e);
}
try {
if (fiv != null) {
@ -451,24 +541,76 @@ public class FileLoadOperation {
}
}
private void delayRequestInfo(RequestInfo requestInfo) {
delayedRequestInfos.add(requestInfo);
if (requestInfo.response != null) {
requestInfo.response.disableFree = true;
} else if (requestInfo.responseWeb != null) {
requestInfo.responseWeb.disableFree = true;
} else if (requestInfo.responseCdn != null) {
requestInfo.responseCdn.disableFree = true;
}
}
private void requestFileOffsets(int offset) {
if (requestingCdnOffsets) {
return;
}
requestingCdnOffsets = true;
TLRPC.TL_upload_getCdnFileHashes req = new TLRPC.TL_upload_getCdnFileHashes();
req.file_token = cdnToken;
req.offset = offset;
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error != null) {
onFail(false, 0);
} else {
requestingCdnOffsets = false;
TLRPC.Vector vector = (TLRPC.Vector) response;
if (!vector.objects.isEmpty()) {
if (cdnHashes == null) {
cdnHashes = new HashMap<>();
}
for (int a = 0; a < vector.objects.size(); a++) {
TLRPC.TL_cdnFileHash hash = (TLRPC.TL_cdnFileHash) vector.objects.get(a);
cdnHashes.put(hash.offset, hash);
}
}
for (int a = 0; a < delayedRequestInfos.size(); a++) {
RequestInfo delayedRequestInfo = delayedRequestInfos.get(a);
if (downloadedBytes == delayedRequestInfo.offset) {
delayedRequestInfos.remove(a);
processRequestResult(delayedRequestInfo, null);
if (delayedRequestInfo.response != null) {
delayedRequestInfo.response.disableFree = false;
delayedRequestInfo.response.freeResources();
} else if (delayedRequestInfo.responseWeb != null) {
delayedRequestInfo.responseWeb.disableFree = false;
delayedRequestInfo.responseWeb.freeResources();
} else if (delayedRequestInfo.responseCdn != null) {
delayedRequestInfo.responseCdn.disableFree = false;
delayedRequestInfo.responseCdn.freeResources();
}
break;
}
}
}
}
}, null, null, 0, datacenter_id, ConnectionsManager.ConnectionTypeGeneric, true);
}
private void processRequestResult(RequestInfo requestInfo, TLRPC.TL_error error) {
if (state != stateDownloading) {
return;
}
requestInfos.remove(requestInfo);
if (error == null) {
try {
if (downloadedBytes != requestInfo.offset) {
if (state == stateDownloading) {
delayedRequestInfos.add(requestInfo);
if (requestInfo.response != null) {
requestInfo.response.disableFree = true;
} else if (requestInfo.responseWeb != null) {
requestInfo.responseWeb.disableFree = true;
} else if (requestInfo.responseCdn != null) {
requestInfo.responseCdn.disableFree = true;
}
}
delayRequestInfo(requestInfo);
return;
}
NativeByteBuffer bytes;
if (requestInfo.response != null) {
bytes = requestInfo.response.bytes;
@ -483,6 +625,18 @@ public class FileLoadOperation {
onFinishLoadingFile(true);
return;
}
int currentBytesSize = bytes.limit();
if (isCdn) {
int cdnCheckPart = (downloadedBytes + currentBytesSize) / cdnChunkCheckSize;
int fileOffset = (cdnCheckPart - (lastCheckedCdnPart != cdnCheckPart ? 1 : 0)) * cdnChunkCheckSize;
TLRPC.TL_cdnFileHash hash = cdnHashes != null ? cdnHashes.get(fileOffset) : null;
if (hash == null) {
delayRequestInfo(requestInfo);
requestFileOffsets(fileOffset);
return;
}
}
if (requestInfo.responseCdn != null) {
int offset = requestInfo.offset / 16;
cdnIv[15] = (byte) (offset & 0xff);
@ -491,7 +645,7 @@ public class FileLoadOperation {
cdnIv[12] = (byte) ((offset >> 24) & 0xff);
Utilities.aesCtrDecryption(bytes.buffer, cdnKey, cdnIv, 0, bytes.limit());
}
int currentBytesSize = bytes.limit();
downloadedBytes += currentBytesSize;
boolean finishedDownloading = currentBytesSize != currentDownloadChunkSize || (totalBytesCount == downloadedBytes || downloadedBytes % currentDownloadChunkSize != 0) && (totalBytesCount <= 0 || totalBytesCount <= downloadedBytes);
@ -501,9 +655,49 @@ public class FileLoadOperation {
bytes.limit(bytes.limit() - bytesCountPadding);
}
}
if (fileOutputStream != null) {
FileChannel channel = fileOutputStream.getChannel();
channel.write(bytes.buffer);
if (encryptFile) {
int offset = requestInfo.offset / 16;
encryptIv[15] = (byte) (offset & 0xff);
encryptIv[14] = (byte) ((offset >> 8) & 0xff);
encryptIv[13] = (byte) ((offset >> 16) & 0xff);
encryptIv[12] = (byte) ((offset >> 24) & 0xff);
Utilities.aesCtrDecryption(bytes.buffer, encryptKey, encryptIv, 0, bytes.limit());
}
FileChannel channel = fileOutputStream.getChannel();
channel.write(bytes.buffer);
if (isCdn) {
int cdnCheckPart = downloadedBytes / cdnChunkCheckSize;
if (cdnCheckPart != lastCheckedCdnPart || finishedDownloading) {
fileOutputStream.getFD().sync();
int fileOffset = (cdnCheckPart - (lastCheckedCdnPart != cdnCheckPart ? 1 : 0)) * cdnChunkCheckSize;
TLRPC.TL_cdnFileHash hash = cdnHashes.get(fileOffset);
if (fileReadStream == null) {
cdnCheckBytes = new byte[1024 * 128];
fileReadStream = new RandomAccessFile(cacheFileTemp, "r");
if (fileOffset != 0) {
fileReadStream.seek(fileOffset);
}
}
int count;
if (lastCheckedCdnPart != cdnCheckPart) {
count = cdnChunkCheckSize;
} else {
count = downloadedBytes - cdnCheckPart * cdnChunkCheckSize;
}
fileReadStream.readFully(cdnCheckBytes, 0, count);
byte[] sha256 = Utilities.computeSHA256(cdnCheckBytes, 0, count);
if (!Arrays.equals(sha256, hash.hash)) {
if (location != null) {
FileLog.e("invalid cdn hash " + location + " id = " + location.id + " local_id = " + location.local_id + " access_hash = " + location.access_hash + " volume_id = " + location.volume_id + " secret = " + location.secret);
} else if (webLocation != null) {
FileLog.e("invalid cdn hash " + webLocation + " id = " + webLocation.url + " access_hash = " + webLocation.access_hash);
}
onFail(false, 0);
cacheFileTemp.delete();
return;
}
lastCheckedCdnPart = cdnCheckPart;
}
}
if (fiv != null) {
fiv.seek(0);
@ -692,6 +886,15 @@ public class FileLoadOperation {
}
if (response instanceof TLRPC.TL_upload_fileCdnRedirect) {
TLRPC.TL_upload_fileCdnRedirect res = (TLRPC.TL_upload_fileCdnRedirect) response;
if (!res.cdn_file_hashes.isEmpty()) {
if (cdnHashes == null) {
cdnHashes = new HashMap<>();
}
for (int a = 0; a < res.cdn_file_hashes.size(); a++) {
TLRPC.TL_cdnFileHash hash = res.cdn_file_hashes.get(a);
cdnHashes.put(hash.offset, hash);
}
}
if (res.encryption_iv == null || res.encryption_key == null || res.encryption_iv.length != 16 || res.encryption_key.length != 32) {
error = new TLRPC.TL_error();
error.text = "bad redirect response";
@ -719,6 +922,16 @@ public class FileLoadOperation {
public void run(TLObject response, TLRPC.TL_error error) {
reuploadingCdn = false;
if (error == null) {
TLRPC.Vector vector = (TLRPC.Vector) response;
if (!vector.objects.isEmpty()) {
if (cdnHashes == null) {
cdnHashes = new HashMap<>();
}
for (int a = 0; a < vector.objects.size(); a++) {
TLRPC.TL_cdnFileHash hash = (TLRPC.TL_cdnFileHash) vector.objects.get(a);
cdnHashes.put(hash.offset, hash);
}
}
startDownloadRequest();
} else {
if (error.text.equals("FILE_TOKEN_INVALID") || error.text.equals("REQUEST_TOKEN_INVALID")) {
@ -753,7 +966,6 @@ public class FileLoadOperation {
}
processRequestResult(requestInfo, error);
}
}
}, null, null, flags, isCdn ? cdnDatacenterId : datacenter_id, connectionType, isLast);
requestsCount++;

View File

@ -340,23 +340,32 @@ public class FileLoader {
return result[0];
}
public void loadFile(TLRPC.PhotoSize photo, String ext, boolean cacheOnly) {
loadFile(null, null, photo.location, ext, photo.size, false, cacheOnly || (photo != null && photo.size == 0 || photo.location.key != null));
public void loadFile(TLRPC.PhotoSize photo, String ext, int cacheType) {
if (cacheType == 0 && (photo != null && photo.size == 0 || photo.location.key != null)) {
cacheType = 1;
}
loadFile(null, null, photo.location, ext, photo.size, false, cacheType);
}
public void loadFile(TLRPC.Document document, boolean force, boolean cacheOnly) {
loadFile(document, null, null, null, 0, force, cacheOnly || document != null && document.key != null);
public void loadFile(TLRPC.Document document, boolean force, int cacheType) {
if (cacheType == 0 && (document != null && document.key != null)) {
cacheType = 1;
}
loadFile(document, null, null, null, 0, force, cacheType);
}
public void loadFile(TLRPC.TL_webDocument document, boolean force, boolean cacheOnly) {
loadFile(null, document, null, null, 0, force, cacheOnly);
public void loadFile(TLRPC.TL_webDocument document, boolean force, int cacheType) {
loadFile(null, document, null, null, 0, force, cacheType);
}
public void loadFile(TLRPC.FileLocation location, String ext, int size, boolean cacheOnly) {
loadFile(null, null, location, ext, size, true, cacheOnly || size == 0 || (location != null && location.key != null));
public void loadFile(TLRPC.FileLocation location, String ext, int size, int cacheType) {
if (cacheType == 0 && (size == 0 || location != null && location.key != null)) {
cacheType = 1;
}
loadFile(null, null, location, ext, size, true, cacheType);
}
private void loadFile(final TLRPC.Document document, final TLRPC.TL_webDocument webDocument, final TLRPC.FileLocation location, final String locationExt, final int locationSize, final boolean force, final boolean cacheOnly) {
private void loadFile(final TLRPC.Document document, final TLRPC.TL_webDocument webDocument, final TLRPC.FileLocation location, final String locationExt, final int locationSize, final boolean force, final int cacheType) {
fileLoaderQueue.postRunnable(new Runnable() {
@Override
public void run() {
@ -424,8 +433,10 @@ public class FileLoader {
type = MEDIA_DIR_DOCUMENT;
}
}
if (!cacheOnly) {
if (cacheType == 0) {
storeDir = getDirectory(type);
} else if (cacheType == 2) {
operation.setEncryptFile(true);
}
operation.setPaths(storeDir, tempDir);
@ -668,13 +679,13 @@ public class FileLoader {
}
} else {
if (message.media instanceof TLRPC.TL_messageMediaDocument) {
return getPathToAttach(message.media.document);
return getPathToAttach(message.media.document, message.media.ttl_seconds != 0);
} else if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
ArrayList<TLRPC.PhotoSize> sizes = message.media.photo.sizes;
if (sizes.size() > 0) {
TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize());
if (sizeFull != null) {
return getPathToAttach(sizeFull);
return getPathToAttach(sizeFull, message.media.ttl_seconds != 0);
}
}
} else if (message.media instanceof TLRPC.TL_messageMediaWebPage) {
@ -819,6 +830,10 @@ public class FileLoader {
return "";
}
public static File getInternalCacheDir() {
return ApplicationLoader.applicationContext.getCacheDir();
}
public static String getDocumentExtension(TLRPC.Document document) {
String fileName = getDocumentFileName(document);
int idx = fileName.lastIndexOf('.');
@ -911,7 +926,24 @@ public class FileLoader {
public void run() {
for (int a = 0; a < files.size(); a++) {
File file = files.get(a);
if (file.exists()) {
File encrypted = new File(file.getAbsolutePath() + ".enc");
if (encrypted.exists()) {
try {
if (!encrypted.delete()) {
encrypted.deleteOnExit();
}
} catch (Exception e) {
FileLog.e(e);
}
try {
File key = new File(FileLoader.getInternalCacheDir(), file.getName() + ".enc.key");
if (!key.delete()) {
key.deleteOnExit();
}
} catch (Exception e) {
FileLog.e(e);
}
} else if (file.exists()) {
try {
if (!file.delete()) {
file.deleteOnExit();

View File

@ -25,6 +25,7 @@ import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import org.telegram.messenger.secretmedia.EncryptedFileInputStream;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
@ -631,6 +632,7 @@ public class ImageLoader {
boolean mediaIsVideo = false;
Bitmap image = null;
File cacheFileFinal = cacheImage.finalFilePath;
boolean inEncryptedFile = cacheImage.encryptionKeyPath != null && cacheFileFinal != null && cacheFileFinal.getAbsolutePath().endsWith(".enc");
boolean canDeleteFile = true;
boolean useNativeWebpLoaded = false;
@ -711,9 +713,18 @@ public class ImageLoader {
bytesThumb = data = new byte[len];
}
f.readFully(data, 0, len);
f.close();
if (inEncryptedFile) {
EncryptedFileInputStream.decryptBytesWithKeyFile(data, 0, len, cacheImage.encryptionKeyPath);
}
image = BitmapFactory.decodeByteArray(data, 0, len, opts);
} else {
FileInputStream is = new FileInputStream(cacheFileFinal);
FileInputStream is;
if (inEncryptedFile) {
is = new EncryptedFileInputStream(cacheFileFinal, cacheImage.encryptionKeyPath);
} else {
is = new FileInputStream(cacheFileFinal);
}
image = BitmapFactory.decodeStream(is, null, opts);
is.close();
}
@ -808,7 +819,12 @@ public class ImageLoader {
MediaStore.Images.Thumbnails.getThumbnail(ApplicationLoader.applicationContext.getContentResolver(), mediaId, MediaStore.Images.Thumbnails.MINI_KIND, opts);
}
} else {
FileInputStream is = new FileInputStream(cacheFileFinal);
FileInputStream is;
if (inEncryptedFile) {
is = new EncryptedFileInputStream(cacheFileFinal, cacheImage.encryptionKeyPath);
} else {
is = new FileInputStream(cacheFileFinal);
}
image = BitmapFactory.decodeStream(is, null, opts);
is.close();
}
@ -834,7 +850,11 @@ public class ImageLoader {
scaleFactor = 1;
}
opts.inJustDecodeBounds = false;
opts.inSampleSize = (int) scaleFactor;
int sample = 1;
do {
sample *= 2;
} while (sample * 2 < scaleFactor);
opts.inSampleSize = sample;
}
synchronized (sync) {
if (isCancelled) {
@ -880,9 +900,18 @@ public class ImageLoader {
bytes = data = new byte[len];
}
f.readFully(data, 0, len);
f.close();
if (inEncryptedFile) {
EncryptedFileInputStream.decryptBytesWithKeyFile(data, 0, len, cacheImage.encryptionKeyPath);
}
image = BitmapFactory.decodeByteArray(data, 0, len, opts);
} else {
FileInputStream is = new FileInputStream(cacheFileFinal);
FileInputStream is;
if (inEncryptedFile) {
is = new EncryptedFileInputStream(cacheFileFinal, cacheImage.encryptionKeyPath);
} else {
is = new FileInputStream(cacheFileFinal);
}
image = BitmapFactory.decodeStream(is, null, opts);
is.close();
}
@ -916,8 +945,8 @@ public class ImageLoader {
Utilities.pinBitmap(image);
}
}
} catch (Throwable e) {
//don't promt
} catch (Throwable ignore) {
}
}
Thread.interrupted();
@ -979,6 +1008,8 @@ public class ImageLoader {
protected File tempFilePath;
protected boolean thumb;
protected File encryptionKeyPath;
protected String httpUrl;
protected HttpImageTask httpTask;
protected CacheOutTask cacheTask;
@ -1611,7 +1642,7 @@ public class ImageLoader {
}
}
private void createLoadOperationForImageReceiver(final ImageReceiver imageReceiver, final String key, final String url, final String ext, final TLObject imageLocation, final String httpLocation, final String filter, final int size, final boolean cacheOnly, final int thumb) {
private void createLoadOperationForImageReceiver(final ImageReceiver imageReceiver, final String key, final String url, final String ext, final TLObject imageLocation, final String httpLocation, final String filter, final int size, final int cacheType, final int thumb) {
if (imageReceiver == null || url == null || key == null) {
return;
}
@ -1658,6 +1689,7 @@ public class ImageLoader {
boolean onlyCache = false;
boolean isQuality = false;
File cacheFile = null;
boolean cacheFileExists = false;
if (httpLocation != null) {
if (!httpLocation.startsWith("http")) {
@ -1681,6 +1713,8 @@ public class ImageLoader {
cacheFile = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), "q_" + url);
if (!cacheFile.exists()) {
cacheFile = null;
} else {
cacheFileExists = true;
}
}
@ -1723,8 +1757,13 @@ public class ImageLoader {
}
if (cacheFile == null) {
if (cacheOnly || size == 0 || httpLocation != null || isEncrypted) {
if (cacheType != 0 || size == 0 || httpLocation != null || isEncrypted) {
cacheFile = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), url);
if (cacheFile.exists()) {
cacheFileExists = true;
} else if (cacheType == 2) {
cacheFile = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), url + ".enc");
}
} else if (imageLocation instanceof TLRPC.Document) {
if (MessageObject.isVideoDocument((TLRPC.Document) imageLocation)) {
cacheFile = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_VIDEO), url);
@ -1743,8 +1782,11 @@ public class ImageLoader {
img.filter = filter;
img.httpUrl = httpLocation;
img.ext = ext;
if (cacheType == 2) {
img.encryptionKeyPath = new File(FileLoader.getInternalCacheDir(), url + ".enc.key");
}
img.addImageReceiver(imageReceiver, key, filter);
if (onlyCache || cacheFile.exists()) {
if (onlyCache || cacheFileExists || cacheFile.exists()) {
img.finalFilePath = cacheFile;
img.cacheTask = new CacheOutTask(img);
imageLoadingByKeys.put(key, img);
@ -1760,11 +1802,15 @@ public class ImageLoader {
if (httpLocation == null) {
if (imageLocation instanceof TLRPC.FileLocation) {
TLRPC.FileLocation location = (TLRPC.FileLocation) imageLocation;
FileLoader.getInstance().loadFile(location, ext, size, size == 0 || location.key != null || cacheOnly);
int localCacheType = cacheType;
if (localCacheType == 0 && (size == 0 || location.key != null)) {
localCacheType = 1;
}
FileLoader.getInstance().loadFile(location, ext, size, localCacheType);
} else if (imageLocation instanceof TLRPC.Document) {
FileLoader.getInstance().loadFile((TLRPC.Document) imageLocation, true, cacheOnly);
FileLoader.getInstance().loadFile((TLRPC.Document) imageLocation, true, cacheType);
} else if (imageLocation instanceof TLRPC.TL_webDocument) {
FileLoader.getInstance().loadFile((TLRPC.TL_webDocument) imageLocation, true, cacheOnly);
FileLoader.getInstance().loadFile((TLRPC.TL_webDocument) imageLocation, true, cacheType);
}
} else {
String file = Utilities.MD5(httpLocation);
@ -1787,13 +1833,15 @@ public class ImageLoader {
return;
}
boolean imageSet = false;
String key = imageReceiver.getKey();
if (key != null) {
BitmapDrawable bitmapDrawable = memCache.get(key);
if (bitmapDrawable != null) {
cancelLoadingForImageReceiver(imageReceiver, 0);
imageReceiver.setImageBitmapByKey(bitmapDrawable, key, false, true);
imageSet = true;
if (!imageReceiver.isForcePreview()) {
imageReceiver.setImageBitmapByKey(bitmapDrawable, key, false, true);
return;
}
}
@ -1805,6 +1853,9 @@ public class ImageLoader {
if (bitmapDrawable != null) {
imageReceiver.setImageBitmapByKey(bitmapDrawable, thumbKey, true, true);
cancelLoadingForImageReceiver(imageReceiver, 1);
if (imageSet && imageReceiver.isForcePreview()) {
return;
}
thumbSet = true;
}
}
@ -1892,11 +1943,15 @@ public class ImageLoader {
}
if (httpLocation != null) {
createLoadOperationForImageReceiver(imageReceiver, thumbKey, thumbUrl, ext, thumbLocation, null, thumbFilter, 0, true, thumbSet ? 2 : 1);
createLoadOperationForImageReceiver(imageReceiver, key, url, ext, null, httpLocation, filter, 0, true, 0);
createLoadOperationForImageReceiver(imageReceiver, thumbKey, thumbUrl, ext, thumbLocation, null, thumbFilter, 0, 1, thumbSet ? 2 : 1);
createLoadOperationForImageReceiver(imageReceiver, key, url, ext, null, httpLocation, filter, 0, 1, 0);
} else {
createLoadOperationForImageReceiver(imageReceiver, thumbKey, thumbUrl, ext, thumbLocation, null, thumbFilter, 0, true, thumbSet ? 2 : 1);
createLoadOperationForImageReceiver(imageReceiver, key, url, ext, imageLocation, null, filter, imageReceiver.getSize(), saveImageToCache || imageReceiver.getCacheOnly(), 0);
int cacheType = imageReceiver.getCacheType();
if (cacheType == 0 && saveImageToCache) {
cacheType = 1;
}
createLoadOperationForImageReceiver(imageReceiver, thumbKey, thumbUrl, ext, thumbLocation, null, thumbFilter, 0, cacheType == 0 ? 1 : cacheType, thumbSet ? 2 : 1);
createLoadOperationForImageReceiver(imageReceiver, key, url, ext, imageLocation, null, filter, imageReceiver.getSize(), cacheType, 0);
}
}
@ -1943,6 +1998,7 @@ public class ImageLoader {
cacheImage.httpUrl = img.httpUrl;
cacheImage.thumb = img.thumb;
cacheImage.ext = img.ext;
cacheImage.encryptionKeyPath = img.encryptionKeyPath;
cacheImage.cacheTask = new CacheOutTask(cacheImage);
cacheImage.filter = filter;
cacheImage.animatedFile = img.animatedFile;
@ -2135,8 +2191,8 @@ public class ImageLoader {
matrix.postRotate(270);
break;
}
} catch (Throwable e) {
FileLog.e(e);
} catch (Throwable ignore) {
}
}
@ -2359,8 +2415,31 @@ public class ImageLoader {
UserConfig.lastLocalId--;
}
File file = FileLoader.getPathToAttach(photoSize, true);
boolean isEncrypted = false;
if (MessageObject.shouldEncryptPhotoOrVideo(message)) {
file = new File(file.getAbsolutePath() + ".enc");
isEncrypted = true;
}
if (!file.exists()) {
try {
if (isEncrypted) {
File keyPath = new File(FileLoader.getInternalCacheDir(), file.getName() + ".key");
RandomAccessFile keyFile = new RandomAccessFile(keyPath, "rws");
long len = keyFile.length();
byte[] encryptKey = new byte[32];
byte[] encryptIv = new byte[16];
if (len > 0 && len % 48 == 0) {
keyFile.read(encryptKey, 0, 32);
keyFile.read(encryptIv, 0, 16);
} else {
Utilities.random.nextBytes(encryptKey);
Utilities.random.nextBytes(encryptIv);
keyFile.write(encryptKey);
keyFile.write(encryptIv);
}
keyFile.close();
Utilities.aesCtrDecryptionByteArray(photoSize.bytes, encryptKey, encryptIv, 0, photoSize.bytes.length, 0);
}
RandomAccessFile writeFile = new RandomAccessFile(file, "rws");
writeFile.write(photoSize.bytes);
writeFile.close();

View File

@ -41,7 +41,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
public TLRPC.FileLocation thumbLocation;
public String thumbFilter;
public int size;
public boolean cacheOnly;
public int cacheType;
public String ext;
}
@ -63,7 +63,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
private String currentExt;
private TLRPC.FileLocation currentThumbLocation;
private int currentSize;
private boolean currentCacheOnly;
private int currentCacheType;
private Drawable currentImage;
private Drawable currentThumb;
private Drawable staticThumb;
@ -79,6 +79,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
private boolean isVisible = true;
private boolean isAspectFit;
private boolean forcePreview;
private boolean forceCrossfade;
private int roundRadius;
private BitmapShader bitmapShader;
private BitmapShader bitmapShaderThumb;
@ -94,6 +95,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
private float currentAlpha;
private long lastUpdateAlphaTime;
private byte crossfadeAlpha = 1;
private boolean manualAlphaAnimator;
private boolean crossfadeWithThumb;
private ColorFilter colorFilter;
@ -113,27 +115,27 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
canceledLoading = true;
}
public void setImage(TLObject path, String filter, Drawable thumb, String ext, boolean cacheOnly) {
setImage(path, null, filter, thumb, null, null, 0, ext, cacheOnly);
public void setImage(TLObject path, String filter, Drawable thumb, String ext, int cacheType) {
setImage(path, null, filter, thumb, null, null, 0, ext, cacheType);
}
public void setImage(TLObject path, String filter, Drawable thumb, int size, String ext, boolean cacheOnly) {
setImage(path, null, filter, thumb, null, null, size, ext, cacheOnly);
public void setImage(TLObject path, String filter, Drawable thumb, int size, String ext, int cacheType) {
setImage(path, null, filter, thumb, null, null, size, ext, cacheType);
}
public void setImage(String httpUrl, String filter, Drawable thumb, String ext, int size) {
setImage(null, httpUrl, filter, thumb, null, null, size, ext, true);
setImage(null, httpUrl, filter, thumb, null, null, size, ext, 1);
}
public void setImage(TLObject fileLocation, String filter, TLRPC.FileLocation thumbLocation, String thumbFilter, String ext, boolean cacheOnly) {
setImage(fileLocation, null, filter, null, thumbLocation, thumbFilter, 0, ext, cacheOnly);
public void setImage(TLObject fileLocation, String filter, TLRPC.FileLocation thumbLocation, String thumbFilter, String ext, int cacheType) {
setImage(fileLocation, null, filter, null, thumbLocation, thumbFilter, 0, ext, cacheType);
}
public void setImage(TLObject fileLocation, String filter, TLRPC.FileLocation thumbLocation, String thumbFilter, int size, String ext, boolean cacheOnly) {
setImage(fileLocation, null, filter, null, thumbLocation, thumbFilter, size, ext, cacheOnly);
public void setImage(TLObject fileLocation, String filter, TLRPC.FileLocation thumbLocation, String thumbFilter, int size, String ext, int cacheType) {
setImage(fileLocation, null, filter, null, thumbLocation, thumbFilter, size, ext, cacheType);
}
public void setImage(TLObject fileLocation, String httpUrl, String filter, Drawable thumb, TLRPC.FileLocation thumbLocation, String thumbFilter, int size, String ext, boolean cacheOnly) {
public void setImage(TLObject fileLocation, String httpUrl, String filter, Drawable thumb, TLRPC.FileLocation thumbLocation, String thumbFilter, int size, String ext, int cacheType) {
if (setImageBackup != null) {
setImageBackup.fileLocation = null;
setImageBackup.httpUrl = null;
@ -156,7 +158,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
currentImageLocation = null;
currentHttpUrl = null;
currentFilter = null;
currentCacheOnly = false;
currentCacheType = 0;
staticThumb = thumb;
currentAlpha = 1;
currentThumbLocation = null;
@ -239,7 +241,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
currentFilter = filter;
currentThumbFilter = thumbFilter;
currentSize = size;
currentCacheOnly = cacheOnly;
currentCacheType = cacheType;
currentThumbLocation = thumbLocation;
staticThumb = thumb;
bitmapShader = null;
@ -327,7 +329,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
currentHttpUrl = null;
currentFilter = null;
currentSize = 0;
currentCacheOnly = false;
currentCacheType = 0;
bitmapShader = null;
bitmapShaderThumb = null;
if (setImageBackup != null) {
@ -371,7 +373,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
setImageBackup.thumbFilter = currentThumbFilter;
setImageBackup.size = currentSize;
setImageBackup.ext = currentExt;
setImageBackup.cacheOnly = currentCacheOnly;
setImageBackup.cacheType = currentCacheType;
}
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didReplacedPhotoInMemCache);
clearImage();
@ -383,7 +385,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
NotificationCenter.getInstance().addObserver(this, NotificationCenter.messageThumbGenerated);
}
if (setImageBackup != null && (setImageBackup.fileLocation != null || setImageBackup.httpUrl != null || setImageBackup.thumbLocation != null || setImageBackup.thumb != null)) {
setImage(setImageBackup.fileLocation, setImageBackup.httpUrl, setImageBackup.filter, setImageBackup.thumb, setImageBackup.thumbLocation, setImageBackup.thumbFilter, setImageBackup.size, setImageBackup.ext, setImageBackup.cacheOnly);
setImage(setImageBackup.fileLocation, setImageBackup.httpUrl, setImageBackup.filter, setImageBackup.thumb, setImageBackup.thumbLocation, setImageBackup.thumbFilter, setImageBackup.size, setImageBackup.ext, setImageBackup.cacheType);
return true;
}
return false;
@ -489,7 +491,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
ImageLoader.getInstance().removeImage(currentThumbKey);
currentThumbKey = null;
}
setImage(currentImageLocation, currentHttpUrl, currentFilter, currentThumb, currentThumbLocation, currentThumbFilter, currentSize, currentExt, currentCacheOnly);
setImage(currentImageLocation, currentHttpUrl, currentFilter, currentThumb, currentThumbLocation, currentThumbFilter, currentSize, currentExt, currentCacheType);
FileLog.e(e);
}
canvas.restore();
@ -537,7 +539,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
ImageLoader.getInstance().removeImage(currentThumbKey);
currentThumbKey = null;
}
setImage(currentImageLocation, currentHttpUrl, currentFilter, currentThumb, currentThumbLocation, currentThumbFilter, currentSize, currentExt, currentCacheOnly);
setImage(currentImageLocation, currentHttpUrl, currentFilter, currentThumb, currentThumbLocation, currentThumbFilter, currentSize, currentExt, currentCacheType);
FileLog.e(e);
}
}
@ -577,7 +579,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
ImageLoader.getInstance().removeImage(currentThumbKey);
currentThumbKey = null;
}
setImage(currentImageLocation, currentHttpUrl, currentFilter, currentThumb, currentThumbLocation, currentThumbFilter, currentSize, currentExt, currentCacheOnly);
setImage(currentImageLocation, currentHttpUrl, currentFilter, currentThumb, currentThumbLocation, currentThumbFilter, currentSize, currentExt, currentCacheType);
FileLog.e(e);
}
}
@ -600,6 +602,9 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
}
private void checkAlphaAnimation(boolean skip) {
if (manualAlphaAnimator) {
return;
}
if (currentAlpha != 1) {
if (!skip) {
long currentTime = System.currentTimeMillis();
@ -680,10 +685,18 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
return false;
}
public void setManualAlphaAnimator(boolean value) {
manualAlphaAnimator = value;
}
public float getCurrentAlpha() {
return currentAlpha;
}
public void setCurrentAlpha(float value) {
currentAlpha = value;
}
public Bitmap getBitmap() {
if (currentImage instanceof AnimatedFileDrawable) {
return ((AnimatedFileDrawable) currentImage).getAnimatedBitmap();
@ -699,6 +712,15 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
return null;
}
public Bitmap getThumbBitmap() {
if (currentThumb instanceof BitmapDrawable) {
return ((BitmapDrawable) currentThumb).getBitmap();
} else if (staticThumb instanceof BitmapDrawable) {
return ((BitmapDrawable) staticThumb).getBitmap();
}
return null;
}
public int getBitmapWidth() {
if (currentImage instanceof AnimatedFileDrawable) {
return orientation % 360 == 0 || orientation % 360 == 180 ? currentImage.getIntrinsicWidth() : currentImage.getIntrinsicHeight();
@ -864,14 +886,18 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
return currentHttpUrl;
}
public boolean getCacheOnly() {
return currentCacheOnly;
public int getCacheType() {
return currentCacheType;
}
public void setForcePreview(boolean value) {
forcePreview = value;
}
public void setForceCrossfade(boolean value) {
forceCrossfade = value;
}
public boolean isForcePreview() {
return forcePreview;
}
@ -984,8 +1010,8 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
bitmapShader = null;
}
if (!memCache && !forcePreview) {
if (currentThumb == null && staticThumb == null || currentAlpha == 1.0f) {
if (!memCache && !forcePreview || forceCrossfade) {
if (currentThumb == null && staticThumb == null || currentAlpha == 1.0f || forceCrossfade) {
currentAlpha = 0.0f;
lastUpdateAlphaTime = System.currentTimeMillis();
crossfadeWithThumb = currentThumb != null || staticThumb != null;

View File

@ -9,18 +9,16 @@
package org.telegram.messenger;
public class Intro {
public static native void on_draw_frame();
public static native void set_scroll_offset(float a_offset);
public static native void set_page(int page);
public static native void set_date(float a);
public static native void set_date0(float a);
public static native void set_pages_textures(int a1, int a2, int a3, int a4, int a5, int a6);
public static native void set_ic_textures(int a_ic_bubble_dot, int a_ic_bubble, int a_ic_cam_lens, int a_ic_cam, int a_ic_pencil, int a_ic_pin, int a_ic_smile_eye, int a_ic_smile, int a_ic_videocam);
public static native void set_telegram_textures(int a_telegram_sphere, int a_telegram_plane);
public static native void set_fast_textures(int a_fast_body, int a_fast_spiral, int a_fast_arrow, int a_fast_arrow_shadow);
public static native void set_free_textures(int a_knot_up, int a_knot_down);
public static native void set_powerful_textures(int a_powerful_mask, int a_powerful_star, int a_powerful_infinity, int a_powerful_infinity_white);
public static native void set_private_textures(int a_private_door, int a_private_screw);
public static native void on_surface_created();
public static native void on_surface_changed(int a_width_px, int a_height_px, float a_scale_factor, int a1, int a2, int a3, int a4, int a5);
public static native void onDrawFrame();
public static native void setScrollOffset(float a_offset);
public static native void setPage(int page);
public static native void setDate(float a);
public static native void setIcTextures(int a_ic_bubble_dot, int a_ic_bubble, int a_ic_cam_lens, int a_ic_cam, int a_ic_pencil, int a_ic_pin, int a_ic_smile_eye, int a_ic_smile, int a_ic_videocam);
public static native void setTelegramTextures(int a_telegram_sphere, int a_telegram_plane);
public static native void setFastTextures(int a_fast_body, int a_fast_spiral, int a_fast_arrow, int a_fast_arrow_shadow);
public static native void setFreeTextures(int a_knot_up, int a_knot_down);
public static native void setPowerfulTextures(int a_powerful_mask, int a_powerful_star, int a_powerful_infinity, int a_powerful_infinity_white);
public static native void setPrivateTextures(int a_private_door, int a_private_screw);
public static native void onSurfaceCreated();
public static native void onSurfaceChanged(int a_width_px, int a_height_px, float a_scale_factor, int a1);
}

View File

@ -1283,6 +1283,9 @@ public class LocaleController {
localeInfo.version = difference.version;
}
saveOtherLanguages();
if (currentLocaleInfo != null && currentLocaleInfo.isLocal()) {
return;
}
try {
Locale newLocale;
String[] args = localeInfo.shortName.split("_");

View File

@ -186,6 +186,10 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
public VideoEditedInfo editedInfo;
public boolean isVideo;
public CharSequence caption;
public boolean isFiltered;
public boolean isPainted;
public boolean isCropped;
public int ttl;
public ArrayList<TLRPC.InputDocument> stickers = new ArrayList<>();
public PhotoEntry(int bucketId, int imageId, long dateTaken, String path, int orientation, boolean isVideo) {
@ -200,6 +204,17 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
}
this.isVideo = isVideo;
}
public void reset() {
isFiltered = false;
isPainted = false;
isCropped = false;
ttl = 0;
imagePath = null;
thumbPath = null;
caption = null;
stickers.clear();
}
}
public static class SearchImage {
@ -216,6 +231,10 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
public String imagePath;
public CharSequence caption;
public TLRPC.Document document;
public boolean isFiltered;
public boolean isPainted;
public boolean isCropped;
public int ttl;
public ArrayList<TLRPC.InputDocument> stickers = new ArrayList<>();
}
@ -549,15 +568,17 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
}
}
private ExternalObserver externalObserver = null;
private InternalObserver internalObserver = null;
private long lastSecretChatEnterTime = 0;
private long lastSecretChatLeaveTime = 0;
private long lastMediaCheckTime = 0;
private TLRPC.EncryptedChat lastSecretChat = null;
private ArrayList<Long> lastSecretChatVisibleMessages = null;
private int startObserverToken = 0;
private StopMediaObserverRunnable stopMediaObserverRunnable = null;
private ExternalObserver externalObserver;
private InternalObserver internalObserver;
private long lastChatEnterTime;
private long lastChatLeaveTime;
private long lastMediaCheckTime;
private TLRPC.EncryptedChat lastSecretChat;
private TLRPC.User lastUser;
private int lastMessageId;
private ArrayList<Long> lastChatVisibleMessages;
private int startObserverToken;
private StopMediaObserverRunnable stopMediaObserverRunnable;
private final class StopMediaObserverRunnable implements Runnable {
public int currentObserverToken = 0;
@ -688,25 +709,15 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
checkAutodownloadSettings();
}
if (Build.VERSION.SDK_INT >= 16) {
mediaProjections = new String[]{
MediaStore.Images.ImageColumns.DATA,
MediaStore.Images.ImageColumns.DISPLAY_NAME,
MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,
MediaStore.Images.ImageColumns.DATE_TAKEN,
MediaStore.Images.ImageColumns.TITLE,
MediaStore.Images.ImageColumns.WIDTH,
MediaStore.Images.ImageColumns.HEIGHT
};
} else {
mediaProjections = new String[]{
MediaStore.Images.ImageColumns.DATA,
MediaStore.Images.ImageColumns.DISPLAY_NAME,
MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,
MediaStore.Images.ImageColumns.DATE_TAKEN,
MediaStore.Images.ImageColumns.TITLE
};
}
mediaProjections = new String[]{
MediaStore.Images.ImageColumns.DATA,
MediaStore.Images.ImageColumns.DISPLAY_NAME,
MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,
MediaStore.Images.ImageColumns.DATE_TAKEN,
MediaStore.Images.ImageColumns.TITLE,
MediaStore.Images.ImageColumns.WIDTH,
MediaStore.Images.ImageColumns.HEIGHT
};
try {
ApplicationLoader.applicationContext.getContentResolver().registerContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, false, new GalleryObserverExternal());
@ -1096,10 +1107,10 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
boolean added = true;
if (downloadObject.object instanceof TLRPC.PhotoSize) {
FileLoader.getInstance().loadFile((TLRPC.PhotoSize) downloadObject.object, null, false);
FileLoader.getInstance().loadFile((TLRPC.PhotoSize) downloadObject.object, null, downloadObject.secret ? 2 : 0);
} else if (downloadObject.object instanceof TLRPC.Document) {
TLRPC.Document document = (TLRPC.Document) downloadObject.object;
FileLoader.getInstance().loadFile(document, false, false);
FileLoader.getInstance().loadFile(document, false, downloadObject.secret ? 2 : 0);
} else {
added = false;
}
@ -1208,7 +1219,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
ApplicationLoader.applicationHandler.postDelayed(stopMediaObserverRunnable, 5000);
}
public void processMediaObserver(Uri uri) {
private void processMediaObserver(Uri uri) {
try {
Point size = AndroidUtilities.getRealScreenSize();
@ -1222,12 +1233,8 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
String album_name = cursor.getString(2);
long date = cursor.getLong(3);
String title = cursor.getString(4);
int photoW = 0;
int photoH = 0;
if (Build.VERSION.SDK_INT >= 16) {
photoW = cursor.getInt(5);
photoH = cursor.getInt(6);
}
int photoW = cursor.getInt(5);
int photoH = cursor.getInt(6);
if (data != null && data.toLowerCase().contains("screenshot") ||
display_name != null && display_name.toLowerCase().contains("screenshot") ||
album_name != null && album_name.toLowerCase().contains("screenshot") ||
@ -1265,33 +1272,40 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
}
private void checkScreenshots(ArrayList<Long> dates) {
if (dates == null || dates.isEmpty() || lastSecretChatEnterTime == 0 || lastSecretChat == null || !(lastSecretChat instanceof TLRPC.TL_encryptedChat)) {
if (dates == null || dates.isEmpty() || lastChatEnterTime == 0 || (lastUser == null && !(lastSecretChat instanceof TLRPC.TL_encryptedChat))) {
return;
}
long dt = 2000;
boolean send = false;
for (Long date : dates) {
for (int a = 0; a < dates.size(); a++) {
Long date = dates.get(a);
if (lastMediaCheckTime != 0 && date <= lastMediaCheckTime) {
continue;
}
if (date >= lastSecretChatEnterTime) {
if (lastSecretChatLeaveTime == 0 || date <= lastSecretChatLeaveTime + dt) {
if (date >= lastChatEnterTime) {
if (lastChatLeaveTime == 0 || date <= lastChatLeaveTime + dt) {
lastMediaCheckTime = Math.max(lastMediaCheckTime, date);
send = true;
}
}
}
if (send) {
SecretChatHelper.getInstance().sendScreenshotMessage(lastSecretChat, lastSecretChatVisibleMessages, null);
if (lastSecretChat != null) {
SecretChatHelper.getInstance().sendScreenshotMessage(lastSecretChat, lastChatVisibleMessages, null);
} else {
SendMessagesHelper.getInstance().sendScreenshotMessage(lastUser, lastMessageId, null);
}
}
}
public void setLastEncryptedChatParams(long enterTime, long leaveTime, TLRPC.EncryptedChat encryptedChat, ArrayList<Long> visibleMessages) {
lastSecretChatEnterTime = enterTime;
lastSecretChatLeaveTime = leaveTime;
public void setLastVisibleMessageIds(long enterTime, long leaveTime, TLRPC.User user, TLRPC.EncryptedChat encryptedChat, ArrayList<Long> visibleMessages, int visibleMessage) {
lastChatEnterTime = enterTime;
lastChatLeaveTime = leaveTime;
lastSecretChat = encryptedChat;
lastSecretChatVisibleMessages = visibleMessages;
lastUser = user;
lastMessageId = visibleMessage;
lastChatVisibleMessages = visibleMessages;
}
public int generateObserverTag() {
@ -2308,7 +2322,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
final File cacheFile = file != null ? file : FileLoader.getPathToMessage(nextAudio.messageOwner);
boolean exist = cacheFile != null && cacheFile.exists();
if (cacheFile != null && cacheFile != file && !cacheFile.exists()) {
FileLoader.getInstance().loadFile(nextAudio.getDocument(), false, false);
FileLoader.getInstance().loadFile(nextAudio.getDocument(), false, 0);
}
}
@ -2335,7 +2349,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
final File cacheFile = file != null ? file : FileLoader.getPathToMessage(nextAudio.messageOwner);
boolean exist = cacheFile != null && cacheFile.exists();
if (cacheFile != null && cacheFile != file && !cacheFile.exists() && nextAudio.isMusic()) {
FileLoader.getInstance().loadFile(nextAudio.getDocument(), false, false);
FileLoader.getInstance().loadFile(nextAudio.getDocument(), false, 0);
}
}
@ -2485,7 +2499,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
}
final File cacheFile = file != null ? file : FileLoader.getPathToMessage(messageObject.messageOwner);
if (cacheFile != null && cacheFile != file && !cacheFile.exists()) {
FileLoader.getInstance().loadFile(messageObject.getDocument(), false, false);
FileLoader.getInstance().loadFile(messageObject.getDocument(), false, 0);
downloadingCurrentMessage = true;
isPaused = false;
lastProgress = 0;
@ -3142,7 +3156,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
audioToSend.attributes.add(attributeAudio);
if (duration > 700) {
if (send == 1) {
SendMessagesHelper.getInstance().sendMessage(audioToSend, null, recordingAudioFileToSend.getAbsolutePath(), recordDialogId, recordReplyingMessageObject, null, null);
SendMessagesHelper.getInstance().sendMessage(audioToSend, null, recordingAudioFileToSend.getAbsolutePath(), recordDialogId, recordReplyingMessageObject, null, null, 0);
}
NotificationCenter.getInstance().postNotificationName(NotificationCenter.audioDidSent, send == 2 ? audioToSend : null, send == 2 ? recordingAudioFileToSend.getAbsolutePath() : null);
} else {

View File

@ -317,6 +317,12 @@ public class MessageObject {
}
}
}
} else if (message.action instanceof TLRPC.TL_messageActionScreenshotTaken) {
if (isOut()) {
messageText = LocaleController.formatString("ActionTakeScreenshootYou", R.string.ActionTakeScreenshootYou);
} else {
messageText = replaceWithLink(LocaleController.getString("ActionTakeScreenshoot", R.string.ActionTakeScreenshoot), "un1", fromUser);
}
} else if (message.action instanceof TLRPC.TL_messageActionCreatedBroadcastList) {
messageText = LocaleController.formatString("YouCreatedBroadcastList", R.string.YouCreatedBroadcastList);
} else if (message.action instanceof TLRPC.TL_messageActionChannelCreate) {
@ -386,7 +392,7 @@ public class MessageObject {
} else if (!isMediaEmpty()) {
if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
messageText = LocaleController.getString("AttachPhoto", R.string.AttachPhoto);
} else if (isVideo()) {
} else if (isVideo() || message.media instanceof TLRPC.TL_messageMediaDocument && message.media.document instanceof TLRPC.TL_documentEmpty && message.media.ttl_seconds != 0) {
messageText = LocaleController.getString("AttachVideo", R.string.AttachVideo);
} else if (isVoice()) {
messageText = LocaleController.getString("AttachAudio", R.string.AttachAudio);
@ -1138,6 +1144,9 @@ public class MessageObject {
if (TextUtils.isEmpty(messageText) && eventId == 0) {
messageText = "Empty message";
}
} else if (messageOwner.media.ttl_seconds != 0 && (messageOwner.media.photo instanceof TLRPC.TL_photoEmpty || messageOwner.media.document instanceof TLRPC.TL_documentEmpty)) {
contentType = 1;
type = 10;
} else if (messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
type = 1;
} else if (messageOwner.media instanceof TLRPC.TL_messageMediaGeo || messageOwner.media instanceof TLRPC.TL_messageMediaVenue) {
@ -1254,9 +1263,6 @@ public class MessageObject {
}
public static boolean isRoundVideoDocument(TLRPC.Document document) {
if (Build.VERSION.SDK_INT < 16) {
return false;
}
if (document != null && document.mime_type != null && document.mime_type.equals("video/mp4")) {
int width = 0;
int height = 0;
@ -2023,13 +2029,28 @@ public class MessageObject {
return messageOwner.id;
}
public static boolean shouldEncryptPhotoOrVideo(TLRPC.Message message) {
return message instanceof TLRPC.TL_message && (message.media instanceof TLRPC.TL_messageMediaPhoto || message.media instanceof TLRPC.TL_messageMediaDocument) && message.media.ttl_seconds != 0 ||
message instanceof TLRPC.TL_message_secret && (message.media instanceof TLRPC.TL_messageMediaPhoto || isVideoMessage(message)) && message.ttl > 0 && message.ttl <= 60;
}
public boolean shouldEncryptPhotoOrVideo() {
return shouldEncryptPhotoOrVideo(messageOwner);
}
public static boolean isSecretPhotoOrVideo(TLRPC.Message message) {
return message instanceof TLRPC.TL_message && (message.media instanceof TLRPC.TL_messageMediaPhoto || message.media instanceof TLRPC.TL_messageMediaDocument) && message.media.ttl_seconds != 0 ||
message instanceof TLRPC.TL_message_secret && (message.media instanceof TLRPC.TL_messageMediaPhoto || isRoundVideoMessage(message) || isVideoMessage(message)) && message.ttl > 0 && message.ttl <= 60;
}
public boolean isSecretPhoto() {
return messageOwner instanceof TLRPC.TL_message_secret && (messageOwner.media instanceof TLRPC.TL_messageMediaPhoto || isRoundVideo()) && messageOwner.ttl > 0 && messageOwner.ttl <= 60;
return messageOwner instanceof TLRPC.TL_message && (messageOwner.media instanceof TLRPC.TL_messageMediaPhoto || messageOwner.media instanceof TLRPC.TL_messageMediaDocument) && messageOwner.media.ttl_seconds != 0 ||
messageOwner instanceof TLRPC.TL_message_secret && (messageOwner.media instanceof TLRPC.TL_messageMediaPhoto || isRoundVideo() || isVideo()) && messageOwner.ttl > 0 && messageOwner.ttl <= 60;
}
public boolean isSecretMedia() {
return messageOwner instanceof TLRPC.TL_message_secret &&
((messageOwner.media instanceof TLRPC.TL_messageMediaPhoto || isRoundVideo()) && messageOwner.ttl > 0 && messageOwner.ttl <= 60 || isVoice() || isVideo());
return messageOwner instanceof TLRPC.TL_message && (messageOwner.media instanceof TLRPC.TL_messageMediaPhoto || messageOwner.media instanceof TLRPC.TL_messageMediaDocument) && messageOwner.media.ttl_seconds != 0 ||
messageOwner instanceof TLRPC.TL_message_secret && ((messageOwner.media instanceof TLRPC.TL_messageMediaPhoto || isRoundVideo()) && messageOwner.ttl > 0 && messageOwner.ttl <= 60 || isVoice() || isVideo());
}
public static void setUnreadFlags(TLRPC.Message message, int flag) {
@ -2092,14 +2113,19 @@ public class MessageObject {
return messageOwner.send_state == MESSAGE_SEND_STATE_SENT || messageOwner.id > 0;
}
public String getSecretTimeString() {
if (!isSecretMedia()) {
return null;
}
public int getSecretTimeLeft() {
int secondsLeft = messageOwner.ttl;
if (messageOwner.destroyTime != 0) {
secondsLeft = Math.max(0, messageOwner.destroyTime - ConnectionsManager.getInstance().getCurrentTime());
}
return secondsLeft;
}
public String getSecretTimeString() {
if (!isSecretMedia()) {
return null;
}
int secondsLeft = getSecretTimeLeft();
String str;
if (secondsLeft < 60) {
str = secondsLeft + "s";
@ -2188,7 +2214,7 @@ public class MessageObject {
for (int a = 0; a < document.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = document.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeVideo) {
if (Build.VERSION.SDK_INT >= 16 && attribute.round_message) {
if (attribute.round_message) {
return false;
}
isVideo = true;
@ -2229,9 +2255,6 @@ public class MessageObject {
}
public static boolean isRoundVideoMessage(TLRPC.Message message) {
if (Build.VERSION.SDK_INT < 16) {
return false;
}
if (message.media instanceof TLRPC.TL_messageMediaWebPage) {
return isRoundVideoDocument(message.media.webpage.document);
}
@ -2428,9 +2451,6 @@ public class MessageObject {
}
public boolean isRoundVideo() {
if (Build.VERSION.SDK_INT < 16) {
return false;
}
if (isRoundVideoCached == 0) {
isRoundVideoCached = type == 5 || isRoundVideoMessage(messageOwner) ? 1 : 2;
}
@ -2501,6 +2521,8 @@ public class MessageObject {
TLRPC.DocumentAttribute attribute = document.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeAudio) {
return attribute.duration;
} else if (attribute instanceof TLRPC.TL_documentAttributeVideo) {
return attribute.duration;
}
}
return 0;
@ -2667,7 +2689,13 @@ public class MessageObject {
if (type == 1) {
TLRPC.PhotoSize currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(photoThumbs, AndroidUtilities.getPhotoSize());
if (currentPhotoObject != null) {
mediaExists = FileLoader.getPathToMessage(messageOwner).exists();
File file = FileLoader.getPathToMessage(messageOwner);
if (isSecretPhoto()) {
mediaExists = new File(file.getAbsolutePath() + ".enc").exists();
}
if (!mediaExists) {
mediaExists = file.exists();
}
}
} else if (type == 8 || type == 3 || type == 9 || type == 2 || type == 14 || type == 5) {
if (messageOwner.attachPath != null && messageOwner.attachPath.length() > 0) {
@ -2675,7 +2703,13 @@ public class MessageObject {
attachPathExists = f.exists();
}
if (!attachPathExists) {
mediaExists = FileLoader.getPathToMessage(messageOwner).exists();
File file = FileLoader.getPathToMessage(messageOwner);
if (type == 3 && isSecretPhoto()) {
mediaExists = new File(file.getAbsolutePath() + ".enc").exists();
}
if (!mediaExists) {
mediaExists = file.exists();
}
}
} else {
TLRPC.Document document = getDocument();

View File

@ -121,6 +121,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
private boolean gettingNewDeleteTask;
private int currentDeletingTaskTime;
private ArrayList<Integer> currentDeletingTaskMids;
private int currentDeletingTaskChannelId;
private Runnable currentDeleteTaskRunnable;
public boolean loadingDialogs;
@ -270,6 +271,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidLoaded);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidFailedLoad);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.messageReceivedByServer);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateMessageMedia);
addSupportUser();
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
enableJoined = preferences.getBoolean("EnableContactJoined", true);
@ -578,6 +580,16 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (obj != null) {
dialogMessagesByIds.put(newMsgId, obj);
}
} else if (id == NotificationCenter.updateMessageMedia) {
TLRPC.Message message = (TLRPC.Message) args[0];
MessageObject existMessageObject = dialogMessagesByIds.get(message.id);
if (existMessageObject != null) {
existMessageObject.messageOwner.media = message.media;
if (message.media.ttl_seconds != 0 && (message.media.photo instanceof TLRPC.TL_photoEmpty || message.media.document instanceof TLRPC.TL_documentEmpty)) {
existMessageObject.setType();
NotificationCenter.getInstance().postNotificationName(NotificationCenter.notificationsSettingsUpdated);
}
}
}
}
@ -644,6 +656,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
currentDeletingTaskTime = 0;
currentDeletingTaskMids = null;
currentDeletingTaskChannelId = 0;
gettingNewDeleteTask = false;
loadingDialogs = false;
dialogsEndReached = false;
@ -1546,12 +1559,12 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
}
public void didAddedNewTask(final int minDate, final SparseArray<ArrayList<Integer>> mids) {
public void didAddedNewTask(final int minDate, final SparseArray<ArrayList<Long>> mids) {
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
if (currentDeletingTaskMids == null && !gettingNewDeleteTask || currentDeletingTaskTime != 0 && minDate < currentDeletingTaskTime) {
getNewDeleteTask(null);
getNewDeleteTask(null, 0);
}
}
});
@ -1563,12 +1576,12 @@ public class MessagesController implements NotificationCenter.NotificationCenter
});
}
public void getNewDeleteTask(final ArrayList<Integer> oldTask) {
public void getNewDeleteTask(final ArrayList<Integer> oldTask, final int channelId) {
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
gettingNewDeleteTask = true;
MessagesStorage.getInstance().getNewTask(oldTask);
MessagesStorage.getInstance().getNewTask(oldTask, channelId);
}
});
}
@ -1582,15 +1595,19 @@ public class MessagesController implements NotificationCenter.NotificationCenter
Utilities.stageQueue.cancelRunnable(currentDeleteTaskRunnable);
}
currentDeleteTaskRunnable = null;
final ArrayList<Integer> mids = new ArrayList<>(currentDeletingTaskMids);
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
deleteMessages(currentDeletingTaskMids, null, null, 0, false);
if (!mids.isEmpty() && mids.get(0) > 0) {
MessagesStorage.getInstance().emptyMessagesMedia(mids);
} else {
deleteMessages(mids, null, null, 0, false);
}
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
getNewDeleteTask(currentDeletingTaskMids);
getNewDeleteTask(mids, currentDeletingTaskChannelId);
currentDeletingTaskTime = 0;
currentDeletingTaskMids = null;
}
@ -1602,7 +1619,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
return false;
}
public void processLoadedDeleteTask(final int taskTime, final ArrayList<Integer> messages) {
public void processLoadedDeleteTask(final int taskTime, final ArrayList<Integer> messages, final int channelId) {
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
@ -3279,7 +3296,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
@Override
public void run() {
if (!firstGettingTask) {
getNewDeleteTask(null);
getNewDeleteTask(null, 0);
firstGettingTask = true;
}
@ -3970,7 +3987,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
messageId |= ((long) message.to_id.channel_id) << 32;
}
arrayList.add(messageId);
MessagesStorage.getInstance().markMessagesContentAsRead(arrayList);
MessagesStorage.getInstance().markMessagesContentAsRead(arrayList, 0);
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
@ -4002,7 +4019,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
messageId |= ((long) messageObject.messageOwner.to_id.channel_id) << 32;
}
arrayList.add(messageId);
MessagesStorage.getInstance().markMessagesContentAsRead(arrayList);
MessagesStorage.getInstance().markMessagesContentAsRead(arrayList, 0);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesReadContent, arrayList);
if (messageObject.getId() < 0) {
markMessageAsRead(messageObject.getDialogId(), messageObject.messageOwner.random_id, Integer.MIN_VALUE);
@ -4021,6 +4038,25 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
}
public void markMessageAsRead(final int mid, final int channelId, int ttl) {
if (mid == 0 || ttl <= 0) {
return;
}
int time = ConnectionsManager.getInstance().getCurrentTime();
MessagesStorage.getInstance().createTaskForMid(mid, channelId, time, time, ttl, false);
TLRPC.TL_messages_readMessageContents req = new TLRPC.TL_messages_readMessageContents();
req.id.add(mid);
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
TLRPC.TL_messages_affectedMessages res = (TLRPC.TL_messages_affectedMessages) response;
processNewDifferenceParams(-1, res.pts, -1, res.pts_count);
}
}
});
}
public void markMessageAsRead(final long dialog_id, final long random_id, int ttl) {
if (random_id == 0 || dialog_id == 0 || ttl <= 0 && ttl != Integer.MIN_VALUE) {
return;
@ -7887,7 +7923,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
MessagesStorage.getInstance().markMessagesAsRead(markAsReadMessagesInbox, markAsReadMessagesOutbox, markAsReadEncrypted, true);
}
if (!markAsReadMessages.isEmpty()) {
MessagesStorage.getInstance().markMessagesContentAsRead(markAsReadMessages);
MessagesStorage.getInstance().markMessagesContentAsRead(markAsReadMessages, ConnectionsManager.getInstance().getCurrentTime());
}
if (deletedMessages.size() != 0) {
for (int a = 0; a < deletedMessages.size(); a++) {

View File

@ -1612,7 +1612,96 @@ public class MessagesStorage {
});
}
public void getNewTask(final ArrayList<Integer> oldTask) {
public void emptyMessagesMedia(final ArrayList<Integer> mids) {
storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
try {
ArrayList<File> filesToDelete = new ArrayList<>();
final ArrayList<TLRPC.Message> messages = new ArrayList<>();
SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid, date, uid FROM messages WHERE mid IN (%s)", TextUtils.join(",", mids)));
while (cursor.next()) {
NativeByteBuffer data = cursor.byteBufferValue(0);
if (data != null) {
TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false);
data.reuse();
if (message.media != null) {
if (message.media.document != null) {
File file = FileLoader.getPathToAttach(message.media.document, true);
if (file != null && file.toString().length() > 0) {
filesToDelete.add(file);
}
file = FileLoader.getPathToAttach(message.media.document.thumb, true);
if (file != null && file.toString().length() > 0) {
filesToDelete.add(file);
}
message.media.document = new TLRPC.TL_documentEmpty();
} else if (message.media.photo != null) {
for (TLRPC.PhotoSize photoSize : message.media.photo.sizes) {
File file = FileLoader.getPathToAttach(photoSize, true);
if (file != null && file.toString().length() > 0) {
filesToDelete.add(file);
}
}
message.media.photo = new TLRPC.TL_photoEmpty();
} else {
continue;
}
message.media.flags = message.media.flags &~ 1;
message.id = cursor.intValue(1);
message.date = cursor.intValue(2);
message.dialog_id = cursor.longValue(3);
messages.add(message);
}
}
}
cursor.dispose();
if (!messages.isEmpty()) {
SQLitePreparedStatement state = database.executeFast("REPLACE INTO messages VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?)");
for (int a = 0; a < messages.size(); a++) {
TLRPC.Message message = messages.get(a);
NativeByteBuffer data = new NativeByteBuffer(message.getObjectSize());
message.serializeToStream(data);
state.requery();
state.bindLong(1, message.id);
state.bindLong(2, message.dialog_id);
state.bindInteger(3, MessageObject.getUnreadFlags(message));
state.bindInteger(4, message.send_state);
state.bindInteger(5, message.date);
state.bindByteBuffer(6, data);
state.bindInteger(7, (MessageObject.isOut(message) ? 1 : 0));
state.bindInteger(8, message.ttl);
if ((message.flags & TLRPC.MESSAGE_FLAG_HAS_VIEWS) != 0) {
state.bindInteger(9, message.views);
} else {
state.bindInteger(9, getMessageMediaType(message));
}
state.bindInteger(10, 0);
state.step();
data.reuse();
}
state.dispose();
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
for (int a = 0; a < messages.size(); a++) {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateMessageMedia, messages.get(a));
}
}
});
}
FileLoader.getInstance().deleteFiles(filesToDelete, 0);
} catch (Exception e) {
FileLog.e(e);
}
}
});
}
public void getNewTask(final ArrayList<Integer> oldTask, final int channelId) {
storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
@ -1622,18 +1711,25 @@ public class MessagesStorage {
database.executeFast(String.format(Locale.US, "DELETE FROM enc_tasks_v2 WHERE mid IN(%s)", ids)).stepThis().dispose();
}
int date = 0;
int channelId = -1;
ArrayList<Integer> arr = null;
SQLiteCursor cursor = database.queryFinalized("SELECT mid, date FROM enc_tasks_v2 WHERE date = (SELECT min(date) FROM enc_tasks_v2)");
while (cursor.next()) {
Integer mid = cursor.intValue(0);
long mid = cursor.longValue(0);
if (channelId == -1) {
channelId = (int) (mid >> 32);
if (channelId < 0) {
channelId = 0;
}
}
date = cursor.intValue(1);
if (arr == null) {
arr = new ArrayList<>();
}
arr.add(mid);
arr.add((int) mid);
}
cursor.dispose();
MessagesController.getInstance().processLoadedDeleteTask(date, arr);
MessagesController.getInstance().processLoadedDeleteTask(date, arr, channelId);
} catch (Exception e) {
FileLog.e(e);
}
@ -1641,34 +1737,81 @@ public class MessagesStorage {
});
}
public void createTaskForSecretChat(final int chat_id, final int time, final int readTime, final int isOut, final ArrayList<Long> random_ids) {
public void createTaskForMid(final int messageId, final int channelId, final int time, final int readTime, final int ttl, final boolean inner) {
storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
try {
int minDate = (time > readTime ? time : readTime) + ttl;
SparseArray<ArrayList<Long>> messages = new SparseArray<>();
final ArrayList<Long> midsArray = new ArrayList<>();
long mid = messageId;
if (channelId != 0) {
mid |= ((long) channelId) << 32;
}
midsArray.add(mid);
messages.put(minDate, midsArray);
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
if (!inner) {
MessagesStorage.getInstance().markMessagesContentAsRead(midsArray, 0);
}
NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesReadContent, midsArray);
}
});
SQLitePreparedStatement state = database.executeFast("REPLACE INTO enc_tasks_v2 VALUES(?, ?)");
for (int a = 0; a < messages.size(); a++) {
int key = messages.keyAt(a);
ArrayList<Long> arr = messages.get(key);
for (int b = 0; b < arr.size(); b++) {
state.requery();
state.bindLong(1, arr.get(b));
state.bindInteger(2, key);
state.step();
}
}
state.dispose();
database.executeFast(String.format(Locale.US, "UPDATE messages SET ttl = 0 WHERE mid = %d", mid)).stepThis().dispose();
MessagesController.getInstance().didAddedNewTask(minDate, messages);
} catch (Exception e) {
FileLog.e(e);
}
}
});
}
public void createTaskForSecretChat(final long did, final int time, final int readTime, final int isOut, final ArrayList<Long> random_ids) {
storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
try {
int minDate = Integer.MAX_VALUE;
SparseArray<ArrayList<Integer>> messages = new SparseArray<>();
SparseArray<ArrayList<Long>> messages = new SparseArray<>();
final ArrayList<Long> midsArray = new ArrayList<>();
StringBuilder mids = new StringBuilder();
SQLiteCursor cursor;
if (random_ids == null) {
cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid, ttl FROM messages WHERE uid = %d AND out = %d AND read_state != 0 AND ttl > 0 AND date <= %d AND send_state = 0 AND media != 1", ((long) chat_id) << 32, isOut, time));
cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid, ttl FROM messages WHERE uid = %d AND out = %d AND read_state != 0 AND ttl > 0 AND date <= %d AND send_state = 0 AND media != 1", did, isOut, time));
} else {
String ids = TextUtils.join(",", random_ids);
cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.mid, m.ttl FROM messages as m INNER JOIN randoms as r ON m.mid = r.mid WHERE r.random_id IN (%s)", ids));
}
while (cursor.next()) {
int ttl = cursor.intValue(1);
int mid = cursor.intValue(0);
long mid = cursor.intValue(0);
if (random_ids != null) {
midsArray.add((long) mid);
midsArray.add(mid);
}
if (ttl <= 0) {
continue;
}
int date = (time > readTime ? time : readTime) + ttl;
minDate = Math.min(minDate, date);
ArrayList<Integer> arr = messages.get(date);
ArrayList<Long> arr = messages.get(date);
if (arr == null) {
arr = new ArrayList<>();
messages.put(date, arr);
@ -1685,7 +1828,7 @@ public class MessagesStorage {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
MessagesStorage.getInstance().markMessagesContentAsRead(midsArray);
MessagesStorage.getInstance().markMessagesContentAsRead(midsArray, 0);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesReadContent, midsArray);
}
});
@ -1696,10 +1839,10 @@ public class MessagesStorage {
SQLitePreparedStatement state = database.executeFast("REPLACE INTO enc_tasks_v2 VALUES(?, ?)");
for (int a = 0; a < messages.size(); a++) {
int key = messages.keyAt(a);
ArrayList<Integer> arr = messages.get(key);
ArrayList<Long> arr = messages.get(key);
for (int b = 0; b < arr.size(); b++) {
state.requery();
state.bindInteger(1, arr.get(b));
state.bindLong(1, arr.get(b));
state.bindInteger(2, key);
state.step();
}
@ -3062,7 +3205,7 @@ public class MessagesStorage {
if ((message.flags & TLRPC.MESSAGE_FLAG_HAS_VIEWS) != 0) {
message.views = cursor.intValue(7);
}
if (lower_id != 0) {
if (lower_id != 0 && message.ttl == 0) {
message.ttl = cursor.intValue(8);
}
res.messages.add(message);
@ -3115,7 +3258,7 @@ public class MessagesStorage {
if (lower_id == 0 && !cursor.isNull(5)) {
message.random_id = cursor.longValue(5);
}
if ((int) dialog_id == 0 && message.media != null && message.media.photo != null) {
if (MessageObject.isSecretPhotoOrVideo(message)) {
try {
SQLiteCursor cursor2 = database.queryFinalized(String.format(Locale.US, "SELECT date FROM enc_tasks_v2 WHERE mid = %d", message.id));
if (cursor2.next()) {
@ -3335,12 +3478,12 @@ public class MessagesStorage {
TLRPC.MessageMedia messageMedia = null;
if (file instanceof TLRPC.Photo) {
messageMedia = new TLRPC.TL_messageMediaPhoto();
messageMedia.caption = "";
messageMedia.photo = (TLRPC.Photo) file;
messageMedia.flags |= 1;
} else if (file instanceof TLRPC.Document) {
messageMedia = new TLRPC.TL_messageMediaDocument();
messageMedia.caption = "";
messageMedia.document = (TLRPC.Document) file;
messageMedia.flags |= 1;
}
if (messageMedia == null) {
return;
@ -3986,6 +4129,7 @@ public class MessagesStorage {
} else if (messageMedia.photo != null) {
downloadObject.object = FileLoader.getClosestPhotoSizeWithSize(messageMedia.photo.sizes, AndroidUtilities.getPhotoSize());
}
downloadObject.secret = messageMedia.ttl_seconds != 0;
}
objects.add(downloadObject);
}
@ -4005,7 +4149,9 @@ public class MessagesStorage {
}
private int getMessageMediaType(TLRPC.Message message) {
if (message instanceof TLRPC.TL_message_secret && (
if (message instanceof TLRPC.TL_message && (message.media instanceof TLRPC.TL_messageMediaPhoto || message.media instanceof TLRPC.TL_messageMediaDocument) && message.media.ttl_seconds != 0) {
return 1;
} else if (message instanceof TLRPC.TL_message_secret && (
message.media instanceof TLRPC.TL_messageMediaPhoto && message.ttl > 0 && message.ttl <= 60 ||
MessageObject.isVoiceMessage(message) ||
MessageObject.isVideoMessage(message) ||
@ -4442,16 +4588,16 @@ public class MessagesStorage {
id = message.media.document.id;
type = MediaController.AUTODOWNLOAD_MASK_AUDIO;
object = new TLRPC.TL_messageMediaDocument();
object.caption = "";
object.document = message.media.document;
object.flags |= 1;
}
} else if (MessageObject.isRoundVideoMessage(message)) {
if ((downloadMask & MediaController.AUTODOWNLOAD_MASK_VIDEOMESSAGE) != 0 && message.media.document.size < 1024 * 1024 * 5) {
id = message.media.document.id;
type = MediaController.AUTODOWNLOAD_MASK_VIDEOMESSAGE;
object = new TLRPC.TL_messageMediaDocument();
object.caption = "";
object.document = message.media.document;
object.flags |= 1;
}
} else if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
if ((downloadMask & MediaController.AUTODOWNLOAD_MASK_PHOTO) != 0) {
@ -4460,8 +4606,8 @@ public class MessagesStorage {
id = message.media.photo.id;
type = MediaController.AUTODOWNLOAD_MASK_PHOTO;
object = new TLRPC.TL_messageMediaPhoto();
object.caption = "";
object.photo = message.media.photo;
object.flags |= 1;
}
}
} else if (MessageObject.isVideoMessage(message)) {
@ -4469,19 +4615,23 @@ public class MessagesStorage {
id = message.media.document.id;
type = MediaController.AUTODOWNLOAD_MASK_VIDEO;
object = new TLRPC.TL_messageMediaDocument();
object.caption = "";
object.document = message.media.document;
object.flags |= 1;
}
} else if (message.media instanceof TLRPC.TL_messageMediaDocument && !MessageObject.isMusicMessage(message) && !MessageObject.isGifDocument(message.media.document)) {
if ((downloadMask & MediaController.AUTODOWNLOAD_MASK_DOCUMENT) != 0) {
id = message.media.document.id;
type = MediaController.AUTODOWNLOAD_MASK_DOCUMENT;
object = new TLRPC.TL_messageMediaDocument();
object.caption = "";
object.document = message.media.document;
object.flags |= 1;
}
}
if (object != null) {
if (message.media.ttl_seconds != 0) {
object.ttl_seconds = message.media.ttl_seconds;
object.flags |= 4;
}
downloadMediaMask |= type;
state4.requery();
data = new NativeByteBuffer(object.getObjectSize());
@ -4980,7 +5130,7 @@ public class MessagesStorage {
}
}
public void markMessagesContentAsRead(final ArrayList<Long> mids) {
public void markMessagesContentAsRead(final ArrayList<Long> mids, final int date) {
if (mids == null || mids.isEmpty()) {
return;
}
@ -4988,7 +5138,22 @@ public class MessagesStorage {
@Override
public void run() {
try {
database.executeFast(String.format(Locale.US, "UPDATE messages SET read_state = read_state | 2 WHERE mid IN (%s)", TextUtils.join(",", mids))).stepThis().dispose();
String midsStr = TextUtils.join(",", mids);
database.executeFast(String.format(Locale.US, "UPDATE messages SET read_state = read_state | 2 WHERE mid IN (%s)", midsStr)).stepThis().dispose();
if (date != 0) {
SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid, ttl FROM messages WHERE mid IN (%s) AND ttl > 0", midsStr));
ArrayList<Integer> arrayList = null;
while (cursor.next()) {
if (arrayList == null) {
arrayList = new ArrayList<>();
}
arrayList.add(cursor.intValue(0));
}
if (arrayList != null) {
emptyMessagesMedia(arrayList);
}
cursor.dispose();
}
} catch (Exception e) {
FileLog.e(e);
}
@ -5622,11 +5787,11 @@ public class MessagesStorage {
state.bindInteger(5, message.date);
state.bindByteBuffer(6, data);
state.bindInteger(7, (MessageObject.isOut(message) ? 1 : 0));
state.bindInteger(8, 0);
state.bindInteger(8, message.ttl);
if ((message.flags & TLRPC.MESSAGE_FLAG_HAS_VIEWS) != 0) {
state.bindInteger(9, message.views);
} else {
state.bindInteger(9, 0);
state.bindInteger(9, getMessageMediaType(message));
}
state.bindInteger(10, 0);
state.step();

View File

@ -916,13 +916,21 @@ public class NotificationsController {
if (!shortMessage && Build.VERSION.SDK_INT >= 19 && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
msg = LocaleController.formatString("NotificationMessageText", R.string.NotificationMessageText, name, "\uD83D\uDDBC " + messageObject.messageOwner.media.caption);
} else {
msg = LocaleController.formatString("NotificationMessagePhoto", R.string.NotificationMessagePhoto, name);
if (messageObject.messageOwner.media.ttl_seconds != 0) {
msg = LocaleController.formatString("NotificationMessageSDPhoto", R.string.NotificationMessageSDPhoto, name);
} else {
msg = LocaleController.formatString("NotificationMessagePhoto", R.string.NotificationMessagePhoto, name);
}
}
} else if (messageObject.isVideo()) {
if (!shortMessage && Build.VERSION.SDK_INT >= 19 && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
msg = LocaleController.formatString("NotificationMessageText", R.string.NotificationMessageText, name, "\uD83D\uDCF9 " + messageObject.messageOwner.media.caption);
} else {
msg = LocaleController.formatString("NotificationMessageVideo", R.string.NotificationMessageVideo, name);
if (messageObject.messageOwner.media.ttl_seconds != 0) {
msg = LocaleController.formatString("NotificationMessageSDVideo", R.string.NotificationMessageSDVideo, name);
} else {
msg = LocaleController.formatString("NotificationMessageVideo", R.string.NotificationMessageVideo, name);
}
}
} else if (messageObject.isGame()) {
msg = LocaleController.formatString("NotificationMessageGame", R.string.NotificationMessageGame, name, messageObject.messageOwner.media.game.title);
@ -1037,6 +1045,8 @@ public class NotificationsController {
msg = LocaleController.formatString("ActionMigrateFromGroupNotify", R.string.ActionMigrateFromGroupNotify, chat.title);
} else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChannelMigrateFrom) {
msg = LocaleController.formatString("ActionMigrateFromGroupNotify", R.string.ActionMigrateFromGroupNotify, messageObject.messageOwner.action.title);
} else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionScreenshotTaken) {
msg = messageObject.messageText.toString();
} else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionPinMessage) {
if (messageObject.replyMessageObject == null) {
if (!ChatObject.isChannel(chat) || chat.megagroup) {

View File

@ -849,6 +849,7 @@ public class SecretChatHelper {
return null;
}
newMessage.media = new TLRPC.TL_messageMediaPhoto();
newMessage.media.flags |= 3;
newMessage.media.caption = decryptedMessage.media.caption != null ? decryptedMessage.media.caption : "";
newMessage.media.photo = new TLRPC.TL_photo();
newMessage.media.photo.date = newMessage.date;
@ -881,6 +882,7 @@ public class SecretChatHelper {
return null;
}
newMessage.media = new TLRPC.TL_messageMediaDocument();
newMessage.media.flags |= 3;
newMessage.media.document = new TLRPC.TL_documentEncrypted();
newMessage.media.document.key = decryptedMessage.media.key;
newMessage.media.document.iv = decryptedMessage.media.iv;
@ -919,6 +921,7 @@ public class SecretChatHelper {
return null;
}
newMessage.media = new TLRPC.TL_messageMediaDocument();
newMessage.media.flags |= 3;
newMessage.media.caption = decryptedMessage.media.caption != null ? decryptedMessage.media.caption : "";
newMessage.media.document = new TLRPC.TL_documentEncrypted();
newMessage.media.document.id = file.id;
@ -956,6 +959,7 @@ public class SecretChatHelper {
}
} else if (decryptedMessage.media instanceof TLRPC.TL_decryptedMessageMediaExternalDocument) {
newMessage.media = new TLRPC.TL_messageMediaDocument();
newMessage.media.flags |= 3;
newMessage.media.caption = "";
newMessage.media.document = new TLRPC.TL_document();
newMessage.media.document.id = decryptedMessage.media.id;
@ -974,6 +978,7 @@ public class SecretChatHelper {
return null;
}
newMessage.media = new TLRPC.TL_messageMediaDocument();
newMessage.media.flags |= 3;
newMessage.media.document = new TLRPC.TL_documentEncrypted();
newMessage.media.document.key = decryptedMessage.media.key;
newMessage.media.document.iv = decryptedMessage.media.iv;

View File

@ -286,6 +286,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
}
} else {
media.thumb = file;
media.flags |= 4;
performSendMessageRequest(message.sendRequest, message.obj, message.originalPath);
}
} else if (message.type == 2) {
@ -298,6 +299,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
}
} else {
media.thumb = file;
media.flags |= 4;
performSendMessageRequest(message.sendRequest, message.obj, message.originalPath);
}
} else if (message.type == 3) {
@ -446,7 +448,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
messages.add(message.obj.messageOwner);
MessagesStorage.getInstance().putMessages(messages, false, true, false, 0);
performSendDelayedMessage(message);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateMessageMedia, message.obj);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateMessageMedia, message.obj.messageOwner);
} else {
FileLog.e("can't load image " + message.httpLocation + " to file " + cacheFile.toString());
MessagesStorage.getInstance().markMessageAsSendError(message.obj.messageOwner);
@ -490,7 +492,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
messages.add(message.obj.messageOwner);
MessagesStorage.getInstance().putMessages(messages, false, true, false, 0);
performSendDelayedMessage(message);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateMessageMedia, message.obj);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateMessageMedia, message.obj.messageOwner);
}
});
}
@ -602,6 +604,9 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
SecretChatHelper.getInstance().sendNoopMessage(encryptedChat, messageObject.messageOwner);
}
return true;
} else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionScreenshotTaken) {
TLRPC.User user = MessagesController.getInstance().getUser((int) messageObject.getDialogId());
sendScreenshotMessage(user, messageObject.messageOwner.reply_to_msg_id, messageObject.messageOwner);
}
if (unsent) {
unsentMessages.put(messageObject.getId(), messageObject);
@ -624,9 +629,9 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
}
if (messageObject.messageOwner.media != null && !(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty) && !(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage) && !(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGame) && !(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaInvoice)) {
if (messageObject.messageOwner.media.photo instanceof TLRPC.TL_photo) {
sendMessage((TLRPC.TL_photo) messageObject.messageOwner.media.photo, null, did, messageObject.replyMessageObject, null, null);
sendMessage((TLRPC.TL_photo) messageObject.messageOwner.media.photo, null, did, messageObject.replyMessageObject, null, null, messageObject.messageOwner.media.ttl_seconds);
} else if (messageObject.messageOwner.media.document instanceof TLRPC.TL_document) {
sendMessage((TLRPC.TL_document) messageObject.messageOwner.media.document, null, messageObject.messageOwner.attachPath, did, messageObject.replyMessageObject, null, null);
sendMessage((TLRPC.TL_document) messageObject.messageOwner.media.document, null, messageObject.messageOwner.attachPath, did, messageObject.replyMessageObject, null, null, messageObject.messageOwner.media.ttl_seconds);
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVenue || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo) {
sendMessage(messageObject.messageOwner.media, did, messageObject.replyMessageObject, null, null);
} else if (messageObject.messageOwner.media.phone_number != null) {
@ -670,6 +675,52 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
}
}
public void sendScreenshotMessage(TLRPC.User user, int messageId, TLRPC.Message resendMessage) {
if (user == null || messageId == 0 || user.id == UserConfig.getClientUserId()) {
return;
}
TLRPC.TL_messages_sendScreenshotNotification req = new TLRPC.TL_messages_sendScreenshotNotification();
req.peer = new TLRPC.TL_inputPeerUser();
req.peer.access_hash = user.access_hash;
req.peer.user_id = user.id;
TLRPC.Message message;
if (resendMessage != null) {
message = resendMessage;
req.reply_to_msg_id = messageId;
req.random_id = resendMessage.random_id;
} else {
message = new TLRPC.TL_messageService();
message.random_id = getNextRandomId();
message.dialog_id = user.id;
message.unread = true;
message.out = true;
message.local_id = message.id = UserConfig.getNewMessageId();
message.from_id = UserConfig.getClientUserId();
message.flags |= 256;
message.flags |= 8;
message.reply_to_msg_id = messageId;
message.to_id = new TLRPC.TL_peerUser();
message.to_id.user_id = user.id;
message.date = ConnectionsManager.getInstance().getCurrentTime();
message.action = new TLRPC.TL_messageActionScreenshotTaken();
UserConfig.saveConfig(false);
}
req.random_id = message.random_id;
MessageObject newMsgObj = new MessageObject(message, null, false);
newMsgObj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENDING;
ArrayList<MessageObject> objArr = new ArrayList<>();
objArr.add(newMsgObj);
MessagesController.getInstance().updateInterfaceWithMessages(message.dialog_id, objArr);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
ArrayList<TLRPC.Message> arr = new ArrayList<>();
arr.add(message);
MessagesStorage.getInstance().putMessages(arr, false, true, false, 0);
performSendMessageRequest(req, newMsgObj, null);
}
public void sendSticker(TLRPC.Document document, long peer, MessageObject replyingMessageObject) {
if (document == null) {
return;
@ -718,7 +769,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
}
document = newDocument;
}
SendMessagesHelper.getInstance().sendMessage((TLRPC.TL_document) document, null, null, peer, replyingMessageObject, null, null);
SendMessagesHelper.getInstance().sendMessage((TLRPC.TL_document) document, null, null, peer, replyingMessageObject, null, null, 0);
}
public int sendMessage(ArrayList<MessageObject> messages, final long peer) {
@ -763,7 +814,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
final boolean toMyself = peer == myId;
for (int a = 0; a < messages.size(); a++) {
MessageObject msgObj = messages.get(a);
if (msgObj.getId() <= 0) {
if (msgObj.getId() <= 0 || msgObj.isSecretPhoto()) {
continue;
}
if (!canSendStickers && (msgObj.isSticker() || msgObj.isGif() || msgObj.isGame())) {
@ -784,19 +835,27 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
newMsg.flags = TLRPC.MESSAGE_FLAG_FWD;
} else if (msgObj.getDialogId() != myId) {
newMsg.fwd_from = new TLRPC.TL_messageFwdHeader();
newMsg.fwd_from.channel_post = msgObj.getId();
newMsg.fwd_from.flags |= 4;
if (msgObj.isFromUser()) {
newMsg.fwd_from.from_id = msgObj.messageOwner.from_id;
newMsg.fwd_from.flags |= 1;
} else {
newMsg.fwd_from.channel_id = msgObj.messageOwner.to_id.channel_id;
newMsg.fwd_from.flags |= 2;
if (msgObj.messageOwner.post) {
newMsg.fwd_from.channel_post = msgObj.getId();
newMsg.fwd_from.flags |= 4;
if (msgObj.messageOwner.from_id > 0) {
newMsg.fwd_from.from_id = msgObj.messageOwner.from_id;
newMsg.fwd_from.flags |= 1;
}
if (msgObj.messageOwner.post && msgObj.messageOwner.from_id > 0) {
newMsg.fwd_from.from_id = msgObj.messageOwner.from_id;
newMsg.fwd_from.flags |= 1;
}
}
if (msgObj.messageOwner.post_author != null) {
newMsg.fwd_from.post_author = msgObj.messageOwner.post_author;
newMsg.fwd_from.flags |= 8;
} else if (!msgObj.isOutOwner() && msgObj.messageOwner.from_id > 0 && msgObj.messageOwner.post) {
TLRPC.User signUser = MessagesController.getInstance().getUser(msgObj.messageOwner.from_id);
if (signUser != null) {
newMsg.fwd_from.post_author = ContactsController.formatName(signUser.first_name, signUser.last_name);
newMsg.fwd_from.flags |= 8;
}
}
newMsg.date = msgObj.messageOwner.date;
@ -1286,34 +1345,34 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
}
public void sendMessage(MessageObject retryMessageObject) {
sendMessage(null, null, null, null, null, null, null, retryMessageObject.getDialogId(), retryMessageObject.messageOwner.attachPath, null, null, true, retryMessageObject, null, retryMessageObject.messageOwner.reply_markup, retryMessageObject.messageOwner.params);
sendMessage(null, null, null, null, null, null, null, retryMessageObject.getDialogId(), retryMessageObject.messageOwner.attachPath, null, null, true, retryMessageObject, null, retryMessageObject.messageOwner.reply_markup, retryMessageObject.messageOwner.params, 0);
}
public void sendMessage(TLRPC.User user, long peer, MessageObject reply_to_msg, TLRPC.ReplyMarkup replyMarkup, HashMap<String, String> params) {
sendMessage(null, null, null, null, user, null, null, peer, null, reply_to_msg, null, true, null, null, replyMarkup, params);
sendMessage(null, null, null, null, user, null, null, peer, null, reply_to_msg, null, true, null, null, replyMarkup, params, 0);
}
public void sendMessage(TLRPC.TL_document document, VideoEditedInfo videoEditedInfo, String path, long peer, MessageObject reply_to_msg, TLRPC.ReplyMarkup replyMarkup, HashMap<String, String> params) {
sendMessage(null, null, null, videoEditedInfo, null, document, null, peer, path, reply_to_msg, null, true, null, null, replyMarkup, params);
public void sendMessage(TLRPC.TL_document document, VideoEditedInfo videoEditedInfo, String path, long peer, MessageObject reply_to_msg, TLRPC.ReplyMarkup replyMarkup, HashMap<String, String> params, int ttl) {
sendMessage(null, null, null, videoEditedInfo, null, document, null, peer, path, reply_to_msg, null, true, null, null, replyMarkup, params, ttl);
}
public void sendMessage(String message, long peer, MessageObject reply_to_msg, TLRPC.WebPage webPage, boolean searchLinks, ArrayList<TLRPC.MessageEntity> entities, TLRPC.ReplyMarkup replyMarkup, HashMap<String, String> params) {
sendMessage(message, null, null, null, null, null, null, peer, null, reply_to_msg, webPage, searchLinks, null, entities, replyMarkup, params);
sendMessage(message, null, null, null, null, null, null, peer, null, reply_to_msg, webPage, searchLinks, null, entities, replyMarkup, params, 0);
}
public void sendMessage(TLRPC.MessageMedia location, long peer, MessageObject reply_to_msg, TLRPC.ReplyMarkup replyMarkup, HashMap<String, String> params) {
sendMessage(null, location, null, null, null, null, null, peer, null, reply_to_msg, null, true, null, null, replyMarkup, params);
sendMessage(null, location, null, null, null, null, null, peer, null, reply_to_msg, null, true, null, null, replyMarkup, params, 0);
}
public void sendMessage(TLRPC.TL_game game, long peer, TLRPC.ReplyMarkup replyMarkup, HashMap<String, String> params) {
sendMessage(null, null, null, null, null, null, game, peer, null, null, null, true, null, null, replyMarkup, params);
sendMessage(null, null, null, null, null, null, game, peer, null, null, null, true, null, null, replyMarkup, params, 0);
}
public void sendMessage(TLRPC.TL_photo photo, String path, long peer, MessageObject reply_to_msg, TLRPC.ReplyMarkup replyMarkup, HashMap<String, String> params) {
sendMessage(null, null, photo, null, null, null, null, peer, path, reply_to_msg, null, true, null, null, replyMarkup, params);
public void sendMessage(TLRPC.TL_photo photo, String path, long peer, MessageObject reply_to_msg, TLRPC.ReplyMarkup replyMarkup, HashMap<String, String> params, int ttl) {
sendMessage(null, null, photo, null, null, null, null, peer, path, reply_to_msg, null, true, null, null, replyMarkup, params, ttl);
}
private void sendMessage(String message, TLRPC.MessageMedia location, TLRPC.TL_photo photo, VideoEditedInfo videoEditedInfo, TLRPC.User user, TLRPC.TL_document document, TLRPC.TL_game game, long peer, String path, MessageObject reply_to_msg, TLRPC.WebPage webPage, boolean searchLinks, MessageObject retryMessageObject, ArrayList<TLRPC.MessageEntity> entities, TLRPC.ReplyMarkup replyMarkup, HashMap<String, String> params) {
private void sendMessage(String message, TLRPC.MessageMedia location, TLRPC.TL_photo photo, VideoEditedInfo videoEditedInfo, TLRPC.User user, TLRPC.TL_document document, TLRPC.TL_game game, long peer, String path, MessageObject reply_to_msg, TLRPC.WebPage webPage, boolean searchLinks, MessageObject retryMessageObject, ArrayList<TLRPC.MessageEntity> entities, TLRPC.ReplyMarkup replyMarkup, HashMap<String, String> params, int ttl) {
if (peer == 0) {
return;
}
@ -1439,7 +1498,12 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
newMsg = new TLRPC.TL_message();
}
newMsg.media = new TLRPC.TL_messageMediaPhoto();
newMsg.media.flags |= 3;
newMsg.media.caption = photo.caption != null ? photo.caption : "";
if (ttl != 0) {
newMsg.ttl = newMsg.media.ttl_seconds = ttl;
newMsg.media.flags |= 4;
}
newMsg.media.photo = photo;
if (params != null && params.containsKey("query_id")) {
type = 9;
@ -1492,6 +1556,11 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
newMsg = new TLRPC.TL_message();
}
newMsg.media = new TLRPC.TL_messageMediaDocument();
newMsg.media.flags |= 3;
if (ttl != 0) {
newMsg.ttl = newMsg.media.ttl_seconds = ttl;
newMsg.media.flags |= 4;
}
newMsg.media.caption = document.caption != null ? document.caption : "";
newMsg.media.document = document;
if (params != null && params.containsKey("query_id")) {
@ -1646,7 +1715,11 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
} else {
newMsg.to_id.user_id = encryptedChat.participant_id;
}
newMsg.ttl = encryptedChat.ttl;
if (ttl != 0) {
newMsg.ttl = ttl;
} else {
newMsg.ttl = encryptedChat.ttl;
}
if (newMsg.ttl != 0 && newMsg.media.document != null) {
if (MessageObject.isVoiceMessage(newMsg)) {
int duration = 0;
@ -1657,7 +1730,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
break;
}
}
newMsg.ttl = Math.max(encryptedChat.ttl, duration + 1);
newMsg.ttl = Math.max(newMsg.ttl, duration + 1);
} else if (MessageObject.isVideoMessage(newMsg) || MessageObject.isRoundVideoMessage(newMsg)) {
int duration = 0;
for (int a = 0; a < newMsg.media.document.attributes.size(); a++) {
@ -1667,7 +1740,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
break;
}
}
newMsg.ttl = Math.max(encryptedChat.ttl, duration + 1);
newMsg.ttl = Math.max(newMsg.ttl, duration + 1);
}
}
}
@ -1785,6 +1858,10 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
if (photo.access_hash == 0) {
inputMedia = new TLRPC.TL_inputMediaUploadedPhoto();
inputMedia.caption = photo.caption != null ? photo.caption : "";
if (ttl != 0) {
newMsg.ttl = inputMedia.ttl_seconds = ttl;
inputMedia.flags |= 2;
}
if (params != null) {
String masks = params.get("masks");
if (masks != null) {
@ -1815,14 +1892,14 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
}
} else if (type == 3) {
if (document.access_hash == 0) {
if (document.thumb.location != null) {
inputMedia = new TLRPC.TL_inputMediaUploadedThumbDocument();
} else {
inputMedia = new TLRPC.TL_inputMediaUploadedDocument();
}
inputMedia = new TLRPC.TL_inputMediaUploadedDocument();
inputMedia.caption = document.caption != null ? document.caption : "";
inputMedia.mime_type = document.mime_type;
inputMedia.attributes = document.attributes;
if (ttl != 0) {
newMsg.ttl = inputMedia.ttl_seconds = ttl;
inputMedia.flags |= 2;
}
delayedMessage = new DelayedMessage();
delayedMessage.originalPath = originalPath;
delayedMessage.type = 1;
@ -1853,10 +1930,10 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
inputMedia.q = args[1];
}
} else {
if (document.thumb.location != null && document.thumb.location instanceof TLRPC.TL_fileLocation) {
inputMedia = new TLRPC.TL_inputMediaUploadedThumbDocument();
} else {
inputMedia = new TLRPC.TL_inputMediaUploadedDocument();
inputMedia = new TLRPC.TL_inputMediaUploadedDocument();
if (ttl != 0) {
newMsg.ttl = inputMedia.ttl_seconds = ttl;
inputMedia.flags |= 2;
}
delayedMessage = new DelayedMessage();
delayedMessage.originalPath = originalPath;
@ -1882,6 +1959,10 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
inputMedia.mime_type = document.mime_type;
inputMedia.attributes = document.attributes;
inputMedia.caption = document.caption != null ? document.caption : "";
if (ttl != 0) {
newMsg.ttl = inputMedia.ttl_seconds = ttl;
inputMedia.flags |= 2;
}
delayedMessage = new DelayedMessage();
delayedMessage.type = 3;
delayedMessage.obj = newMsgObj;
@ -2192,7 +2273,11 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
if (retryMessageObject.getId() >= 0) {
reqSend.id.add(retryMessageObject.getId());
} else {
reqSend.id.add(retryMessageObject.messageOwner.fwd_msg_id);
if (retryMessageObject.messageOwner.fwd_from != null) {
reqSend.id.add(retryMessageObject.messageOwner.fwd_from.channel_post);
} else {
reqSend.id.add(retryMessageObject.messageOwner.fwd_msg_id);
}
}
performSendMessageRequest(reqSend, newMsgObj, null);
} else if (type == 9) {
@ -2245,7 +2330,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
}
if (!file.exists()) {
putToDelayedMessages(FileLoader.getAttachFileName(message.location), message);
FileLoader.getInstance().loadFile(message.location, "jpg", 0, false);
FileLoader.getInstance().loadFile(message.location, "jpg", 0, 0);
return;
}
}
@ -2313,7 +2398,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
File file = new File(location);
if (!file.exists()) {
putToDelayedMessages(FileLoader.getAttachFileName(message.documentLocation), message);
FileLoader.getInstance().loadFile(message.documentLocation, true, false);
FileLoader.getInstance().loadFile(message.documentLocation, true, 0);
return;
}
}
@ -2352,7 +2437,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
File file = new File(location);
if (!file.exists()) {
putToDelayedMessages(FileLoader.getAttachFileName(message.documentLocation), message);
FileLoader.getInstance().loadFile(message.documentLocation, true, false);
FileLoader.getInstance().loadFile(message.documentLocation, true, 0);
return;
}
}
@ -2563,7 +2648,9 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
return;
}
if (sentMessage.media instanceof TLRPC.TL_messageMediaPhoto && sentMessage.media.photo != null && newMsg.media instanceof TLRPC.TL_messageMediaPhoto && newMsg.media.photo != null) {
MessagesStorage.getInstance().putSentFile(originalPath, sentMessage.media.photo, 0);
if (sentMessage.media.ttl_seconds == 0) {
MessagesStorage.getInstance().putSentFile(originalPath, sentMessage.media.photo, 0);
}
if (newMsg.media.photo.sizes.size() == 1 && newMsg.media.photo.sizes.get(0).location instanceof TLRPC.TL_fileLocationUnavailable) {
newMsg.media.photo.sizes = sentMessage.media.photo.sizes;
@ -2586,7 +2673,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
}
File cacheFile = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), fileName + ".jpg");
File cacheFile2;
if (sentMessage.media.photo.sizes.size() == 1 || size.w > 90 || size.h > 90) {
if (sentMessage.media.ttl_seconds == 0 && (sentMessage.media.photo.sizes.size() == 1 || size.w > 90 || size.h > 90)) {
cacheFile2 = FileLoader.getPathToAttach(size);
} else {
cacheFile2 = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), fileName2 + ".jpg");
@ -2606,10 +2693,14 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
newMsg.media.photo.access_hash = sentMessage.media.photo.access_hash;
} else if (sentMessage.media instanceof TLRPC.TL_messageMediaDocument && sentMessage.media.document != null && newMsg.media instanceof TLRPC.TL_messageMediaDocument && newMsg.media.document != null) {
if (MessageObject.isVideoMessage(sentMessage)) {
MessagesStorage.getInstance().putSentFile(originalPath, sentMessage.media.document, 2);
if (sentMessage.media.ttl_seconds == 0) {
MessagesStorage.getInstance().putSentFile(originalPath, sentMessage.media.document, 2);
}
sentMessage.attachPath = newMsg.attachPath;
} else if (!MessageObject.isVoiceMessage(sentMessage) && !MessageObject.isRoundVideoMessage(sentMessage)) {
MessagesStorage.getInstance().putSentFile(originalPath, sentMessage.media.document, 1);
if (sentMessage.media.ttl_seconds == 0) {
MessagesStorage.getInstance().putSentFile(originalPath, sentMessage.media.document, 1);
}
}
TLRPC.PhotoSize size2 = newMsg.media.document.thumb;
@ -2665,7 +2756,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
if (newMsg.attachPath != null && newMsg.attachPath.startsWith(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE).getAbsolutePath())) {
File cacheFile = new File(newMsg.attachPath);
File cacheFile2 = FileLoader.getPathToAttach(sentMessage.media.document);
File cacheFile2 = FileLoader.getPathToAttach(sentMessage.media.document, sentMessage.media.ttl_seconds != 0);
if (!cacheFile.renameTo(cacheFile2)) {
sentMessage.attachPath = newMsg.attachPath;
sentMessage.message = newMsg.message;
@ -2925,7 +3016,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
SendMessagesHelper.getInstance().sendMessage(documentFinal, null, pathFinal, dialog_id, reply_to_msg, null, params);
SendMessagesHelper.getInstance().sendMessage(documentFinal, null, pathFinal, dialog_id, reply_to_msg, null, params, 0);
}
});
return true;
@ -2990,7 +3081,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
SendMessagesHelper.getInstance().sendMessage(documentFinal, null, messageObject.messageOwner.attachPath, dialog_id, reply_to_msg, null, params);
SendMessagesHelper.getInstance().sendMessage(documentFinal, null, messageObject.messageOwner.attachPath, dialog_id, reply_to_msg, null, params, 0);
}
});
}
@ -3040,10 +3131,11 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
}).start();
}
public static void prepareSendingPhoto(String imageFilePath, Uri imageUri, long dialog_id, MessageObject reply_to_msg, CharSequence caption, ArrayList<TLRPC.InputDocument> stickers, InputContentInfoCompat inputContent) {
public static void prepareSendingPhoto(String imageFilePath, Uri imageUri, long dialog_id, MessageObject reply_to_msg, CharSequence caption, ArrayList<TLRPC.InputDocument> stickers, InputContentInfoCompat inputContent, int ttl) {
ArrayList<String> paths = null;
ArrayList<Uri> uris = null;
ArrayList<String> captions = null;
ArrayList<Integer> ttls = null;
ArrayList<ArrayList<TLRPC.InputDocument>> masks = null;
if (imageFilePath != null && imageFilePath.length() != 0) {
paths = new ArrayList<>();
@ -3053,6 +3145,10 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
uris = new ArrayList<>();
uris.add(imageUri);
}
if (ttl != 0) {
ttls = new ArrayList<>();
ttls.add(ttl);
}
if (caption != null) {
captions = new ArrayList<>();
captions.add(caption.toString());
@ -3061,7 +3157,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
masks = new ArrayList<>();
masks.add(new ArrayList<>(stickers));
}
prepareSendingPhotos(paths, uris, dialog_id, reply_to_msg, captions, masks, inputContent, false);
prepareSendingPhotos(paths, uris, dialog_id, reply_to_msg, captions, masks, inputContent, false, ttls);
}
public static void prepareSendingBotContextResult(final TLRPC.BotInlineResult result, final HashMap<String, String> params, final long dialog_id, final MessageObject reply_to_msg) {
@ -3276,10 +3372,10 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
public void run() {
if (finalDocument != null) {
finalDocument.caption = result.send_message.caption;
SendMessagesHelper.getInstance().sendMessage(finalDocument, null, finalPathFinal, dialog_id, reply_to_msg, result.send_message.reply_markup, params);
SendMessagesHelper.getInstance().sendMessage(finalDocument, null, finalPathFinal, dialog_id, reply_to_msg, result.send_message.reply_markup, params, 0);
} else if (finalPhoto != null) {
finalPhoto.caption = result.send_message.caption;
SendMessagesHelper.getInstance().sendMessage(finalPhoto, result.content_url, dialog_id, reply_to_msg, result.send_message.reply_markup, params);
SendMessagesHelper.getInstance().sendMessage(finalPhoto, result.content_url, dialog_id, reply_to_msg, result.send_message.reply_markup, params, 0);
} else if (finalGame != null) {
SendMessagesHelper.getInstance().sendMessage(finalGame, dialog_id, result.send_message.reply_markup, params);
}
@ -3331,6 +3427,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
boolean isEncrypted = (int) dialog_id == 0;
for (int a = 0; a < photos.size(); a++) {
final MediaController.SearchImage searchImage = photos.get(a);
final int ttl = searchImage.ttl;
if (searchImage.type == 1) {
final HashMap<String, String> params = new HashMap<>();
TLRPC.TL_document document = null;
@ -3417,13 +3514,13 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
SendMessagesHelper.getInstance().sendMessage(documentFinal, null, pathFinal, dialog_id, reply_to_msg, null, params);
SendMessagesHelper.getInstance().sendMessage(documentFinal, null, pathFinal, dialog_id, reply_to_msg, null, params, 0);
}
});
} else {
boolean needDownloadHttp = true;
TLRPC.TL_photo photo = null;
if (!isEncrypted) {
if (!isEncrypted && ttl == 0) {
photo = (TLRPC.TL_photo) MessagesStorage.getInstance().getSentFile(searchImage.imageUrl, !isEncrypted ? 0 : 3);
}
if (photo == null) {
@ -3467,7 +3564,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
SendMessagesHelper.getInstance().sendMessage(photoFinal, needDownloadHttpFinal ? searchImage.imageUrl : null, dialog_id, reply_to_msg, null, params);
SendMessagesHelper.getInstance().sendMessage(photoFinal, needDownloadHttpFinal ? searchImage.imageUrl : null, dialog_id, reply_to_msg, null, params, ttl);
}
});
}
@ -3517,7 +3614,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
});
}
public static void prepareSendingPhotos(ArrayList<String> paths, ArrayList<Uri> uris, final long dialog_id, final MessageObject reply_to_msg, final ArrayList<String> captions, final ArrayList<ArrayList<TLRPC.InputDocument>> masks, final InputContentInfoCompat inputContent, final boolean forceDocument) {
public static void prepareSendingPhotos(ArrayList<String> paths, ArrayList<Uri> uris, final long dialog_id, final MessageObject reply_to_msg, final ArrayList<String> captions, final ArrayList<ArrayList<TLRPC.InputDocument>> masks, final InputContentInfoCompat inputContent, final boolean forceDocument, final ArrayList<Integer> ttls) {
if (paths == null && uris == null || paths != null && paths.isEmpty() || uris != null && uris.isEmpty()) {
return;
}
@ -3554,6 +3651,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
tempPath = AndroidUtilities.getPath(uri);
originalPath = uri.toString();
}
final int ttl = ttls != null ? ttls.get(a) : 0;
boolean isDocument = false;
if (forceDocument) {
@ -3598,7 +3696,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
originalPath = null;
}
TLRPC.TL_photo photo = null;
if (!isEncrypted) {
if (!isEncrypted && ttl == 0) {
photo = (TLRPC.TL_photo) MessagesStorage.getInstance().getSentFile(originalPath, !isEncrypted ? 0 : 3);
if (photo == null && uri != null) {
photo = (TLRPC.TL_photo) MessagesStorage.getInstance().getSentFile(AndroidUtilities.getPath(uri), !isEncrypted ? 0 : 3);
@ -3630,7 +3728,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
SendMessagesHelper.getInstance().sendMessage(photoFinal, null, dialog_id, reply_to_msg, null, params);
SendMessagesHelper.getInstance().sendMessage(photoFinal, null, dialog_id, reply_to_msg, null, params, ttl);
}
});
} else {
@ -3747,7 +3845,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
return bitmap;
}
public static void prepareSendingVideo(final String videoPath, final long estimatedSize, final long duration, final int width, final int height, final VideoEditedInfo videoEditedInfo, final long dialog_id, final MessageObject reply_to_msg, final CharSequence caption) {
public static void prepareSendingVideo(final String videoPath, final long estimatedSize, final long duration, final int width, final int height, final VideoEditedInfo videoEditedInfo, final long dialog_id, final MessageObject reply_to_msg, final CharSequence caption, final int ttl) {
if (videoPath == null || videoPath.length() == 0) {
return;
}
@ -3778,7 +3876,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
startTime = videoEditedInfo.startTime >= 0 ? videoEditedInfo.startTime : 0;
}
TLRPC.TL_document document = null;
if (!isEncrypted) {
if (!isEncrypted && ttl == 0) {
document = (TLRPC.TL_document) MessagesStorage.getInstance().getSentFile(originalPath, !isEncrypted ? 2 : 5);
}
if (document == null) {
@ -3878,7 +3976,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
if (thumbFinal != null && thumbKeyFinal != null) {
ImageLoader.getInstance().putImageToCache(new BitmapDrawable(thumbFinal), thumbKeyFinal);
}
SendMessagesHelper.getInstance().sendMessage(videoFinal, videoEditedInfo, finalPath, dialog_id, reply_to_msg, null, params);
SendMessagesHelper.getInstance().sendMessage(videoFinal, videoEditedInfo, finalPath, dialog_id, reply_to_msg, null, params, ttl);
}
});
} else {

View File

@ -53,6 +53,7 @@ public class Utilities {
public native static int convertVideoFrame(ByteBuffer src, ByteBuffer dest, int destFormat, int width, int height, int padding, int swap);
private native static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length);
public native static void aesCtrDecryption(ByteBuffer buffer, byte[] key, byte[] iv, int offset, int length);
public native static void aesCtrDecryptionByteArray(byte[] buffer, byte[] key, byte[] iv, int offset, int length, int n);
public native static String readlink(String path);
public static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) {

View File

@ -7,7 +7,6 @@ import com.google.android.gms.wearable.Channel;
import com.google.android.gms.wearable.Wearable;
import com.google.android.gms.wearable.WearableListenerService;
import org.json.JSONObject;
import org.telegram.tgnet.TLRPC;
import java.io.BufferedOutputStream;
@ -21,144 +20,155 @@ import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by grishka on 16.06.17.
*/
public class WearDataLayerListenerService extends WearableListenerService{
public class WearDataLayerListenerService extends WearableListenerService {
@Override
public void onCreate(){
public void onCreate() {
super.onCreate();
FileLog.d("WearableDataLayer service created");
}
@Override
public void onDestroy(){
public void onDestroy() {
super.onDestroy();
FileLog.d("WearableDataLayer service destroyed");
}
@Override
public void onChannelOpened(final Channel ch){
new Thread(new Runnable(){
@Override
public void run(){
GoogleApiClient apiClient=new GoogleApiClient.Builder(WearDataLayerListenerService.this).addApi(Wearable.API).build();
if(!apiClient.blockingConnect().isSuccess()){
FileLog.e("failed to connect google api client");
return;
}
String path=ch.getPath();
FileLog.d("wear channel path: "+path);
try{
if("/getCurrentUser".equals(path)){
DataOutputStream out=new DataOutputStream(new BufferedOutputStream(ch.getOutputStream(apiClient).await().getOutputStream()));
if(UserConfig.isClientActivated()){
final TLRPC.User user=UserConfig.getCurrentUser();
out.writeInt(user.id);
out.writeUTF(user.first_name);
out.writeUTF(user.last_name);
out.writeUTF(user.phone);
if(user.photo!=null){
final File photo=FileLoader.getPathToAttach(user.photo.photo_small, true);
final CyclicBarrier barrier=new CyclicBarrier(2);
if(!photo.exists()){
final NotificationCenter.NotificationCenterDelegate listener=new NotificationCenter.NotificationCenterDelegate(){
@Override
public void didReceivedNotification(int id, Object... args){
if(id==NotificationCenter.FileDidLoaded){
FileLog.d("file loaded: "+args[0]+" "+args[0].getClass().getName());
if(args[0].equals(photo.getName())){
FileLog.e("LOADED USER PHOTO");
try{barrier.await(10, TimeUnit.MILLISECONDS);}catch(Exception x){}
}
public void onChannelOpened(final Channel ch) {
//new Thread(new Runnable(){
// @Override
// public void run(){
GoogleApiClient apiClient = new GoogleApiClient.Builder(WearDataLayerListenerService.this).addApi(Wearable.API).build();
if (!apiClient.blockingConnect().isSuccess()) {
FileLog.e("failed to connect google api client");
return;
}
String path = ch.getPath();
FileLog.d("wear channel path: " + path);
try {
if ("/getCurrentUser".equals(path)) {
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(ch.getOutputStream(apiClient).await().getOutputStream()));
if (UserConfig.isClientActivated()) {
final TLRPC.User user = UserConfig.getCurrentUser();
out.writeInt(user.id);
out.writeUTF(user.first_name);
out.writeUTF(user.last_name);
out.writeUTF(user.phone);
if (user.photo != null) {
final File photo = FileLoader.getPathToAttach(user.photo.photo_small, true);
final CyclicBarrier barrier = new CyclicBarrier(2);
if (!photo.exists()) {
final NotificationCenter.NotificationCenterDelegate listener = new NotificationCenter.NotificationCenterDelegate() {
@Override
public void didReceivedNotification(int id, Object... args) {
if (id == NotificationCenter.FileDidLoaded) {
FileLog.d("file loaded: " + args[0] + " " + args[0].getClass().getName());
if (args[0].equals(photo.getName())) {
FileLog.e("LOADED USER PHOTO");
try {
barrier.await(10, TimeUnit.MILLISECONDS);
} catch (Exception ignore) {
}
}
};
AndroidUtilities.runOnUIThread(new Runnable(){
@Override
public void run(){
NotificationCenter.getInstance().addObserver(listener, NotificationCenter.FileDidLoaded);
FileLoader.getInstance().loadFile(user.photo.photo_small, null, 0, true);
}
});
try{barrier.await(10, TimeUnit.SECONDS);}catch(Exception x){}
AndroidUtilities.runOnUIThread(new Runnable(){
@Override
public void run(){
NotificationCenter.getInstance().removeObserver(listener, NotificationCenter.FileDidLoaded);
}
});
}
}
if(photo.exists() && photo.length()<=50*1024*1024){
byte[] photoData=new byte[(int)photo.length()];
FileInputStream photoIn=new FileInputStream(photo);
new DataInputStream(photoIn).readFully(photoData);
photoIn.close();
out.writeInt(photoData.length);
out.write(photoData);
}else{
out.writeInt(0);
};
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
NotificationCenter.getInstance().addObserver(listener, NotificationCenter.FileDidLoaded);
FileLoader.getInstance().loadFile(user.photo.photo_small, null, 0, 1);
}
}else{
out.writeInt(0);
});
try {
barrier.await(10, TimeUnit.SECONDS);
} catch (Exception ignore) {
}
}else{
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
NotificationCenter.getInstance().removeObserver(listener, NotificationCenter.FileDidLoaded);
}
});
}
if (photo.exists() && photo.length() <= 50 * 1024 * 1024) {
byte[] photoData = new byte[(int) photo.length()];
FileInputStream photoIn = new FileInputStream(photo);
new DataInputStream(photoIn).readFully(photoData);
photoIn.close();
out.writeInt(photoData.length);
out.write(photoData);
} else {
out.writeInt(0);
}
out.flush();
out.close();
}else if("/waitForAuthCode".equals(path)){
final String[] code={null};
final CyclicBarrier barrier=new CyclicBarrier(2);
final NotificationCenter.NotificationCenterDelegate listener=new NotificationCenter.NotificationCenterDelegate(){
@Override
public void didReceivedNotification(int id, Object... args){
if(id==NotificationCenter.didReceivedNewMessages){
long did = (Long) args[0];
if(did==777000){
ArrayList<MessageObject> arr = (ArrayList<MessageObject>) args[1];
if(arr.size()>0){
MessageObject msg=arr.get(0);
if(!TextUtils.isEmpty(msg.messageText)){
Matcher matcher=Pattern.compile("[0-9]+").matcher(msg.messageText);
if(matcher.find()){
code[0]=matcher.group();
try{barrier.await(10, TimeUnit.MILLISECONDS);}catch(Exception x){}
}
} else {
out.writeInt(0);
}
} else {
out.writeInt(0);
}
out.flush();
out.close();
} else if ("/waitForAuthCode".equals(path)) {
final String[] code = {null};
final CyclicBarrier barrier = new CyclicBarrier(2);
final NotificationCenter.NotificationCenterDelegate listener = new NotificationCenter.NotificationCenterDelegate() {
@Override
public void didReceivedNotification(int id, Object... args) {
if (id == NotificationCenter.didReceivedNewMessages) {
long did = (Long) args[0];
if (did == 777000) {
ArrayList<MessageObject> arr = (ArrayList<MessageObject>) args[1];
if (arr.size() > 0) {
MessageObject msg = arr.get(0);
if (!TextUtils.isEmpty(msg.messageText)) {
Matcher matcher = Pattern.compile("[0-9]+").matcher(msg.messageText);
if (matcher.find()) {
code[0] = matcher.group();
try {
barrier.await(10, TimeUnit.MILLISECONDS);
} catch (Exception ignore) {
}
}
}
}
}
};
AndroidUtilities.runOnUIThread(new Runnable(){
@Override
public void run(){
NotificationCenter.getInstance().addObserver(listener, NotificationCenter.didReceivedNewMessages);
}
});
try{barrier.await(10, TimeUnit.SECONDS);}catch(Exception x){}
AndroidUtilities.runOnUIThread(new Runnable(){
@Override
public void run(){
NotificationCenter.getInstance().removeObserver(listener, NotificationCenter.didReceivedNewMessages);
}
});
DataOutputStream out=new DataOutputStream(ch.getOutputStream(apiClient).await().getOutputStream());
if(code!=null)
out.writeUTF(code[0]);
else
out.writeUTF("");
out.flush();
out.close();
}
}
}catch(Exception x){
FileLog.e("error processing wear request", x);
};
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
NotificationCenter.getInstance().addObserver(listener, NotificationCenter.didReceivedNewMessages);
}
});
try {
barrier.await(15, TimeUnit.SECONDS);
} catch (Exception ignore) {
}
ch.close(apiClient).await();
apiClient.disconnect();
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
NotificationCenter.getInstance().removeObserver(listener, NotificationCenter.didReceivedNewMessages);
}
});
DataOutputStream out = new DataOutputStream(ch.getOutputStream(apiClient).await().getOutputStream());
if (code[0] != null)
out.writeUTF(code[0]);
else
out.writeUTF("");
out.flush();
out.close();
}
}).start();
} catch (Exception x) {
FileLog.e("error processing wear request", x);
}
ch.close(apiClient).await();
apiClient.disconnect();
FileLog.d("WearableDataLayer channel thread exiting");
// }
//}).start();
}
}

View File

@ -201,7 +201,7 @@ public class Browser {
} else if ("telegram.me".equals(host) || "t.me".equals(host) || "telegram.dog".equals(host) || "telesco.pe".equals(host)) {
String path = uri.getPath();
if (path != null && path.length() > 1) {
return true;
return !path.toLowerCase().equals("/iv");
}
}
return false;

View File

@ -102,6 +102,9 @@ public class CameraController implements MediaRecorder.OnInfoListener {
List<Camera.Size> list = params.getSupportedPreviewSizes();
for (int a = 0; a < list.size(); a++) {
Camera.Size size = list.get(a);
if (size.width == 1280 && size.height != 720) {
continue;
}
if (size.height < 2160 && size.width < 2160) {
cameraInfo.previewSizes.add(new Size(size.width, size.height));
FileLog.e("preview size = " + size.width + " " + size.height);
@ -111,6 +114,9 @@ public class CameraController implements MediaRecorder.OnInfoListener {
list = params.getSupportedPictureSizes();
for (int a = 0; a < list.size(); a++) {
Camera.Size size = list.get(a);
if (size.width == 1280 && size.height != 720) {
continue;
}
if (!"samsung".equals(Build.MANUFACTURER) || !"jflteuc".equals(Build.PRODUCT) || size.width < 2048) {
cameraInfo.pictureSizes.add(new Size(size.width, size.height));
FileLog.e("picture size = " + size.width + " " + size.height);
@ -119,6 +125,25 @@ public class CameraController implements MediaRecorder.OnInfoListener {
camera.release();
result.add(cameraInfo);
Comparator<Size> comparator = new Comparator<Size>() {
@Override
public int compare(Size o1, Size o2) {
if (o1.mWidth < o2.mWidth) {
return 1;
} else if (o1.mWidth > o2.mWidth) {
return -1;
} else {
if (o1.mHeight < o2.mHeight) {
return 1;
} else if (o1.mHeight > o2.mHeight) {
return -1;
}
return 0;
}
}
};
Collections.sort(cameraInfo.previewSizes, comparator);
Collections.sort(cameraInfo.pictureSizes, comparator);
}
cameraInfos = result;
}
@ -648,7 +673,6 @@ public class CameraController implements MediaRecorder.OnInfoListener {
onVideoTakeCallback = null;
}
} catch (Exception e) {
FileLog.e(e);
}
}
});

View File

@ -24,7 +24,6 @@ import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.FileLog;
import java.util.ArrayList;
import java.util.List;
public class CameraSession {
@ -400,7 +399,17 @@ public class CameraSession {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraInfo.cameraId, info);
int displayOrientation = getDisplayOrientation(info, false);
recorder.setOrientationHint(displayOrientation);
int outputOrientation = 0;
if (jpegOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
outputOrientation = (info.orientation - jpegOrientation + 360) % 360;
} else {
outputOrientation = (info.orientation + jpegOrientation) % 360;
}
}
recorder.setOrientationHint(outputOrientation);
int highProfile = getHigh();
boolean canGoHigh = CamcorderProfile.hasProfile(cameraInfo.cameraId, highProfile);

View File

@ -147,7 +147,7 @@ public class SharedMediaQuery {
if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
return MEDIA_PHOTOVIDEO;
} else if (message.media instanceof TLRPC.TL_messageMediaDocument) {
if (MessageObject.isVoiceMessage(message)) {
if (MessageObject.isVoiceMessage(message) || MessageObject.isRoundVideoMessage(message)) {
return MEDIA_AUDIO;
} else if (MessageObject.isVideoMessage(message)) {
return MEDIA_PHOTOVIDEO;
@ -170,7 +170,9 @@ public class SharedMediaQuery {
}
public static boolean canAddMessageToMedia(TLRPC.Message message) {
if (message instanceof TLRPC.TL_message_secret && message.media instanceof TLRPC.TL_messageMediaPhoto && message.ttl != 0 && message.ttl <= 60) {
if (message instanceof TLRPC.TL_message && (message.media instanceof TLRPC.TL_messageMediaPhoto || message.media instanceof TLRPC.TL_messageMediaDocument) && message.media.ttl_seconds != 0) {
return false;
} else if (message instanceof TLRPC.TL_message_secret && message.media instanceof TLRPC.TL_messageMediaPhoto && message.ttl != 0 && message.ttl <= 60) {
return false;
} else if (message.media instanceof TLRPC.TL_messageMediaPhoto ||
message.media instanceof TLRPC.TL_messageMediaDocument && !MessageObject.isGifDocument(message.media.document)) {

View File

@ -0,0 +1,139 @@
/*
* This is the source code of Telegram for Android v. 3.x.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-2017.
*/
package org.telegram.messenger.secretmedia;
import android.net.Uri;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.Utilities;
import org.telegram.messenger.exoplayer2.C;
import org.telegram.messenger.exoplayer2.upstream.DataSource;
import org.telegram.messenger.exoplayer2.upstream.DataSpec;
import org.telegram.messenger.exoplayer2.upstream.TransferListener;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public final class EncryptedFileDataSource implements DataSource {
/**
* Thrown when IOException is encountered during local file read operation.
*/
public static class EncryptedFileDataSourceException extends IOException {
public EncryptedFileDataSourceException(IOException cause) {
super(cause);
}
}
private final TransferListener<? super EncryptedFileDataSource> listener;
private RandomAccessFile file;
private Uri uri;
private long bytesRemaining;
private boolean opened;
private byte[] key = new byte[32];
private byte[] iv = new byte[16];
private int fileOffset;
public EncryptedFileDataSource() {
this(null);
}
public EncryptedFileDataSource(TransferListener<? super EncryptedFileDataSource> listener) {
this.listener = listener;
}
@Override
public long open(DataSpec dataSpec) throws EncryptedFileDataSourceException {
try {
uri = dataSpec.uri;
File path = new File(dataSpec.uri.getPath());
String name = path.getName();
File keyPath = new File(FileLoader.getInternalCacheDir(), name + ".key");
RandomAccessFile keyFile = new RandomAccessFile(keyPath, "r");
keyFile.read(key);
keyFile.read(iv);
keyFile.close();
file = new RandomAccessFile(path, "r");
file.seek(dataSpec.position);
fileOffset = (int) dataSpec.position;
bytesRemaining = dataSpec.length == C.LENGTH_UNSET ? file.length() - dataSpec.position : dataSpec.length;
if (bytesRemaining < 0) {
throw new EOFException();
}
} catch (IOException e) {
throw new EncryptedFileDataSourceException(e);
}
opened = true;
if (listener != null) {
listener.onTransferStart(this, dataSpec);
}
return bytesRemaining;
}
@Override
public int read(byte[] buffer, int offset, int readLength) throws EncryptedFileDataSourceException {
if (readLength == 0) {
return 0;
} else if (bytesRemaining == 0) {
return C.RESULT_END_OF_INPUT;
} else {
int bytesRead;
try {
bytesRead = file.read(buffer, offset, (int) Math.min(bytesRemaining, readLength));
Utilities.aesCtrDecryptionByteArray(buffer, key, iv, offset, bytesRead, fileOffset);
fileOffset += bytesRead;
} catch (IOException e) {
throw new EncryptedFileDataSourceException(e);
}
if (bytesRead > 0) {
bytesRemaining -= bytesRead;
if (listener != null) {
listener.onBytesTransferred(this, bytesRead);
}
}
return bytesRead;
}
}
@Override
public Uri getUri() {
return uri;
}
@Override
public void close() throws EncryptedFileDataSourceException {
uri = null;
fileOffset = 0;
try {
if (file != null) {
file.close();
}
} catch (IOException e) {
throw new EncryptedFileDataSourceException(e);
} finally {
file = null;
if (opened) {
opened = false;
if (listener != null) {
listener.onTransferEnd(this);
}
}
}
}
}

View File

@ -0,0 +1,56 @@
/*
* This is the source code of Telegram for Android v. 3.x.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-2017.
*/
package org.telegram.messenger.secretmedia;
import org.telegram.messenger.Utilities;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
public class EncryptedFileInputStream extends FileInputStream {
private byte[] key = new byte[32];
private byte[] iv = new byte[16];
private int fileOffset;
public EncryptedFileInputStream(File file, File keyFile) throws Exception {
super(file);
RandomAccessFile randomAccessFile = new RandomAccessFile(keyFile, "r");
randomAccessFile.read(key, 0, 32);
randomAccessFile.read(iv, 0, 16);
randomAccessFile.close();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int result = super.read(b, off, len);
Utilities.aesCtrDecryptionByteArray(b, key, iv, off, len, fileOffset);
fileOffset += len;
return result;
}
@Override
public long skip(long n) throws IOException {
fileOffset += n;
return super.skip(n);
}
public static void decryptBytesWithKeyFile(byte[] bytes, int offset, int length, File keyFile) throws Exception {
byte[] key = new byte[32];
byte[] iv = new byte[16];
RandomAccessFile randomAccessFile = new RandomAccessFile(keyFile, "r");
randomAccessFile.read(key, 0, 32);
randomAccessFile.read(iv, 0, 16);
randomAccessFile.close();
Utilities.aesCtrDecryptionByteArray(bytes, key, iv, offset, length, 0);
}
}

View File

@ -0,0 +1,139 @@
/*
* This is the source code of Telegram for Android v. 3.x.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-2017.
*/
package org.telegram.messenger.secretmedia;
import android.content.Context;
import android.net.Uri;
import org.telegram.messenger.exoplayer2.upstream.AssetDataSource;
import org.telegram.messenger.exoplayer2.upstream.ContentDataSource;
import org.telegram.messenger.exoplayer2.upstream.DataSource;
import org.telegram.messenger.exoplayer2.upstream.DataSpec;
import org.telegram.messenger.exoplayer2.upstream.DefaultHttpDataSource;
import org.telegram.messenger.exoplayer2.upstream.FileDataSource;
import org.telegram.messenger.exoplayer2.upstream.TransferListener;
import org.telegram.messenger.exoplayer2.util.Assertions;
import org.telegram.messenger.exoplayer2.util.Util;
import java.io.IOException;
public final class ExtendedDefaultDataSource implements DataSource {
private static final String SCHEME_ASSET = "asset";
private static final String SCHEME_CONTENT = "content";
private final DataSource baseDataSource;
private final DataSource fileDataSource;
private final DataSource encryptedFileDataSource;
private final DataSource assetDataSource;
private final DataSource contentDataSource;
private DataSource dataSource;
/**
* Constructs a new instance, optionally configured to follow cross-protocol redirects.
*
* @param context A context.
* @param listener An optional listener.
* @param userAgent The User-Agent string that should be used when requesting remote data.
* @param allowCrossProtocolRedirects Whether cross-protocol redirects (i.e. redirects from HTTP
* to HTTPS and vice versa) are enabled when fetching remote data.
*/
public ExtendedDefaultDataSource(Context context, TransferListener<? super DataSource> listener,
String userAgent, boolean allowCrossProtocolRedirects) {
this(context, listener, userAgent, DefaultHttpDataSource.DEFAULT_CONNECT_TIMEOUT_MILLIS,
DefaultHttpDataSource.DEFAULT_READ_TIMEOUT_MILLIS, allowCrossProtocolRedirects);
}
/**
* Constructs a new instance, optionally configured to follow cross-protocol redirects.
*
* @param context A context.
* @param listener An optional listener.
* @param userAgent The User-Agent string that should be used when requesting remote data.
* @param connectTimeoutMillis The connection timeout that should be used when requesting remote
* data, in milliseconds. A timeout of zero is interpreted as an infinite timeout.
* @param readTimeoutMillis The read timeout that should be used when requesting remote data,
* in milliseconds. A timeout of zero is interpreted as an infinite timeout.
* @param allowCrossProtocolRedirects Whether cross-protocol redirects (i.e. redirects from HTTP
* to HTTPS and vice versa) are enabled when fetching remote data.
*/
public ExtendedDefaultDataSource(Context context, TransferListener<? super DataSource> listener,
String userAgent, int connectTimeoutMillis, int readTimeoutMillis,
boolean allowCrossProtocolRedirects) {
this(context, listener,
new DefaultHttpDataSource(userAgent, null, listener, connectTimeoutMillis,
readTimeoutMillis, allowCrossProtocolRedirects, null));
}
/**
* Constructs a new instance that delegates to a provided {@link DataSource} for URI schemes other
* than file, asset and content.
*
* @param context A context.
* @param listener An optional listener.
* @param baseDataSource A {@link DataSource} to use for URI schemes other than file, asset and
* content. This {@link DataSource} should normally support at least http(s).
*/
public ExtendedDefaultDataSource(Context context, TransferListener<? super DataSource> listener,
DataSource baseDataSource) {
this.baseDataSource = Assertions.checkNotNull(baseDataSource);
this.fileDataSource = new FileDataSource(listener);
this.encryptedFileDataSource = new EncryptedFileDataSource(listener);
this.assetDataSource = new AssetDataSource(context, listener);
this.contentDataSource = new ContentDataSource(context, listener);
}
@Override
public long open(DataSpec dataSpec) throws IOException {
Assertions.checkState(dataSource == null);
// Choose the correct source for the scheme.
String scheme = dataSpec.uri.getScheme();
if (Util.isLocalFileUri(dataSpec.uri)) {
if (dataSpec.uri.getPath().startsWith("/android_asset/")) {
dataSource = assetDataSource;
} else {
if (dataSpec.uri.getPath().endsWith(".enc")) {
dataSource = encryptedFileDataSource;
} else {
dataSource = fileDataSource;
}
}
} else if (SCHEME_ASSET.equals(scheme)) {
dataSource = assetDataSource;
} else if (SCHEME_CONTENT.equals(scheme)) {
dataSource = contentDataSource;
} else {
dataSource = baseDataSource;
}
// Open the source and return.
return dataSource.open(dataSpec);
}
@Override
public int read(byte[] buffer, int offset, int readLength) throws IOException {
return dataSource.read(buffer, offset, readLength);
}
@Override
public Uri getUri() {
return dataSource == null ? null : dataSource.getUri();
}
@Override
public void close() throws IOException {
if (dataSource != null) {
try {
dataSource.close();
} finally {
dataSource = null;
}
}
}
}

View File

@ -0,0 +1,60 @@
/*
* This is the source code of Telegram for Android v. 3.x.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-2017.
*/
package org.telegram.messenger.secretmedia;
import android.content.Context;
import org.telegram.messenger.exoplayer2.upstream.DataSource;
import org.telegram.messenger.exoplayer2.upstream.DefaultDataSource;
import org.telegram.messenger.exoplayer2.upstream.DefaultHttpDataSourceFactory;
import org.telegram.messenger.exoplayer2.upstream.TransferListener;
public final class ExtendedDefaultDataSourceFactory implements DataSource.Factory {
private final Context context;
private final TransferListener<? super DataSource> listener;
private final DataSource.Factory baseDataSourceFactory;
/**
* @param context A context.
* @param userAgent The User-Agent string that should be used.
*/
public ExtendedDefaultDataSourceFactory(Context context, String userAgent) {
this(context, userAgent, null);
}
/**
* @param context A context.
* @param userAgent The User-Agent string that should be used.
* @param listener An optional listener.
*/
public ExtendedDefaultDataSourceFactory(Context context, String userAgent,
TransferListener<? super DataSource> listener) {
this(context, listener, new DefaultHttpDataSourceFactory(userAgent, listener));
}
/**
* @param context A context.
* @param listener An optional listener.
* @param baseDataSourceFactory A {@link DataSource.Factory} to be used to create a base {@link DataSource}
* for {@link DefaultDataSource}.
* @see DefaultDataSource#DefaultDataSource(Context, TransferListener, DataSource)
*/
public ExtendedDefaultDataSourceFactory(Context context, TransferListener<? super DataSource> listener,
DataSource.Factory baseDataSourceFactory) {
this.context = context.getApplicationContext();
this.listener = listener;
this.baseDataSourceFactory = baseDataSourceFactory;
}
@Override
public ExtendedDefaultDataSource createDataSource() {
return new ExtendedDefaultDataSource(context, listener, baseDataSourceFactory.createDataSource());
}
}

File diff suppressed because it is too large Load Diff

View File

@ -55,6 +55,8 @@ public class ActionBar extends FrameLayout {
private int extraHeight;
private AnimatorSet actionModeAnimation;
private int titleRightMargin;
private boolean allowOverlayTitle;
private CharSequence lastTitle;
private CharSequence lastSubtitle;
@ -172,6 +174,10 @@ public class ActionBar extends FrameLayout {
addView(titleTextView, 0, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP));
}
public void setTitleRightMargin(int value) {
titleRightMargin = value;
}
public void setTitle(CharSequence value) {
if (value != null && titleTextView == null) {
createTitleTextView();
@ -490,7 +496,7 @@ public class ActionBar extends FrameLayout {
}
if (titleTextView != null && titleTextView.getVisibility() != GONE || subtitleTextView != null && subtitleTextView.getVisibility() != GONE) {
int availableWidth = width - (menu != null ? menu.getMeasuredWidth() : 0) - AndroidUtilities.dp(16) - textLeft;
int availableWidth = width - (menu != null ? menu.getMeasuredWidth() : 0) - AndroidUtilities.dp(16) - textLeft - titleRightMargin;
if (titleTextView != null && titleTextView.getVisibility() != GONE) {
titleTextView.setTextSize(!AndroidUtilities.isTablet() && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? 18 : 20);

View File

@ -66,6 +66,8 @@ public class BottomSheet extends Dialog {
private boolean allowDrawContent = true;
private boolean useHardwareLayer = true;
private DialogInterface.OnClickListener onClickListener;
private CharSequence[] items;
@ -593,33 +595,33 @@ public class BottomSheet extends Dialog {
containerView.setVisibility(View.INVISIBLE);
container.addView(containerView, 0, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM));
int topOffset = 0;
if (title != null) {
TextView titleView = new TextView(getContext());
titleView.setLines(1);
titleView.setSingleLine(true);
titleView.setText(title);
titleView.setTextColor(Theme.getColor(Theme.key_dialogTextGray2));
titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
titleView.setEllipsize(TextUtils.TruncateAt.MIDDLE);
titleView.setPadding(AndroidUtilities.dp(16), 0, AndroidUtilities.dp(16), AndroidUtilities.dp(8));
titleView.setGravity(Gravity.CENTER_VERTICAL);
containerView.addView(titleView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48));
titleView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
topOffset += 48;
}
if (customView != null) {
if (customView.getParent() != null) {
ViewGroup viewGroup = (ViewGroup) customView.getParent();
viewGroup.removeView(customView);
}
containerView.addView(customView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP));
containerView.addView(customView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 0, topOffset, 0, 0));
} else {
int topOffset = 0;
if (title != null) {
TextView titleView = new TextView(getContext());
titleView.setLines(1);
titleView.setSingleLine(true);
titleView.setText(title);
titleView.setTextColor(Theme.getColor(Theme.key_dialogTextGray2));
titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
titleView.setEllipsize(TextUtils.TruncateAt.MIDDLE);
titleView.setPadding(AndroidUtilities.dp(16), 0, AndroidUtilities.dp(16), AndroidUtilities.dp(8));
titleView.setGravity(Gravity.CENTER_VERTICAL);
containerView.addView(titleView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48));
titleView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
topOffset += 48;
}
if (items != null) {
FrameLayout rowLayout = null;
int lastRowLayoutNum = 0;
@ -659,6 +661,10 @@ public class BottomSheet extends Dialog {
showWithoutAnimation = value;
}
public void setBackgroundColor(int color) {
shadowDrawable.setColorFilter(color, PorterDuff.Mode.MULTIPLY);
}
@Override
public void show() {
super.show();
@ -754,7 +760,7 @@ public class BottomSheet extends Dialog {
containerView.setVisibility(View.VISIBLE);
if (!onCustomOpenAnimation()) {
if (Build.VERSION.SDK_INT >= 20) {
if (Build.VERSION.SDK_INT >= 20 && useHardwareLayer) {
container.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
containerView.setTranslationY(containerView.getMeasuredHeight());
@ -773,7 +779,9 @@ public class BottomSheet extends Dialog {
if (delegate != null) {
delegate.onOpenAnimationEnd();
}
container.setLayerType(View.LAYER_TYPE_NONE, null);
if (useHardwareLayer) {
container.setLayerType(View.LAYER_TYPE_NONE, null);
}
}
}
@ -981,6 +989,11 @@ public class BottomSheet extends Dialog {
return this;
}
public Builder setUseHardwareLayer(boolean value) {
bottomSheet.useHardwareLayer = value;
return this;
}
public Builder setDelegate(BottomSheetDelegate delegate) {
bottomSheet.setDelegate(delegate);
return this;

View File

@ -2415,23 +2415,21 @@ public class Theme {
chat_composeShadowDrawable = context.getResources().getDrawable(R.drawable.compose_panel_shadow);
if (Build.VERSION.SDK_INT >= 16) {
try {
int bitmapSize = AndroidUtilities.roundMessageSize + AndroidUtilities.dp(6);
Bitmap bitmap = Bitmap.createBitmap(bitmapSize, bitmapSize, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setShadowLayer(AndroidUtilities.dp(4), 0, 0, 0x5f000000);
canvas.drawCircle(bitmapSize / 2, bitmapSize / 2, AndroidUtilities.roundMessageSize / 2 - AndroidUtilities.dp(1), paint);
try {
int bitmapSize = AndroidUtilities.roundMessageSize + AndroidUtilities.dp(6);
Bitmap bitmap = Bitmap.createBitmap(bitmapSize, bitmapSize, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setShadowLayer(AndroidUtilities.dp(4), 0, 0, 0x5f000000);
canvas.drawCircle(bitmapSize / 2, bitmapSize / 2, AndroidUtilities.roundMessageSize / 2 - AndroidUtilities.dp(1), paint);
try {
canvas.setBitmap(null);
} catch (Exception ignore) {
}
chat_roundVideoShadow = new BitmapDrawable(bitmap);
} catch (Throwable ignore) {
canvas.setBitmap(null);
} catch (Exception ignore) {
}
chat_roundVideoShadow = new BitmapDrawable(bitmap);
} catch (Throwable ignore) {
}
applyChatTheme(fontsOnly);

View File

@ -77,7 +77,7 @@ public class StickersAdapter extends RecyclerListView.SelectionAdapter implement
File f = FileLoader.getPathToAttach(document.thumb, "webp", true);
if (!f.exists()) {
stickersToLoad.add(FileLoader.getAttachFileName(document.thumb, "webp"));
FileLoader.getInstance().loadFile(document.thumb.location, "webp", 0, true);
FileLoader.getInstance().loadFile(document.thumb.location, "webp", 0, 1);
}
}
return stickersToLoad.isEmpty();

View File

@ -186,6 +186,9 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
private Paint scrimPaint;
private AnimatorSet progressViewAnimation;
private Paint headerPaint = new Paint();
private Paint headerProgressPaint = new Paint();
private ActionBarPopupWindow popupWindow;
private ActionBarPopupWindow.ActionBarPopupWindowLayout popupLayout;
private Rect popupRect;
@ -247,6 +250,8 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
private FrameLayout nightModeHintView;
private FontCell[] fontCells = new FontCell[2];
private int isRtl = -1;
private class SizeChooseView extends View {
private Paint paint;
@ -944,6 +949,7 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
if (currentPage == null || currentPage.cached_page == null) {
return;
}
isRtl = -1;
channelBlock = null;
blocks.clear();
photoBlocks.clear();
@ -1448,13 +1454,13 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
} else if (parentBlock instanceof TLRPC.TL_pageBlockChannel) {
if (channelNamePaint == null) {
channelNamePaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
if (channelBlock == null) {
channelNamePaint.setColor(getTextColor());
} else {
channelNamePaint.setColor(0xffffffff);
}
channelNamePaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
}
if (channelBlock == null) {
channelNamePaint.setColor(getTextColor());
} else {
channelNamePaint.setColor(0xffffffff);
}
channelNamePaint.setTextSize(AndroidUtilities.dp(15));
paint = channelNamePaint;
} else if (parentBlock instanceof TLRPC.TL_pageBlockList && plainText != null) {
@ -2123,17 +2129,58 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
if (listView.getChildCount() == 0) {
return;
}
headerView.invalidate();
checkScroll(dy);
}
});
headerView = new FrameLayout(activity);
headerPaint.setColor(0xff000000);
headerProgressPaint.setColor(0xff242426);
headerView = new FrameLayout(activity) {
@Override
protected void onDraw(Canvas canvas) {
int width = getMeasuredWidth();
int height = getMeasuredHeight();
canvas.drawRect(0, 0, width, height, headerPaint);
if (layoutManager == null) {
return;
}
int first = layoutManager.findFirstVisibleItemPosition();
int last = layoutManager.findLastVisibleItemPosition();
int count = layoutManager.getItemCount();
View view;
if (last >= count - 2) {
view = layoutManager.findViewByPosition(count - 2);
} else {
view = layoutManager.findViewByPosition(first);
}
if (view == null) {
return;
}
float itemProgress = width / (float) (count - 1);
int childCount = layoutManager.getChildCount();
float viewHeight = view.getMeasuredHeight();
float viewProgress;
if (last >= count - 2) {
viewProgress = (count - 2 - first) * itemProgress * (listView.getMeasuredHeight() - view.getTop()) / viewHeight;
} else {
viewProgress = itemProgress * (1.0f - (Math.min(0, view.getTop() - listView.getPaddingTop()) + viewHeight) / viewHeight);
}
float progress = first * itemProgress + viewProgress;
canvas.drawRect(0, 0, progress, height, headerProgressPaint);
}
};
headerView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
headerView.setBackgroundColor(0xff000000);
headerView.setWillNotDraw(false);
containerView.addView(headerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 56));
backButton = new ImageView(activity);
@ -2501,31 +2548,15 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
gestureDetector = new GestureDetector(activity, this);
gestureDetector.setOnDoubleTapListener(this);
ImageReceiver.ImageReceiverDelegate imageReceiverDelegate = new ImageReceiver.ImageReceiverDelegate() {
@Override
public void didSetImage(ImageReceiver imageReceiver, boolean set, boolean thumb) {
if (imageReceiver == centerImage && set && scaleToFill()) {
if (!wasLayout) {
dontResetZoomOnFirstLayout = true;
} else {
setScaleToFill();
}
}
}
};
centerImage.setParentView(photoContainerView);
centerImage.setCrossfadeAlpha((byte) 2);
centerImage.setInvalidateAll(true);
centerImage.setDelegate(imageReceiverDelegate);
leftImage.setParentView(photoContainerView);
leftImage.setCrossfadeAlpha((byte) 2);
leftImage.setInvalidateAll(true);
leftImage.setDelegate(imageReceiverDelegate);
rightImage.setParentView(photoContainerView);
rightImage.setCrossfadeAlpha((byte) 2);
rightImage.setInvalidateAll(true);
rightImage.setDelegate(imageReceiverDelegate);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.messagePlayingProgressDidChanged);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.messagePlayingDidReset);
@ -3813,9 +3844,9 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
imageView.setImageCoords(photoX, (isFirst || currentType == 1 || currentType == 2 || currentBlock.level > 0) ? 0 : AndroidUtilities.dp(8), photoWidth, height);
if (isGif) {
String filter = String.format(Locale.US, "%d_%d", photoWidth, height);
imageView.setImage(currentDocument, filter, thumb != null ? thumb.location : null, thumb != null ? "80_80_b" : null, currentDocument.size, null, true);
imageView.setImage(currentDocument, filter, thumb != null ? thumb.location : null, thumb != null ? "80_80_b" : null, currentDocument.size, null, 1);
} else {
imageView.setImage(null, null, thumb != null ? thumb.location : null, thumb != null ? "80_80_b" : null, 0, null, true);
imageView.setImage(null, null, thumb != null ? thumb.location : null, thumb != null ? "80_80_b" : null, 0, null, 1);
}
int size = AndroidUtilities.dp(48);
@ -3920,9 +3951,9 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
cancelLoading = false;
radialProgress.setProgress(0, false);
if (isGif) {
imageView.setImage(currentDocument, null, currentDocument.thumb != null ? currentDocument.thumb.location : null, "80_80_b", currentDocument.size, null, true);
imageView.setImage(currentDocument, null, currentDocument.thumb != null ? currentDocument.thumb.location : null, "80_80_b", currentDocument.size, null, 1);
} else {
FileLoader.getInstance().loadFile(currentDocument, true, true);
FileLoader.getInstance().loadFile(currentDocument, true, 1);
}
buttonState = 1;
radialProgress.setBackground(getDrawableForCurrentState(), true, animated);
@ -4047,6 +4078,7 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
message.date = (int) (System.currentTimeMillis() / 1000);
message.message = "-1";
message.media = new TLRPC.TL_messageMediaDocument();
message.media.flags |= 3;
message.media.document = currentDocument;
message.flags |= TLRPC.MESSAGE_FLAG_HAS_MEDIA | TLRPC.MESSAGE_FLAG_HAS_FROM_ID;
currentMessageObject = new MessageObject(message, null, false);
@ -4285,7 +4317,7 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
}
} else if (buttonState == 2) {
radialProgress.setProgress(0, false);
FileLoader.getInstance().loadFile(currentDocument, true, true);
FileLoader.getInstance().loadFile(currentDocument, true, 1);
buttonState = 3;
radialProgress.setBackground(getDrawableForCurrentState(), true, false);
invalidate();
@ -4381,7 +4413,7 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
if (avatarVisible = (photo != null)) {
avatarDrawable.setInfo(0, currentBlock.author, null, false);
TLRPC.PhotoSize image = FileLoader.getClosestPhotoSizeWithSize(photo.sizes, AndroidUtilities.dp(40), true);
avatarImageView.setImage(image.location, String.format(Locale.US, "%d_%d", 40, 40), avatarDrawable, 0, null, true);
avatarImageView.setImage(image.location, String.format(Locale.US, "%d_%d", 40, 40), avatarDrawable, 0, null, 1);
}
}
nameLayout = createLayoutForText(currentBlock.author, null, width - AndroidUtilities.dp(36 + 14 + (avatarVisible ? 40 + 14 : 0)), currentBlock);
@ -5250,6 +5282,10 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
private TLRPC.TL_pageBlockList currentBlock;
private boolean hasRtl;
private int textX;
private int maxLetterWidth;
public BlockListCell(Context context) {
super(context);
}
@ -5277,6 +5313,8 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = 0;
hasRtl = false;
maxLetterWidth = 0;
if (currentBlock != null) {
if (lastCreatedWidth != width) {
@ -5284,23 +5322,55 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
textYLayouts.clear();
textNumLayouts.clear();
int count = currentBlock.items.size();
for (int a = 0; a < count; a++) {
TLRPC.RichText item = currentBlock.items.get(a);
if (a == 0) {
StaticLayout textLayout = createLayoutForText(null, item, width - AndroidUtilities.dp(6 + 18) - maxLetterWidth, currentBlock);
int lCount = textLayout.getLineCount();
for (int b = 0; b < lCount; b++) {
if (textLayout.getLineLeft(b) > 0) {
hasRtl = true;
isRtl = 1;
break;
}
}
}
String num;
if (currentBlock.ordered) {
if (hasRtl) {
num = String.format(".%d", a + 1);
} else {
num = String.format("%d.", a + 1);
}
} else {
num = "";
}
StaticLayout textLayout = createLayoutForText(num, item, width - AndroidUtilities.dp(36 + 18), currentBlock);
textNumLayouts.add(textLayout);
if (currentBlock.ordered) {
if (textLayout != null) {
maxLetterWidth = Math.max(maxLetterWidth, (int) Math.ceil(textLayout.getLineWidth(0)));
}
} else if (a == 0) {
maxLetterWidth = AndroidUtilities.dp(12);
}
}
for (int a = 0; a < count; a++) {
TLRPC.RichText item = currentBlock.items.get(a);
height += AndroidUtilities.dp(8);
StaticLayout textLayout = createLayoutForText(null, item, width - AndroidUtilities.dp(36 + 18), currentBlock);
StaticLayout textLayout = createLayoutForText(null, item, width - AndroidUtilities.dp(6 + 18 + 18) - maxLetterWidth, currentBlock);
textYLayouts.add(height);
textLayouts.add(textLayout);
if (textLayout != null) {
height += textLayout.getHeight();
}
String num;
if (currentBlock.ordered) {
num = String.format(Locale.US, "%d.", a + 1);
} else {
num = "";
}
textLayout = createLayoutForText(num, item, width - AndroidUtilities.dp(36 + 18), currentBlock);
textNumLayouts.add(textLayout);
}
if (hasRtl) {
textX = AndroidUtilities.dp(18);
} else {
textX = AndroidUtilities.dp(18 + 6) + maxLetterWidth;
}
height += AndroidUtilities.dp(8);
//lastCreatedWidth = width;
@ -5318,15 +5388,22 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
return;
}
int count = textLayouts.size();
int width = getMeasuredWidth();
for (int a = 0; a < count; a++) {
StaticLayout textLayout = textLayouts.get(a);
StaticLayout textLayout2 = textNumLayouts.get(a);
canvas.save();
canvas.translate(AndroidUtilities.dp(18), textYLayouts.get(a));
if (hasRtl) {
canvas.translate(width - AndroidUtilities.dp(18) - (int) Math.ceil(textLayout2.getLineWidth(0)), textYLayouts.get(a));
} else {
canvas.translate(AndroidUtilities.dp(18), textYLayouts.get(a));
}
if (textLayout2 != null) {
textLayout2.draw(canvas);
}
canvas.translate(AndroidUtilities.dp(18), 0);
canvas.restore();
canvas.save();
canvas.translate(textX, textYLayouts.get(a));
drawLayoutLink(canvas, textLayout);
if (textLayout != null) {
textLayout.draw(canvas);
@ -5568,8 +5645,9 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
private StaticLayout textLayout2;
private int textY2;
private int lastCreatedWidth;
private int textX = AndroidUtilities.dp(18 + 14);
private int textX;
private int textY = AndroidUtilities.dp(8);
private boolean hasRtl;
private TLRPC.TL_pageBlockBlockquote currentBlock;
@ -5596,8 +5674,22 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
if (currentBlock != null) {
if (lastCreatedWidth != width) {
textLayout = createLayoutForText(null, currentBlock.text, width - AndroidUtilities.dp(36 + 14), currentBlock);
hasRtl = false;
if (textLayout != null) {
height += AndroidUtilities.dp(8) + textLayout.getHeight();
int count = textLayout.getLineCount();
for (int a = 0; a < count; a++) {
if (textLayout.getLineLeft(a) > 0) {
isRtl = 1;
hasRtl = true;
break;
}
}
}
if (hasRtl) {
textX = AndroidUtilities.dp(14);
} else {
textX = AndroidUtilities.dp(18 + 14);
}
textLayout2 = createLayoutForText(null, currentBlock.caption, width - AndroidUtilities.dp(36 + 14), currentBlock);
if (textLayout2 != null) {
@ -5635,7 +5727,12 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
textLayout2.draw(canvas);
canvas.restore();
}
canvas.drawRect(AndroidUtilities.dp(18), AndroidUtilities.dp(6), AndroidUtilities.dp(20), getMeasuredHeight() - AndroidUtilities.dp(6), quoteLinePaint);
if (hasRtl) {
int x = getMeasuredWidth() - AndroidUtilities.dp(20);
canvas.drawRect(x, AndroidUtilities.dp(6), x + AndroidUtilities.dp(2), getMeasuredHeight() - AndroidUtilities.dp(6), quoteLinePaint);
} else {
canvas.drawRect(AndroidUtilities.dp(18), AndroidUtilities.dp(6), AndroidUtilities.dp(20), getMeasuredHeight() - AndroidUtilities.dp(6), quoteLinePaint);
}
}
}
@ -5763,7 +5860,7 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
} else {
filter = String.format(Locale.US, "%d_%d", photoWidth, height);
}
imageView.setImage(image.location, filter, thumb != null ? thumb.location : null, thumb != null ? "80_80_b" : null, image.size, null, true);
imageView.setImage(image.location, filter, thumb != null ? thumb.location : null, thumb != null ? "80_80_b" : null, image.size, null, 1);
}
if (currentType == 0 && lastCreatedWidth != width) {
@ -5984,7 +6081,7 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
private StaticLayout textLayout;
private int lastCreatedWidth;
private int textX = AndroidUtilities.dp(18);
private int textX;
private int textY = AndroidUtilities.dp(8);
private TLRPC.TL_pageBlockAuthorDate currentBlock;
@ -6046,6 +6143,11 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
textLayout = createLayoutForText(text, null, width - AndroidUtilities.dp(36), currentBlock);
if (textLayout != null) {
height += AndroidUtilities.dp(8 + 8) + textLayout.getHeight();
if (isRtl == 1) {
textX = (int) Math.floor(width - textLayout.getLineWidth(0) - AndroidUtilities.dp(16));
} else {
textX = AndroidUtilities.dp(18);
}
}
//lastCreatedWidth = width;
}
@ -6105,6 +6207,18 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
textLayout = createLayoutForText(null, currentBlock.text, width - AndroidUtilities.dp(36), currentBlock);
if (textLayout != null) {
height += AndroidUtilities.dp(8 + 8) + textLayout.getHeight();
if (isRtl == -1) {
int count = textLayout.getLineCount();
for (int a = 0; a < count; a++) {
if (textLayout.getLineLeft(a) > 0) {
isRtl = 1;
break;
}
}
if (isRtl == -1) {
isRtl = 0;
}
}
}
if (currentBlock.first) {
height += AndroidUtilities.dp(8);
@ -7237,14 +7351,14 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
size[0] = -1;
}
TLRPC.PhotoSize thumbLocation = FileLoader.getClosestPhotoSizeWithSize(photo.sizes, 80);
imageReceiver.setImage(fileLocation, null, null, placeHolder != null ? new BitmapDrawable(null, placeHolder) : null, thumbLocation != null ? thumbLocation.location : null, "b", size[0], null, true);
imageReceiver.setImage(fileLocation, null, null, placeHolder != null ? new BitmapDrawable(null, placeHolder) : null, thumbLocation != null ? thumbLocation.location : null, "b", size[0], null, 1);
} else if (isMediaVideo(index)) {
if (!(fileLocation instanceof TLRPC.TL_fileLocationUnavailable)) {
Bitmap placeHolder = null;
if (currentThumb != null && imageReceiver == centerImage) {
placeHolder = currentThumb;
}
imageReceiver.setImage(null, null, null, placeHolder != null ? new BitmapDrawable(null, placeHolder) : null, fileLocation, "b", 0, null, true);
imageReceiver.setImage(null, null, null, placeHolder != null ? new BitmapDrawable(null, placeHolder) : null, fileLocation, "b", 0, null, 1);
} else {
imageReceiver.setImageBitmap(parentActivity.getResources().getDrawable(R.drawable.photoview_placeholder));
}
@ -8221,7 +8335,7 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
if (file == null) {
if (download) {
if (!FileLoader.getInstance().isLoadingFile(currentFileNames[0])) {
FileLoader.getInstance().loadFile(document, true, true);
FileLoader.getInstance().loadFile(document, true, 1);
} else {
FileLoader.getInstance().cancelLoadFile(document);
}
@ -8370,8 +8484,4 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
object.clipTopAddition = currentHeaderHeight;
return object;
}
private boolean scaleToFill() {
return false;
}
}

View File

@ -225,6 +225,7 @@ public class AudioSelectActivity extends BaseFragment implements NotificationCen
message.message = "-1";
message.attachPath = audioEntry.path;
message.media = new TLRPC.TL_messageMediaDocument();
message.media.flags |= 3;
message.media.document = new TLRPC.TL_document();
message.flags |= TLRPC.MESSAGE_FLAG_HAS_MEDIA | TLRPC.MESSAGE_FLAG_HAS_FROM_ID;

View File

@ -79,7 +79,7 @@ public class AboutLinkCell extends FrameLayout {
invalidate();
}
public void setTextAndIcon(String text, int resId) {
public void setTextAndIcon(String text, int resId, boolean parseLinks) {
if (text == null || text.length() == 0) {
setVisibility(GONE);
return;
@ -89,7 +89,9 @@ public class AboutLinkCell extends FrameLayout {
}
oldText = text;
stringBuilder = new SpannableStringBuilder(oldText);
MessageObject.addLinks(false, stringBuilder, false);
if (parseLinks) {
MessageObject.addLinks(false, stringBuilder, false);
}
Emoji.replaceEmoji(stringBuilder, Theme.profile_aboutTextPaint.getFontMetricsInt(), AndroidUtilities.dp(20), false);
requestLayout();
if (resId == 0) {

View File

@ -50,7 +50,7 @@ public class ArchivedStickerSetCell extends FrameLayout {
textView.setSingleLine(true);
textView.setEllipsize(TextUtils.TruncateAt.END);
textView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, LocaleController.isRTL ? 40 : 71, 10, LocaleController.isRTL ? 71 : 40, 0));
addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, 71, 10, 71, 0));
valueTextView = new TextView(context);
valueTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText2));
@ -59,7 +59,7 @@ public class ArchivedStickerSetCell extends FrameLayout {
valueTextView.setMaxLines(1);
valueTextView.setSingleLine(true);
valueTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
addView(valueTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, LocaleController.isRTL ? 40 : 71, 35, LocaleController.isRTL ? 71 : 40, 0));
addView(valueTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, 71, 35, 71, 0));
imageView = new BackupImageView(context);
imageView.setAspectFit(true);

View File

@ -25,6 +25,7 @@ import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessageObject;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.R;
import org.telegram.tgnet.TLRPC;
import org.telegram.messenger.UserConfig;
import org.telegram.ui.ActionBar.Theme;
@ -119,11 +120,11 @@ public class ChatActionCell extends BaseCell {
}
avatarDrawable.setInfo(id, null, null, false);
if (currentMessageObject.messageOwner.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) {
imageReceiver.setImage(currentMessageObject.messageOwner.action.newUserPhoto.photo_small, "50_50", avatarDrawable, null, false);
imageReceiver.setImage(currentMessageObject.messageOwner.action.newUserPhoto.photo_small, "50_50", avatarDrawable, null, 0);
} else {
TLRPC.PhotoSize photo = FileLoader.getClosestPhotoSizeWithSize(currentMessageObject.photoThumbs, AndroidUtilities.dp(64));
if (photo != null) {
imageReceiver.setImage(photo.location, "50_50", avatarDrawable, null, false);
imageReceiver.setImage(photo.location, "50_50", avatarDrawable, null, 0);
} else {
imageReceiver.setImageBitmap(avatarDrawable);
}
@ -297,7 +298,17 @@ public class ChatActionCell extends BaseCell {
if (width != previousWidth) {
CharSequence text;
if (currentMessageObject != null) {
text = currentMessageObject.messageText;
if (currentMessageObject.messageOwner != null && currentMessageObject.messageOwner.media != null && currentMessageObject.messageOwner.media.ttl_seconds != 0) {
if (currentMessageObject.messageOwner.media.photo instanceof TLRPC.TL_photoEmpty) {
text = LocaleController.getString("AttachPhotoExpired", R.string.AttachPhotoExpired);
} else if (currentMessageObject.messageOwner.media.document instanceof TLRPC.TL_documentEmpty) {
text = LocaleController.getString("AttachVideoExpired", R.string.AttachVideoExpired);
} else {
text = currentMessageObject.messageText;
}
} else {
text = currentMessageObject.messageText;
}
} else {
text = customText;
}

View File

@ -70,6 +70,7 @@ import org.telegram.ui.Components.URLSpanBotCommand;
import org.telegram.ui.Components.URLSpanMono;
import org.telegram.ui.Components.URLSpanNoUnderline;
import org.telegram.ui.PhotoViewer;
import org.telegram.ui.SecretMediaViewer;
import java.io.File;
import java.util.ArrayList;
@ -208,6 +209,11 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
private String currentPhotoFilterThumb;
private boolean cancelLoading;
private float controlsAlpha = 1.0f;
private long lastControlsAlphaChangeTime;
private long totalChangeTime;
private boolean mediaWasInvisible;
private CharacterStyle pressedLink;
private int pressedLinkType;
private boolean linkPreviewPressed;
@ -757,7 +763,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
}
} else {
TLRPC.WebPage webPage = currentMessageObject.messageOwner.media.webpage;
if (webPage != null && Build.VERSION.SDK_INT >= 16 && !TextUtils.isEmpty(webPage.embed_url)) {
if (webPage != null && !TextUtils.isEmpty(webPage.embed_url)) {
delegate.needOpenWebView(webPage.embed_url, webPage.site_name, webPage.title, webPage.url, webPage.embed_width, webPage.embed_height);
} else if (buttonState == -1) {
delegate.didPressedImage(this);
@ -815,6 +821,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
playSoundEffect(SoundEffectConstants.CLICK);
delegate.didPressedOther(this);
invalidate();
result = true;
}
}
}
@ -856,9 +863,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
}
}
if (imagePressed) {
if (currentMessageObject.isSecretPhoto() && currentMessageObject.type != 5) {
imagePressed = false;
} else if (currentMessageObject.isSendError()) {
if (currentMessageObject.isSendError()) {
imagePressed = false;
result = false;
} else if (currentMessageObject.type == 8 && buttonState == -1 && MediaController.getInstance().canAutoplayGifs() && photoImage.getAnimation() == null) {
@ -1248,7 +1253,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
return;
}
if (buttonState == 2) {
FileLoader.getInstance().loadFile(documentAttach, true, false);
FileLoader.getInstance().loadFile(documentAttach, true, 0);
buttonState = 4;
radialProgress.setBackground(getDrawableForCurrentState(), false, false);
}
@ -1362,7 +1367,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
didPressedButton(false);
}
} else if (documentAttachType == DOCUMENT_ATTACH_TYPE_VIDEO) {
if (buttonState == 0 || buttonState == 3) {
if (buttonState == -1) {
delegate.didPressedImage(this);
} else if (buttonState == 0 || buttonState == 3) {
didPressedButton(false);
}
} else if (currentMessageObject.type == 4) {
@ -1375,7 +1382,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
if (buttonState == -1) {
TLRPC.WebPage webPage = currentMessageObject.messageOwner.media.webpage;
if (webPage != null) {
if (Build.VERSION.SDK_INT >= 16 && webPage.embed_url != null && webPage.embed_url.length() != 0) {
if (webPage.embed_url != null && webPage.embed_url.length() != 0) {
delegate.needOpenWebView(webPage.embed_url, webPage.site_name, webPage.description, webPage.url, webPage.embed_width, webPage.embed_height);
} else {
Browser.openUrl(getContext(), webPage.url);
@ -1390,7 +1397,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
}
private void updateSecretTimeText(MessageObject messageObject) {
if (messageObject == null || messageObject.isOut()) {
if (messageObject == null) {
return;
}
String str = messageObject.getSecretTimeString();
@ -1703,20 +1710,21 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
return durationWidth;
} else if (MessageObject.isVideoDocument(documentAttach)) {
documentAttachType = DOCUMENT_ATTACH_TYPE_VIDEO;
int duration = 0;
for (int a = 0; a < documentAttach.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = documentAttach.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeVideo) {
duration = attribute.duration;
break;
if (!messageObject.isSecretPhoto()) {
int duration = 0;
for (int a = 0; a < documentAttach.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = documentAttach.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeVideo) {
duration = attribute.duration;
break;
}
}
int minutes = duration / 60;
int seconds = duration - minutes * 60;
String str = String.format("%d:%02d, %s", minutes, seconds, AndroidUtilities.formatFileSize(documentAttach.size));
infoWidth = (int) Math.ceil(Theme.chat_infoPaint.measureText(str));
infoLayout = new StaticLayout(str, Theme.chat_infoPaint, infoWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
}
int minutes = duration / 60;
int seconds = duration - minutes * 60;
String str = String.format("%d:%02d, %s", minutes, seconds, AndroidUtilities.formatFileSize(documentAttach.size));
infoWidth = (int) Math.ceil(Theme.chat_infoPaint.measureText(str));
infoLayout = new StaticLayout(str, Theme.chat_infoPaint, infoWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
return 0;
} else {
drawPhotoImage = documentAttach.mime_type != null && documentAttach.mime_type.toLowerCase().startsWith("image/") || documentAttach.thumb instanceof TLRPC.TL_photoSize && !(documentAttach.thumb.location instanceof TLRPC.TL_fileLocationUnavailable);
@ -1762,7 +1770,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
photoImage.setParentMessageObject(messageObject);
if (currentPhotoObject != null) {
currentPhotoFilter = "86_86_b";
photoImage.setImage(null, null, null, null, currentPhotoObject.location, currentPhotoFilter, 0, null, true);
photoImage.setImage(null, null, null, null, currentPhotoObject.location, currentPhotoFilter, 0, null, 1);
} else {
photoImage.setImageBitmap((BitmapDrawable) null);
}
@ -1961,7 +1969,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
hasGamePreview = messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGame && messageObject.messageOwner.media.game instanceof TLRPC.TL_game;
hasInvoicePreview = messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaInvoice;
hasLinkPreview = messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage && messageObject.messageOwner.media.webpage instanceof TLRPC.TL_webPage;
drawInstantView = Build.VERSION.SDK_INT >= 16 && hasLinkPreview && messageObject.messageOwner.media.webpage.cached_page != null;
drawInstantView = hasLinkPreview && messageObject.messageOwner.media.webpage.cached_page != null;
String webpageType = hasLinkPreview ? messageObject.messageOwner.media.webpage.type : null;
if (!drawInstantView) {
if ("telegram_channel".equals(webpageType)) {
@ -2476,12 +2484,12 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
currentPhotoFilterThumb = String.format(Locale.US, "%d_%d_b", width, height);
if (webDocument != null) {
photoImage.setImage(webDocument, null, currentPhotoFilter, null, null, "b1", webDocument.size, null, true);
photoImage.setImage(webDocument, null, currentPhotoFilter, null, null, "b1", webDocument.size, null, 1);
} else {
if (documentAttachType == DOCUMENT_ATTACH_TYPE_STICKER) {
photoImage.setImage(documentAttach, null, currentPhotoFilter, null, currentPhotoObject != null ? currentPhotoObject.location : null, "b1", documentAttach.size, "webp", true);
photoImage.setImage(documentAttach, null, currentPhotoFilter, null, currentPhotoObject != null ? currentPhotoObject.location : null, "b1", documentAttach.size, "webp", 1);
} else if (documentAttachType == DOCUMENT_ATTACH_TYPE_VIDEO) {
photoImage.setImage(null, null, currentPhotoObject.location, currentPhotoFilter, 0, null, false);
photoImage.setImage(null, null, currentPhotoObject.location, currentPhotoFilter, 0, null, 0);
} else if (documentAttachType == DOCUMENT_ATTACH_TYPE_GIF || documentAttachType == DOCUMENT_ATTACH_TYPE_ROUND) {
String fileName = FileLoader.getAttachFileName(document);
boolean autoDownload = false;
@ -2493,21 +2501,21 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
}
if (!messageObject.isSending() && (messageObject.mediaExists || FileLoader.getInstance().isLoadingFile(fileName) || autoDownload)) {
photoNotSet = false;
photoImage.setImage(document, null, currentPhotoObject != null ? currentPhotoObject.location : null, currentPhotoFilterThumb, document.size, null, false);
photoImage.setImage(document, null, currentPhotoObject != null ? currentPhotoObject.location : null, currentPhotoFilterThumb, document.size, null, 0);
} else {
photoNotSet = true;
photoImage.setImage(null, null, currentPhotoObject != null ? currentPhotoObject.location : null, currentPhotoFilterThumb, 0, null, false);
photoImage.setImage(null, null, currentPhotoObject != null ? currentPhotoObject.location : null, currentPhotoFilterThumb, 0, null, 0);
}
} else {
boolean photoExist = messageObject.mediaExists;
String fileName = FileLoader.getAttachFileName(currentPhotoObject);
if (hasGamePreview || photoExist || MediaController.getInstance().canDownloadMedia(MediaController.AUTODOWNLOAD_MASK_PHOTO) || FileLoader.getInstance().isLoadingFile(fileName)) {
photoNotSet = false;
photoImage.setImage(currentPhotoObject.location, currentPhotoFilter, currentPhotoObjectThumb != null ? currentPhotoObjectThumb.location : null, currentPhotoFilterThumb, 0, null, false);
photoImage.setImage(currentPhotoObject.location, currentPhotoFilter, currentPhotoObjectThumb != null ? currentPhotoObjectThumb.location : null, currentPhotoFilterThumb, 0, null, 0);
} else {
photoNotSet = true;
if (currentPhotoObjectThumb != null) {
photoImage.setImage(null, null, currentPhotoObjectThumb.location, String.format(Locale.US, "%d_%d_b", width, height), 0, null, false);
photoImage.setImage(null, null, currentPhotoObjectThumb.location, String.format(Locale.US, "%d_%d_b", width, height), 0, null, 0);
} else {
photoImage.setImageBitmap((Drawable) null);
}
@ -2662,7 +2670,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
}
contactAvatarDrawable.setInfo(user);
}
photoImage.setImage(currentPhoto, "50_50", user != null ? contactAvatarDrawable : Theme.chat_contactDrawable[messageObject.isOutOwner() ? 1 : 0], null, false);
photoImage.setImage(currentPhoto, "50_50", user != null ? contactAvatarDrawable : Theme.chat_contactDrawable[messageObject.isOutOwner() ? 1 : 0], null, 0);
String phone = messageObject.messageOwner.media.phone_number;
if (phone != null && phone.length() != 0) {
@ -2853,14 +2861,14 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
null,
currentPhotoObjectThumb != null ? currentPhotoObjectThumb.location : null,
"b1",
messageObject.messageOwner.media.document.size, "webp", true);
messageObject.messageOwner.media.document.size, "webp", 1);
} else if (messageObject.messageOwner.media.document.id != 0) {
photoImage.setImage(messageObject.messageOwner.media.document, null,
String.format(Locale.US, "%d_%d", photoWidth, photoHeight),
null,
currentPhotoObjectThumb != null ? currentPhotoObjectThumb.location : null,
"b1",
messageObject.messageOwner.media.document.size, "webp", true);
messageObject.messageOwner.media.document.size, "webp", 1);
}
} else {
int maxPhotoWidth;
@ -2891,20 +2899,26 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
currentPhotoObjectThumb = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, 80);
} else if (messageObject.type == 3) { //video
createDocumentLayout(0, messageObject);
photoImage.setNeedsQualityThumb(true);
photoImage.setShouldGenerateQualityThumb(true);
updateSecretTimeText(messageObject);
if (!messageObject.isSecretPhoto()) {
photoImage.setNeedsQualityThumb(true);
photoImage.setShouldGenerateQualityThumb(true);
}
photoImage.setParentMessageObject(messageObject);
} else if (messageObject.type == 5) { //round video
photoImage.setNeedsQualityThumb(true);
photoImage.setShouldGenerateQualityThumb(true);
if (!messageObject.isSecretPhoto()) {
photoImage.setNeedsQualityThumb(true);
photoImage.setShouldGenerateQualityThumb(true);
}
photoImage.setParentMessageObject(messageObject);
} else if (messageObject.type == 8) { //gif
String str = AndroidUtilities.formatFileSize(messageObject.messageOwner.media.document.size);
infoWidth = (int) Math.ceil(Theme.chat_infoPaint.measureText(str));
infoLayout = new StaticLayout(str, Theme.chat_infoPaint, infoWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
photoImage.setNeedsQualityThumb(true);
photoImage.setShouldGenerateQualityThumb(true);
if (!messageObject.isSecretPhoto()) {
photoImage.setNeedsQualityThumb(true);
photoImage.setShouldGenerateQualityThumb(true);
}
photoImage.setParentMessageObject(messageObject);
}
@ -3058,11 +3072,11 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
photoExist = false;
}
if (photoExist || MediaController.getInstance().canDownloadMedia(MediaController.AUTODOWNLOAD_MASK_PHOTO) || FileLoader.getInstance().isLoadingFile(fileName)) {
photoImage.setImage(currentPhotoObject.location, currentPhotoFilter, currentPhotoObjectThumb != null ? currentPhotoObjectThumb.location : null, currentPhotoFilterThumb, noSize ? 0 : currentPhotoObject.size, null, false);
photoImage.setImage(currentPhotoObject.location, currentPhotoFilter, currentPhotoObjectThumb != null ? currentPhotoObjectThumb.location : null, currentPhotoFilterThumb, noSize ? 0 : currentPhotoObject.size, null, currentMessageObject.shouldEncryptPhotoOrVideo() ? 2 : 0);
} else {
photoNotSet = true;
if (currentPhotoObjectThumb != null) {
photoImage.setImage(null, null, currentPhotoObjectThumb.location, currentPhotoFilterThumb, 0, null, false);
photoImage.setImage(null, null, currentPhotoObjectThumb.location, currentPhotoFilterThumb, 0, null, currentMessageObject.shouldEncryptPhotoOrVideo() ? 2 : 0);
} else {
photoImage.setImageBitmap((Drawable) null);
}
@ -3088,16 +3102,16 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
}
if (!messageObject.isSending() && (localFile != 0 || FileLoader.getInstance().isLoadingFile(fileName) || autoDownload)) {
if (localFile == 1) {
photoImage.setImage(null, messageObject.isSendError() ? null : messageObject.messageOwner.attachPath, null, null, currentPhotoObject != null ? currentPhotoObject.location : null, currentPhotoFilterThumb, 0, null, false);
photoImage.setImage(null, messageObject.isSendError() ? null : messageObject.messageOwner.attachPath, null, null, currentPhotoObject != null ? currentPhotoObject.location : null, currentPhotoFilterThumb, 0, null, 0);
} else {
photoImage.setImage(messageObject.messageOwner.media.document, null, currentPhotoObject != null ? currentPhotoObject.location : null, currentPhotoFilterThumb, messageObject.messageOwner.media.document.size, null, false);
photoImage.setImage(messageObject.messageOwner.media.document, null, currentPhotoObject != null ? currentPhotoObject.location : null, currentPhotoFilterThumb, messageObject.messageOwner.media.document.size, null, 0);
}
} else {
photoNotSet = true;
photoImage.setImage(null, null, currentPhotoObject != null ? currentPhotoObject.location : null, currentPhotoFilterThumb, 0, null, false);
photoImage.setImage(null, null, currentPhotoObject != null ? currentPhotoObject.location : null, currentPhotoFilterThumb, 0, null, 0);
}
} else {
photoImage.setImage(null, null, currentPhotoObject != null ? currentPhotoObject.location : null, currentPhotoFilterThumb, 0, null, false);
photoImage.setImage(null, null, currentPhotoObject != null ? currentPhotoObject.location : null, currentPhotoFilterThumb, 0, null, currentMessageObject.shouldEncryptPhotoOrVideo() ? 2 : 0);
}
}
setMessageObjectInternal(messageObject);
@ -3110,6 +3124,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
namesOffset += AndroidUtilities.dp(7);
}
totalHeight = photoHeight + AndroidUtilities.dp(14) + namesOffset + additionHeight;
if (pinnedTop) {
namesOffset -= AndroidUtilities.dp(1);
}
@ -3280,6 +3295,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} else if (pinnedBottom) {
totalHeight -= AndroidUtilities.dp(1);
}
if (messageObject.type == 13 && totalHeight < AndroidUtilities.dp(70)) {
totalHeight = AndroidUtilities.dp(70);
}
}
updateWaveform();
updateButtonState(dataChanged);
@ -3485,7 +3503,15 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
forceNotDrawTime = false;
photoImage.setPressed(isDrawSelectedBackground());
photoImage.setVisible(!PhotoViewer.getInstance().isShowingImage(currentMessageObject), false);
photoImage.setVisible(!PhotoViewer.getInstance().isShowingImage(currentMessageObject) && !SecretMediaViewer.getInstance().isShowingImage(currentMessageObject), false);
if (!photoImage.getVisible()) {
mediaWasInvisible = true;
} else if (mediaWasInvisible) {
lastControlsAlphaChangeTime = System.currentTimeMillis();
totalChangeTime = 0;
controlsAlpha = 0.0f;
mediaWasInvisible = false;
}
radialProgress.setHideCurrentDrawable(false);
radialProgress.setProgressColor(Theme.getColor(Theme.key_chat_mediaProgress));
@ -3756,7 +3782,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
}
}
if (buttonState == -1 && currentMessageObject.isSecretPhoto() && !MediaController.getInstance().isPlayingMessage(currentMessageObject)) {
if (buttonState == -1 && currentMessageObject.isSecretPhoto() && !MediaController.getInstance().isPlayingMessage(currentMessageObject) && photoImage.getVisible()) {
int drawable = 4;
if (currentMessageObject.messageOwner.destroyTime != 0) {
if (currentMessageObject.isOutOwner()) {
@ -3766,24 +3792,30 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
}
}
setDrawableBounds(Theme.chat_photoStatesDrawables[drawable][buttonPressed], buttonX, buttonY);
Theme.chat_photoStatesDrawables[drawable][buttonPressed].setAlpha((int) (255 * (1.0f - radialProgress.getAlpha())));
Theme.chat_photoStatesDrawables[drawable][buttonPressed].setAlpha((int) (255 * (1.0f - radialProgress.getAlpha()) * controlsAlpha));
Theme.chat_photoStatesDrawables[drawable][buttonPressed].draw(canvas);
if (!currentMessageObject.isOutOwner() && currentMessageObject.messageOwner.destroyTime != 0) {
long msTime = System.currentTimeMillis() + ConnectionsManager.getInstance().getTimeDifference() * 1000;
float progress = Math.max(0, (long) currentMessageObject.messageOwner.destroyTime * 1000 - msTime) / (currentMessageObject.messageOwner.ttl * 1000.0f);
canvas.drawArc(deleteProgressRect, -90, -360 * progress, true, Theme.chat_deleteProgressPaint);
if (progress != 0) {
int offset = AndroidUtilities.dp(2);
invalidate((int) deleteProgressRect.left - offset, (int) deleteProgressRect.top - offset, (int) deleteProgressRect.right + offset * 2, (int) deleteProgressRect.bottom + offset * 2);
if (currentMessageObject.messageOwner.destroyTime != 0) {
if (!currentMessageObject.isOutOwner()) {
long msTime = System.currentTimeMillis() + ConnectionsManager.getInstance().getTimeDifference() * 1000;
float progress = Math.max(0, (long) currentMessageObject.messageOwner.destroyTime * 1000 - msTime) / (currentMessageObject.messageOwner.ttl * 1000.0f);
Theme.chat_deleteProgressPaint.setAlpha((int) (255 * controlsAlpha));
canvas.drawArc(deleteProgressRect, -90, -360 * progress, true, Theme.chat_deleteProgressPaint);
if (progress != 0) {
int offset = AndroidUtilities.dp(2);
invalidate((int) deleteProgressRect.left - offset, (int) deleteProgressRect.top - offset, (int) deleteProgressRect.right + offset * 2, (int) deleteProgressRect.bottom + offset * 2);
}
}
updateSecretTimeText(currentMessageObject);
}
}
if (documentAttachType == DOCUMENT_ATTACH_TYPE_GIF || currentMessageObject.type == 8) {
if (photoImage.getVisible() && !hasGamePreview) {
if (photoImage.getVisible() && !hasGamePreview && !currentMessageObject.isSecretPhoto()) {
int oldAlpha = ((BitmapDrawable) Theme.chat_msgMediaMenuDrawable).getPaint().getAlpha();
Theme.chat_msgMediaMenuDrawable.setAlpha((int) (oldAlpha * controlsAlpha));
setDrawableBounds(Theme.chat_msgMediaMenuDrawable, otherX = photoImage.getImageX() + photoImage.getImageWidth() - AndroidUtilities.dp(14), otherY = photoImage.getImageY() + AndroidUtilities.dp(8.1f));
Theme.chat_msgMediaMenuDrawable.draw(canvas);
Theme.chat_msgMediaMenuDrawable.setAlpha(oldAlpha);
}
} else if (documentAttachType == DOCUMENT_ATTACH_TYPE_ROUND || currentMessageObject.type == 5) {
if (durationLayout != null) {
@ -3900,9 +3932,14 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
if (currentMessageObject.type == 1 || documentAttachType == DOCUMENT_ATTACH_TYPE_VIDEO) {
if (photoImage.getVisible()) {
if (documentAttachType == DOCUMENT_ATTACH_TYPE_VIDEO) {
setDrawableBounds(Theme.chat_msgMediaMenuDrawable, otherX = photoImage.getImageX() + photoImage.getImageWidth() - AndroidUtilities.dp(14), otherY = photoImage.getImageY() + AndroidUtilities.dp(8.1f));
Theme.chat_msgMediaMenuDrawable.draw(canvas);
if (!currentMessageObject.isSecretPhoto()) {
if (documentAttachType == DOCUMENT_ATTACH_TYPE_VIDEO) {
int oldAlpha = ((BitmapDrawable) Theme.chat_msgMediaMenuDrawable).getPaint().getAlpha();
Theme.chat_msgMediaMenuDrawable.setAlpha((int) (oldAlpha * controlsAlpha));
setDrawableBounds(Theme.chat_msgMediaMenuDrawable, otherX = photoImage.getImageX() + photoImage.getImageWidth() - AndroidUtilities.dp(14), otherY = photoImage.getImageY() + AndroidUtilities.dp(8.1f));
Theme.chat_msgMediaMenuDrawable.draw(canvas);
Theme.chat_msgMediaMenuDrawable.setAlpha(oldAlpha);
}
}
if (infoLayout != null && (buttonState == 1 || buttonState == 0 || buttonState == 3 || currentMessageObject.isSecretPhoto())) {
@ -3910,12 +3947,17 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
int x1 = photoImage.getImageX() + AndroidUtilities.dp(4);
int y1 = photoImage.getImageY() + AndroidUtilities.dp(4);
rect.set(x1, y1, x1 + infoWidth + AndroidUtilities.dp(8), y1 + AndroidUtilities.dp(16.5f));
int oldAlpha = Theme.chat_timeBackgroundPaint.getAlpha();
Theme.chat_timeBackgroundPaint.setAlpha((int) (oldAlpha * controlsAlpha));
canvas.drawRoundRect(rect, AndroidUtilities.dp(4), AndroidUtilities.dp(4), Theme.chat_timeBackgroundPaint);
Theme.chat_timeBackgroundPaint.setAlpha(oldAlpha);
canvas.save();
canvas.translate(photoImage.getImageX() + AndroidUtilities.dp(8), photoImage.getImageY() + AndroidUtilities.dp(5.5f));
Theme.chat_infoPaint.setAlpha((int) (255 * controlsAlpha));
infoLayout.draw(canvas);
canvas.restore();
Theme.chat_infoPaint.setAlpha(255);
}
}
} else {
@ -4471,12 +4513,16 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
invalidate();
} else {
MediaController.getInstance().removeLoadingFileObserver(this);
if (currentMessageObject.type == 8 && !photoImage.isAllowStartAnimation()) {
buttonState = 2;
} else if (documentAttachType == DOCUMENT_ATTACH_TYPE_VIDEO) {
buttonState = 3;
} else {
if (currentMessageObject.isSecretPhoto()) {
buttonState = -1;
} else {
if (currentMessageObject.type == 8 && !photoImage.isAllowStartAnimation()) {
buttonState = 2;
} else if (documentAttachType == DOCUMENT_ATTACH_TYPE_VIDEO) {
buttonState = 3;
} else {
buttonState = -1;
}
}
radialProgress.setBackground(getDrawableForCurrentState(), false, animated);
if (photoNotSet) {
@ -4500,31 +4546,31 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
cancelLoading = false;
radialProgress.setProgress(0, false);
if (currentMessageObject.type == 1) {
photoImage.setImage(currentPhotoObject.location, currentPhotoFilter, currentPhotoObjectThumb != null ? currentPhotoObjectThumb.location : null, currentPhotoFilterThumb, currentPhotoObject.size, null, false);
photoImage.setImage(currentPhotoObject.location, currentPhotoFilter, currentPhotoObjectThumb != null ? currentPhotoObjectThumb.location : null, currentPhotoFilterThumb, currentPhotoObject.size, null, currentMessageObject.shouldEncryptPhotoOrVideo() ? 2 : 0);
} else if (currentMessageObject.type == 8) {
currentMessageObject.gifState = 2;
photoImage.setImage(currentMessageObject.messageOwner.media.document, null, currentPhotoObject != null ? currentPhotoObject.location : null, currentPhotoFilterThumb, currentMessageObject.messageOwner.media.document.size, null, false);
photoImage.setImage(currentMessageObject.messageOwner.media.document, null, currentPhotoObject != null ? currentPhotoObject.location : null, currentPhotoFilterThumb, currentMessageObject.messageOwner.media.document.size, null, 0);
} else if (currentMessageObject.isRoundVideo()) {
if (currentMessageObject.isSecretMedia()) {
FileLoader.getInstance().loadFile(currentMessageObject.getDocument(), true, true);
FileLoader.getInstance().loadFile(currentMessageObject.getDocument(), true, 1);
} else {
currentMessageObject.gifState = 2;
TLRPC.Document document = currentMessageObject.getDocument();
photoImage.setImage(document, null, currentPhotoObject != null ? currentPhotoObject.location : null, currentPhotoFilterThumb, document.size, null, false);
photoImage.setImage(document, null, currentPhotoObject != null ? currentPhotoObject.location : null, currentPhotoFilterThumb, document.size, null, 0);
}
} else if (currentMessageObject.type == 9) {
FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.document, false, false);
FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.document, false, 0);
} else if (documentAttachType == DOCUMENT_ATTACH_TYPE_VIDEO) {
FileLoader.getInstance().loadFile(documentAttach, true, false);
FileLoader.getInstance().loadFile(documentAttach, true, currentMessageObject.shouldEncryptPhotoOrVideo() ? 2 : 0);
} else if (currentMessageObject.type == 0 && documentAttachType != DOCUMENT_ATTACH_TYPE_NONE) {
if (documentAttachType == DOCUMENT_ATTACH_TYPE_GIF) {
photoImage.setImage(currentMessageObject.messageOwner.media.webpage.document, null, currentPhotoObject.location, currentPhotoFilterThumb, currentMessageObject.messageOwner.media.webpage.document.size, null, false);
photoImage.setImage(currentMessageObject.messageOwner.media.webpage.document, null, currentPhotoObject.location, currentPhotoFilterThumb, currentMessageObject.messageOwner.media.webpage.document.size, null, 0);
currentMessageObject.gifState = 2;
} else if (documentAttachType == DOCUMENT_ATTACH_TYPE_DOCUMENT) {
FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.webpage.document, false, false);
FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.webpage.document, false, 0);
}
} else {
photoImage.setImage(currentPhotoObject.location, currentPhotoFilter, currentPhotoObjectThumb != null ? currentPhotoObjectThumb.location : null, currentPhotoFilterThumb, 0, null, false);
photoImage.setImage(currentPhotoObject.location, currentPhotoFilter, currentPhotoObjectThumb != null ? currentPhotoObjectThumb.location : null, currentPhotoFilterThumb, 0, null, 0);
}
buttonState = 1;
radialProgress.setBackground(getDrawableForCurrentState(), true, animated);
@ -4558,7 +4604,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} else if (buttonState == 2) {
if (documentAttachType == DOCUMENT_ATTACH_TYPE_AUDIO || documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC) {
radialProgress.setProgress(0, false);
FileLoader.getInstance().loadFile(documentAttach, true, false);
FileLoader.getInstance().loadFile(documentAttach, true, 0);
buttonState = 4;
radialProgress.setBackground(getDrawableForCurrentState(), true, false);
invalidate();
@ -4673,10 +4719,20 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
}
private void measureTime(MessageObject messageObject) {
boolean hasSign = !messageObject.isOutOwner() && messageObject.messageOwner.from_id > 0 && messageObject.messageOwner.post;
TLRPC.User signUser = MessagesController.getInstance().getUser(messageObject.messageOwner.from_id);
if (hasSign && signUser == null) {
hasSign = false;
CharSequence signString;
if (messageObject.messageOwner.post_author != null) {
signString = messageObject.messageOwner.post_author.replace("\n", "");
} else if (messageObject.messageOwner.fwd_from != null && messageObject.messageOwner.fwd_from.post_author != null) {
signString = messageObject.messageOwner.fwd_from.post_author.replace("\n", "");
} else if (!messageObject.isOutOwner() && messageObject.messageOwner.from_id > 0 && messageObject.messageOwner.post) {
TLRPC.User signUser = MessagesController.getInstance().getUser(messageObject.messageOwner.from_id);
if (signUser != null) {
signString = ContactsController.formatName(signUser.first_name, signUser.last_name).replace('\n', ' ');
} else {
signString = null;
}
} else {
signString = null;
}
String timeString;
TLRPC.User author = null;
@ -4688,7 +4744,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} else {
timeString = LocaleController.getInstance().formatterDay.format((long) (messageObject.messageOwner.date) * 1000);
}
if (hasSign) {
if (signString != null) {
currentTimeString = ", " + timeString;
} else {
currentTimeString = timeString;
@ -4699,18 +4755,17 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
viewsTextWidth = (int) Math.ceil(Theme.chat_timePaint.measureText(currentViewsString));
timeWidth += viewsTextWidth + Theme.chat_msgInViewsDrawable.getIntrinsicWidth() + AndroidUtilities.dp(10);
}
if (hasSign) {
if (signString != null) {
if (availableTimeWidth == 0) {
availableTimeWidth = AndroidUtilities.dp(1000);
}
CharSequence name = ContactsController.formatName(signUser.first_name, signUser.last_name).replace('\n', ' ');
int widthForSign = availableTimeWidth - timeWidth;
int width = (int) Math.ceil(Theme.chat_timePaint.measureText(name, 0, name.length()));
int width = (int) Math.ceil(Theme.chat_timePaint.measureText(signString, 0, signString.length()));
if (width > widthForSign) {
name = TextUtils.ellipsize(name, Theme.chat_timePaint, widthForSign, TextUtils.TruncateAt.END);
signString = TextUtils.ellipsize(signString, Theme.chat_timePaint, widthForSign, TextUtils.TruncateAt.END);
width = widthForSign;
}
currentTimeString = name + currentTimeString;
currentTimeString = signString + currentTimeString;
timeTextWidth += width;
timeWidth += width;
}
@ -4791,7 +4846,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
currentPhoto = null;
avatarDrawable.setInfo(messageObject.messageOwner.from_id, null, null, false);
}
avatarImage.setImage(currentPhoto, "50_50", avatarDrawable, null, false);
avatarImage.setImage(currentPhoto, "50_50", avatarDrawable, null, 0);
}
@ -4970,7 +5025,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
replyImageReceiver.setRoundRadius(0);
}
currentReplyPhoto = photoSize.location;
replyImageReceiver.setImage(photoSize.location, "50_50", null, null, true);
replyImageReceiver.setImage(photoSize.location, "50_50", null, null, 1);
needReplyImage = true;
maxWidth -= AndroidUtilities.dp(44);
}
@ -5351,10 +5406,14 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} else {
paint = Theme.chat_timeBackgroundPaint;
}
int oldAlpha = paint.getAlpha();
paint.setAlpha((int) (oldAlpha * controlsAlpha));
Theme.chat_timePaint.setAlpha((int) (255 * controlsAlpha));
int x1 = timeX - AndroidUtilities.dp(4);
int y1 = layoutHeight - AndroidUtilities.dp(28);
rect.set(x1, y1, x1 + timeWidth + AndroidUtilities.dp(8 + (currentMessageObject.isOutOwner() ? 20 : 0)), y1 + AndroidUtilities.dp(17));
canvas.drawRoundRect(rect, AndroidUtilities.dp(4), AndroidUtilities.dp(4), paint);
paint.setAlpha(oldAlpha);
int additionalX = (int) (-timeLayout.getLineLeft(0));
if ((currentMessageObject.messageOwner.flags & TLRPC.MESSAGE_FLAG_HAS_VIEWS) != 0) {
@ -5381,8 +5440,11 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} else {
viewsDrawable = Theme.chat_msgMediaViewsDrawable;
}
oldAlpha = ((BitmapDrawable) viewsDrawable).getPaint().getAlpha();
viewsDrawable.setAlpha((int) (controlsAlpha * oldAlpha));
setDrawableBounds(viewsDrawable, timeX, layoutHeight - AndroidUtilities.dp(10.5f) - timeLayout.getHeight());
viewsDrawable.draw(canvas);
viewsDrawable.setAlpha(oldAlpha);
if (viewsLayout != null) {
canvas.save();
@ -5397,6 +5459,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
canvas.translate(timeX + additionalX, layoutHeight - AndroidUtilities.dp(12.3f) - timeLayout.getHeight());
timeLayout.draw(canvas);
canvas.restore();
Theme.chat_timePaint.setAlpha(255);
} else {
int additionalX = (int) (-timeLayout.getLineLeft(0));
if ((currentMessageObject.messageOwner.flags & TLRPC.MESSAGE_FLAG_HAS_VIEWS) != 0) {
@ -5448,7 +5511,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
boolean drawCheck2 = false;
boolean drawClock = false;
boolean drawError = false;
boolean isBroadcast = (int)(currentMessageObject.getDialogId() >> 32) == 1;
boolean isBroadcast = (int) (currentMessageObject.getDialogId() >> 32) == 1;
if (currentMessageObject.isSending()) {
drawCheck1 = false;
@ -5521,7 +5584,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
} else {
setDrawableBounds(Theme.chat_msgMediaCheckDrawable, layoutWidth - AndroidUtilities.dp(21.5f) - Theme.chat_msgMediaCheckDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dp(13.5f) - Theme.chat_msgMediaCheckDrawable.getIntrinsicHeight());
}
Theme.chat_msgMediaCheckDrawable.setAlpha((int) (255 * controlsAlpha));
Theme.chat_msgMediaCheckDrawable.draw(canvas);
Theme.chat_msgMediaCheckDrawable.setAlpha(255);
}
}
}
@ -5536,7 +5601,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
Theme.chat_msgStickerHalfCheckDrawable.draw(canvas);
} else {
setDrawableBounds(Theme.chat_msgMediaHalfCheckDrawable, layoutWidth - AndroidUtilities.dp(21.5f) - Theme.chat_msgMediaHalfCheckDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dp(13.5f) - Theme.chat_msgMediaHalfCheckDrawable.getIntrinsicHeight());
Theme.chat_msgMediaHalfCheckDrawable.setAlpha((int) (255 * controlsAlpha));
Theme.chat_msgMediaHalfCheckDrawable.draw(canvas);
Theme.chat_msgMediaHalfCheckDrawable.setAlpha(255);
}
}
}
@ -5558,6 +5625,21 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
}
}
}
if (controlsAlpha != 1.0f) {
long newTime = System.currentTimeMillis();
long dt = Math.abs(lastControlsAlphaChangeTime - newTime);
if (dt > 17) {
dt = 17;
}
totalChangeTime += dt;
if (totalChangeTime > 100) {
totalChangeTime = 100;
}
lastControlsAlphaChangeTime = newTime;
controlsAlpha = AndroidUtilities.decelerateInterpolator.getInterpolation(totalChangeTime / 100.0f);
invalidate();
}
}
@Override

View File

@ -260,15 +260,15 @@ public class ContextLinkCell extends View implements MediaController.FileDownloa
if (documentAttachType == DOCUMENT_ATTACH_TYPE_GIF) {
if (documentAttach != null) {
linkImageView.setImage(documentAttach, null, currentPhotoObject != null ? currentPhotoObject.location : null, currentPhotoFilter, documentAttach.size, ext, false);
linkImageView.setImage(documentAttach, null, currentPhotoObject != null ? currentPhotoObject.location : null, currentPhotoFilter, documentAttach.size, ext, 0);
} else {
linkImageView.setImage(null, url, null, null, currentPhotoObject != null ? currentPhotoObject.location : null, currentPhotoFilter, -1, ext, true);
linkImageView.setImage(null, url, null, null, currentPhotoObject != null ? currentPhotoObject.location : null, currentPhotoFilter, -1, ext, 1);
}
} else {
if (currentPhotoObject != null) {
linkImageView.setImage(currentPhotoObject.location, currentPhotoFilter, currentPhotoObjectThumb != null ? currentPhotoObjectThumb.location : null, currentPhotoFilterThumb, currentPhotoObject.size, ext, false);
linkImageView.setImage(currentPhotoObject.location, currentPhotoFilter, currentPhotoObjectThumb != null ? currentPhotoObjectThumb.location : null, currentPhotoFilterThumb, currentPhotoObject.size, ext, 0);
} else {
linkImageView.setImage(null, url, currentPhotoFilter, null, currentPhotoObjectThumb != null ? currentPhotoObjectThumb.location : null, currentPhotoFilterThumb, -1, ext, true);
linkImageView.setImage(null, url, currentPhotoFilter, null, currentPhotoObjectThumb != null ? currentPhotoObjectThumb.location : null, currentPhotoFilterThumb, -1, ext, 1);
}
}
drawLinkImageView = true;
@ -340,6 +340,7 @@ public class ContextLinkCell extends View implements MediaController.FileDownloa
message.date = (int) (System.currentTimeMillis() / 1000);
message.message = "-1";
message.media = new TLRPC.TL_messageMediaDocument();
message.media.flags |= 3;
message.media.document = new TLRPC.TL_document();
message.flags |= TLRPC.MESSAGE_FLAG_HAS_MEDIA | TLRPC.MESSAGE_FLAG_HAS_FROM_ID;
@ -534,7 +535,7 @@ public class ContextLinkCell extends View implements MediaController.FileDownloa
} else if (buttonState == 2) {
radialProgress.setProgress(0, false);
if (documentAttach != null) {
FileLoader.getInstance().loadFile(documentAttach, true, false);
FileLoader.getInstance().loadFile(documentAttach, true, 0);
} else {
ImageLoader.getInstance().loadHttpFile(inlineResult.content_url, documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC ? "mp3" : "ogg");
}

View File

@ -27,6 +27,7 @@ import org.telegram.messenger.MessageObject;
import org.telegram.messenger.UserObject;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.query.DraftQuery;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.Emoji;
@ -465,7 +466,11 @@ public class DialogCell extends BaseCell {
}
messageString = Emoji.replaceEmoji(stringBuilder, Theme.dialogs_messagePaint.getFontMetricsInt(), AndroidUtilities.dp(20), false);
} else {
if (message.caption != null) {
if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto && message.messageOwner.media.photo instanceof TLRPC.TL_photoEmpty && message.messageOwner.media.ttl_seconds != 0) {
messageString = LocaleController.getString("AttachPhotoExpired", R.string.AttachPhotoExpired);
} else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaDocument && message.messageOwner.media.document instanceof TLRPC.TL_documentEmpty && message.messageOwner.media.ttl_seconds != 0) {
messageString = LocaleController.getString("AttachVideoExpired", R.string.AttachVideoExpired);
} else if (message.caption != null) {
messageString = message.caption;
} else {
if (message.messageOwner.media instanceof TLRPC.TL_messageMediaGame) {
@ -797,7 +802,7 @@ public class DialogCell extends BaseCell {
drawPin = customDialog.pinned;
dialogMuted = customDialog.muted;
avatarDrawable.setInfo(customDialog.id, customDialog.name, null, false);
avatarImage.setImage(null, "50_50", avatarDrawable, null, false);
avatarImage.setImage((TLObject) null, "50_50", avatarDrawable, null, 0);
} else {
if (isDialogCell) {
TLRPC.TL_dialog dialog = MessagesController.getInstance().dialogs_dict.get(currentDialogId);
@ -912,7 +917,7 @@ public class DialogCell extends BaseCell {
}
avatarDrawable.setInfo(chat);
}
avatarImage.setImage(photo, "50_50", avatarDrawable, null, false);
avatarImage.setImage(photo, "50_50", avatarDrawable, null, 0);
}
if (getMeasuredWidth() != 0 || getMeasuredHeight() != 0) {
buildLayout();

View File

@ -129,13 +129,13 @@ public class FeaturedStickerSetCell extends FrameLayout {
}
}
};
addButton.setPadding(AndroidUtilities.dp(17), 0, AndroidUtilities.dp(17), 0);
addButton.setGravity(Gravity.CENTER);
addButton.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText));
addButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
addButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
addButton.setBackgroundDrawable(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), Theme.getColor(Theme.key_featuredStickers_addButton), Theme.getColor(Theme.key_featuredStickers_addButtonPressed)));
addButton.setText(LocaleController.getString("Add", R.string.Add).toUpperCase());
addButton.setPadding(AndroidUtilities.dp(17), 0, AndroidUtilities.dp(17), 0);
addView(addButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 28, Gravity.TOP | (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT), LocaleController.isRTL ? 14 : 0, 18, LocaleController.isRTL ? 0 : 14, 0));
checkImage = new ImageView(context);

View File

@ -100,7 +100,7 @@ public class PaymentInfoCell extends FrameLayout {
detailTextView.setLayoutParams(LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 10 : 123, 33, LocaleController.isRTL ? 123 : 10, 0));
detailExTextView.setLayoutParams(LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 10 : 123, 90, LocaleController.isRTL ? 123 : 10, 0));
imageView.setVisibility(VISIBLE);
imageView.getImageReceiver().setImage(invoice.photo, null, String.format(Locale.US, "%d_%d", width, height), null, null, null, -1, null, true);
imageView.getImageReceiver().setImage(invoice.photo, null, String.format(Locale.US, "%d_%d", width, height), null, null, null, -1, null, 1);
} else {
nameTextView.setLayoutParams(LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 17, 9, 17, 0));
detailTextView.setLayoutParams(LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 17, 33, 17, 0));

View File

@ -0,0 +1,124 @@
/*
* This is the source code of Telegram for Android v. 3.x.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-2017.
*/
package org.telegram.ui.Cells;
import android.content.Context;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.RadioButton;
public class PhotoEditRadioCell extends FrameLayout {
private TextView nameTextView;
private int currentType;
private LinearLayout tintButtonsContainer;
private OnClickListener onClickListener;
private int currentColor;
private final int[] tintShadowColors = new int[] {
0x00000000,
0xffff4d4d,
0xfff48022,
0xffffcd00,
0xff81d281,
0xff71c5d6,
0xff0072bc,
0xff662d91
};
private final int[] tintHighlighsColors = new int[] {
0x00000000,
0xffef9286,
0xffeacea2,
0xfff2e17c,
0xffa4edae,
0xff89dce5,
0xff2e8bc8,
0xffcd98e5
};
public PhotoEditRadioCell(Context context) {
super(context);
nameTextView = new TextView(context);
nameTextView.setGravity(Gravity.RIGHT);
nameTextView.setTextColor(0xffffffff);
nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
nameTextView.setMaxLines(1);
nameTextView.setSingleLine(true);
nameTextView.setEllipsize(TextUtils.TruncateAt.END);
addView(nameTextView, LayoutHelper.createFrame(80, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 0, 0, 0, 0));
tintButtonsContainer = new LinearLayout(context);
tintButtonsContainer.setOrientation(LinearLayout.HORIZONTAL);
for (int a = 0; a < tintShadowColors.length; a++) {
RadioButton radioButton = new RadioButton(context);
radioButton.setSize(AndroidUtilities.dp(20));
radioButton.setTag(a);
tintButtonsContainer.addView(radioButton, LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f / tintShadowColors.length));
radioButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
RadioButton radioButton = (RadioButton) v;
if (currentType == 0) {
currentColor = tintShadowColors[(Integer) radioButton.getTag()];
} else {
currentColor = tintHighlighsColors[(Integer) radioButton.getTag()];
}
updateSelectedTintButton(true);
onClickListener.onClick(PhotoEditRadioCell.this);
}
});
}
addView(tintButtonsContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 40, Gravity.LEFT | Gravity.TOP, 96, 0, 24, 0));
}
public int getCurrentColor() {
return currentColor;
}
private void updateSelectedTintButton(boolean animated) {
int childCount = tintButtonsContainer.getChildCount();
for (int a = 0; a < childCount; a++) {
View child = tintButtonsContainer.getChildAt(a);
if (child instanceof RadioButton) {
RadioButton radioButton = (RadioButton) child;
int num = (Integer) radioButton.getTag();
int color2 = currentType == 0 ? tintShadowColors[num] : tintHighlighsColors[num];
radioButton.setChecked(currentColor == color2, animated);
radioButton.setColor(num == 0 ? 0xffffffff : (currentType == 0 ? tintShadowColors[num] : tintHighlighsColors[num]), num == 0 ? 0xffffffff : (currentType == 0 ? tintShadowColors[num] : tintHighlighsColors[num]));
}
}
}
@Override
public void setOnClickListener(OnClickListener l) {
onClickListener = l;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(40), MeasureSpec.EXACTLY));
}
public void setIconAndTextAndValue(String text, int type, int value) {
currentType = type;
currentColor = value;
nameTextView.setText(text.substring(0, 1).toUpperCase() + text.substring(1).toLowerCase());
updateSelectedTintButton(false);
}
}

View File

@ -8,72 +8,136 @@
package org.telegram.ui.Cells;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.PhotoEditorSeekBar;
public class PhotoEditToolCell extends FrameLayout {
private ImageView iconImage;
private TextView nameTextView;
private TextView valueTextView;
private PhotoEditorSeekBar seekBar;
private AnimatorSet valueAnimation;
private Runnable hideValueRunnable = new Runnable() {
@Override
public void run() {
valueTextView.setTag(null);
valueAnimation = new AnimatorSet();
valueAnimation.playTogether(
ObjectAnimator.ofFloat(valueTextView, "alpha", 0.0f),
ObjectAnimator.ofFloat(nameTextView, "alpha", 1.0f));
valueAnimation.setDuration(180);
valueAnimation.setInterpolator(new DecelerateInterpolator());
valueAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (animation.equals(valueAnimation)) {
valueAnimation = null;
}
}
});
valueAnimation.start();
}
};
private int width;
public PhotoEditToolCell(Context context, int w) {
public PhotoEditToolCell(Context context) {
super(context);
width = w;
iconImage = new ImageView(context);
iconImage.setScaleType(ImageView.ScaleType.CENTER);
addView(iconImage, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.CENTER, 0, 0, 7, 12));
nameTextView = new TextView(context);
nameTextView.setGravity(Gravity.CENTER);
nameTextView.setGravity(Gravity.RIGHT);
nameTextView.setTextColor(0xffffffff);
nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10);
nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
nameTextView.setMaxLines(1);
nameTextView.setSingleLine(true);
nameTextView.setEllipsize(TextUtils.TruncateAt.END);
addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER | Gravity.BOTTOM, 0, 0, 7, 0));
addView(nameTextView, LayoutHelper.createFrame(80, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 0, 0, 0, 0));
valueTextView = new TextView(context);
valueTextView.setTextColor(0xff6cc3ff);
valueTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 11);
valueTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
valueTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
valueTextView.setGravity(Gravity.RIGHT);
valueTextView.setSingleLine(true);
addView(valueTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 50, 3, 0, 0));
addView(valueTextView, LayoutHelper.createFrame(80, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 0, 0, 0, 0));
seekBar = new PhotoEditorSeekBar(context);
addView(seekBar, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 40, Gravity.LEFT | Gravity.CENTER_VERTICAL, 96, 0, 24, 0));
}
public void setSeekBarDelegate(final PhotoEditorSeekBar.PhotoEditorSeekBarDelegate photoEditorSeekBarDelegate) {
seekBar.setDelegate(new PhotoEditorSeekBar.PhotoEditorSeekBarDelegate() {
@Override
public void onProgressChanged(int i, int progress) {
photoEditorSeekBarDelegate.onProgressChanged(i, progress);
if (progress > 0) {
valueTextView.setText("+" + progress);
} else {
valueTextView.setText("" + progress);
}
if (valueTextView.getTag() == null) {
if (valueAnimation != null) {
valueAnimation.cancel();
}
valueTextView.setTag(1);
valueAnimation = new AnimatorSet();
valueAnimation.playTogether(
ObjectAnimator.ofFloat(valueTextView, "alpha", 1.0f),
ObjectAnimator.ofFloat(nameTextView, "alpha", 0.0f));
valueAnimation.setDuration(180);
valueAnimation.setInterpolator(new DecelerateInterpolator());
valueAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
AndroidUtilities.runOnUIThread(hideValueRunnable, 1000);
}
});
valueAnimation.start();
} else {
AndroidUtilities.cancelRunOnUIThread(hideValueRunnable);
AndroidUtilities.runOnUIThread(hideValueRunnable, 1000);
}
}
});
}
@Override
public void setTag(Object tag) {
super.setTag(tag);
seekBar.setTag(tag);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(60), MeasureSpec.EXACTLY));
super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(40), MeasureSpec.EXACTLY));
}
public void setIconAndTextAndValue(int resId, String text, float value) {
iconImage.setImageResource(resId);
nameTextView.setText(text.toUpperCase());
if (value == 0) {
valueTextView.setText("");
} else if (value > 0) {
public void setIconAndTextAndValue(String text, float value, int min, int max) {
if (valueAnimation != null) {
valueAnimation.cancel();
valueAnimation = null;
}
AndroidUtilities.cancelRunOnUIThread(hideValueRunnable);
valueTextView.setTag(null);
nameTextView.setText(text.substring(0, 1).toUpperCase() + text.substring(1).toLowerCase());
if (value > 0) {
valueTextView.setText("+" + (int) value);
} else {
valueTextView.setText("" + (int) value);
}
}
public void setIconAndTextAndValue(int resId, String text, String value) {
iconImage.setImageResource(resId);
nameTextView.setText(text.toUpperCase());
valueTextView.setText(value);
valueTextView.setAlpha(0.0f);
nameTextView.setAlpha(1.0f);
seekBar.setMinMax(min, max);
seekBar.setProgress((int) value, false);
}
}

View File

@ -429,7 +429,7 @@ public class ProfileSearchCell extends BaseCell {
lastAvatar = photo;
avatarImage.setImage(photo, "50_50", avatarDrawable, null, false);
avatarImage.setImage(photo, "50_50", avatarDrawable, null, 0);
if (getMeasuredWidth() != 0 || getMeasuredHeight() != 0) {
buildLayout();

View File

@ -14,7 +14,6 @@ import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
@ -279,10 +278,10 @@ public class SharedLinkCell extends FrameLayout {
}
String filter = String.format(Locale.US, "%d_%d", maxPhotoWidth, maxPhotoWidth);
if (photoExist || MediaController.getInstance().canDownloadMedia(MediaController.AUTODOWNLOAD_MASK_PHOTO) || FileLoader.getInstance().isLoadingFile(fileName)) {
linkImageView.setImage(currentPhotoObject.location, filter, currentPhotoObjectThumb != null ? currentPhotoObjectThumb.location : null, String.format(Locale.US, "%d_%d_b", maxPhotoWidth, maxPhotoWidth), 0, null, false);
linkImageView.setImage(currentPhotoObject.location, filter, currentPhotoObjectThumb != null ? currentPhotoObjectThumb.location : null, String.format(Locale.US, "%d_%d_b", maxPhotoWidth, maxPhotoWidth), 0, null, 0);
} else {
if (currentPhotoObjectThumb != null) {
linkImageView.setImage(null, null, currentPhotoObjectThumb.location, String.format(Locale.US, "%d_%d_b", maxPhotoWidth, maxPhotoWidth), 0, null, false);
linkImageView.setImage(null, null, currentPhotoObjectThumb.location, String.format(Locale.US, "%d_%d_b", maxPhotoWidth, maxPhotoWidth), 0, null, 0);
} else {
linkImageView.setImageBitmap((Drawable) null);
}
@ -378,7 +377,7 @@ public class SharedLinkCell extends FrameLayout {
} else if (linkPreviewPressed) {
try {
TLRPC.WebPage webPage = pressedLink == 0 && message.messageOwner.media != null ? message.messageOwner.media.webpage : null;
if (webPage != null && Build.VERSION.SDK_INT >= 16 && webPage.embed_url != null && webPage.embed_url.length() != 0) {
if (webPage != null && webPage.embed_url != null && webPage.embed_url.length() != 0) {
delegate.needOpenWebView(webPage);
} else {
Browser.openUrl(getContext(), links.get(pressedLink));

View File

@ -28,6 +28,7 @@ public class TextDetailCell extends FrameLayout {
private TextView textView;
private TextView valueTextView;
private ImageView imageView;
private boolean multiline;
public TextDetailCell(Context context) {
super(context);
@ -35,9 +36,6 @@ public class TextDetailCell extends FrameLayout {
textView = new TextView(context);
textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
textView.setLines(1);
textView.setMaxLines(1);
textView.setSingleLine(true);
textView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, LocaleController.isRTL ? 16 : 71, 10, LocaleController.isRTL ? 71 : 16, 0));
@ -53,12 +51,28 @@ public class TextDetailCell extends FrameLayout {
imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhiteGrayIcon), PorterDuff.Mode.MULTIPLY));
addView(imageView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL, LocaleController.isRTL ? 0 : 16, 0, LocaleController.isRTL ? 16 : 0, 0));
addView(imageView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 0 : 16, 11, LocaleController.isRTL ? 16 : 0, 0));
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(64), View.MeasureSpec.EXACTLY));
if (!multiline) {
super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(64), View.MeasureSpec.EXACTLY));
} else {
measureChildWithMargins(textView, widthMeasureSpec, 0, heightMeasureSpec, 0);
measureChildWithMargins(valueTextView, widthMeasureSpec, 0, heightMeasureSpec, 0);
measureChildWithMargins(imageView, widthMeasureSpec, 0, heightMeasureSpec, 0);
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), Math.max(AndroidUtilities.dp(64), textView.getMeasuredHeight() + valueTextView.getMeasuredHeight() + AndroidUtilities.dp(10 + 10)));
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (multiline) {
int y = textView.getMeasuredHeight() + AndroidUtilities.dp(10 + 3);
valueTextView.layout(valueTextView.getLeft(), y, valueTextView.getRight(), y + valueTextView.getMeasuredHeight());
}
}
public void setTextAndValue(String text, String value) {
@ -67,10 +81,26 @@ public class TextDetailCell extends FrameLayout {
imageView.setVisibility(INVISIBLE);
}
public void setTextAndValueAndIcon(String text, String value, int resId) {
public void setTextAndValueAndIcon(String text, String value, int resId, int offset) {
textView.setText(text);
valueTextView.setText(value);
imageView.setVisibility(VISIBLE);
imageView.setImageResource(resId);
if (offset == 0) {
imageView.setLayoutParams(LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL, LocaleController.isRTL ? 0 : 16, 0, LocaleController.isRTL ? 16 : 0, 0));
} else {
imageView.setLayoutParams(LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 0 : 16, offset, LocaleController.isRTL ? 16 : 0, 0));
}
}
public void setMultiline(boolean value) {
multiline = value;
if (multiline) {
textView.setSingleLine(false);
} else {
textView.setLines(1);
textView.setMaxLines(1);
textView.setSingleLine(true);
}
}
}

View File

@ -0,0 +1,292 @@
/*
* This is the source code of Telegram for Android v. 3.x.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-2017.
*/
package org.telegram.ui;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Vibrator;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.UserConfig;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.RequestDelegate;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.ActionBar;
import org.telegram.ui.ActionBar.ActionBarMenu;
import org.telegram.ui.ActionBar.AlertDialog;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.ActionBar.ThemeDescription;
import org.telegram.ui.Components.AlertsCreator;
import org.telegram.ui.Components.LayoutHelper;
public class ChangeBioActivity extends BaseFragment {
private EditText firstNameField;
private View doneButton;
private TextView checkTextView;
private TextView helpTextView;
private final static int done_button = 1;
@Override
public View createView(Context context) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);
actionBar.setTitle(LocaleController.getString("UserBio", R.string.UserBio));
actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
@Override
public void onItemClick(int id) {
if (id == -1) {
finishFragment();
} else if (id == done_button) {
saveName();
}
}
});
ActionBarMenu menu = actionBar.createMenu();
doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56));
fragmentView = new LinearLayout(context);
LinearLayout linearLayout = (LinearLayout) fragmentView;
linearLayout.setOrientation(LinearLayout.VERTICAL);
fragmentView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
FrameLayout fieldContainer = new FrameLayout(context);
linearLayout.addView(fieldContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 24, 24, 20, 0));
firstNameField = new EditText(context);
firstNameField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
firstNameField.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText));
firstNameField.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
firstNameField.setBackgroundDrawable(Theme.createEditTextDrawable(context, false));
firstNameField.setMaxLines(4);
firstNameField.setPadding(AndroidUtilities.dp(LocaleController.isRTL ? 24 : 0), 0, AndroidUtilities.dp(LocaleController.isRTL ? 0 : 24), AndroidUtilities.dp(6));
firstNameField.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
firstNameField.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
firstNameField.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
firstNameField.setImeOptions(EditorInfo.IME_ACTION_DONE);
InputFilter[] inputFilters = new InputFilter[1];
inputFilters[0] = new InputFilter.LengthFilter(70) {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (source != null && TextUtils.indexOf(source, '\n') != -1) {
doneButton.performClick();
return "";
}
CharSequence result = super.filter(source, start, end, dest, dstart, dend);
if (result != null && source != null && result.length() != source.length()) {
Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE);
if (v != null) {
v.vibrate(200);
}
AndroidUtilities.shakeView(checkTextView, 2, 0);
}
return result;
}
};
firstNameField.setFilters(inputFilters);
firstNameField.setMinHeight(AndroidUtilities.dp(36));
firstNameField.setHint(LocaleController.getString("UserBio", R.string.UserBio));
AndroidUtilities.clearCursorDrawable(firstNameField);
firstNameField.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i == EditorInfo.IME_ACTION_DONE && doneButton != null) {
doneButton.performClick();
return true;
}
return false;
}
});
firstNameField.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
checkTextView.setText("" + (70 - firstNameField.length()));
}
});
fieldContainer.addView(firstNameField, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 0, 0, 4, 0));
checkTextView = new TextView(context);
checkTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
checkTextView.setText("70");
checkTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText4));
fieldContainer.addView(checkTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT, 0, 4, 4, 0));
helpTextView = new TextView(context);
helpTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
helpTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText8));
helpTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
helpTextView.setText(AndroidUtilities.replaceTags(LocaleController.getString("UserBioInfo", R.string.UserBioInfo)));
linearLayout.addView(helpTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, 24, 10, 24, 0));
TLRPC.TL_userFull userFull = MessagesController.getInstance().getUserFull(UserConfig.getClientUserId());
if (userFull != null && userFull.about != null) {
firstNameField.setText(userFull.about);
firstNameField.setSelection(firstNameField.length());
}
return fragmentView;
}
@Override
public void onResume() {
super.onResume();
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
boolean animations = preferences.getBoolean("view_animations", true);
if (!animations) {
firstNameField.requestFocus();
AndroidUtilities.showKeyboard(firstNameField);
}
}
private void saveName() {
final TLRPC.TL_userFull userFull = MessagesController.getInstance().getUserFull(UserConfig.getClientUserId());
if (getParentActivity() == null || userFull == null) {
return;
}
String currentName = userFull.about;
if (currentName == null) {
currentName = "";
}
final String newName = firstNameField.getText().toString().replace("\n", "");
if (currentName.equals(newName)) {
finishFragment();
return;
}
final AlertDialog progressDialog = new AlertDialog(getParentActivity(), 1);
progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading));
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
final TLRPC.TL_account_updateProfile req = new TLRPC.TL_account_updateProfile();
req.about = newName;
req.flags |= 4;
final int reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, final TLRPC.TL_error error) {
if (error == null) {
final TLRPC.User user = (TLRPC.User)response;
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
try {
progressDialog.dismiss();
} catch (Exception e) {
FileLog.e(e);
}
userFull.about = newName;
NotificationCenter.getInstance().postNotificationName(NotificationCenter.userInfoDidLoaded, user.id, userFull);
finishFragment();
}
});
} else {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
try {
progressDialog.dismiss();
} catch (Exception e) {
FileLog.e(e);
}
AlertsCreator.processError(error, ChangeBioActivity.this, req);
}
});
}
}
}, ConnectionsManager.RequestFlagFailOnServerErrors);
ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid);
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, LocaleController.getString("Cancel", R.string.Cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ConnectionsManager.getInstance().cancelRequest(reqId, true);
try {
dialog.dismiss();
} catch (Exception e) {
FileLog.e(e);
}
}
});
progressDialog.show();
}
@Override
public void onTransitionAnimationEnd(boolean isOpen, boolean backward) {
if (isOpen) {
firstNameField.requestFocus();
AndroidUtilities.showKeyboard(firstNameField);
}
}
@Override
public ThemeDescription[] getThemeDescriptions() {
return new ThemeDescription[]{
new ThemeDescription(fragmentView, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_windowBackgroundWhite),
new ThemeDescription(actionBar, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_actionBarDefault),
new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_ITEMSCOLOR, null, null, null, null, Theme.key_actionBarDefaultIcon),
new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_TITLECOLOR, null, null, null, null, Theme.key_actionBarDefaultTitle),
new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SELECTORCOLOR, null, null, null, null, Theme.key_actionBarDefaultSelector),
new ThemeDescription(firstNameField, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_windowBackgroundWhiteBlackText),
new ThemeDescription(firstNameField, ThemeDescription.FLAG_HINTTEXTCOLOR, null, null, null, null, Theme.key_windowBackgroundWhiteHintText),
new ThemeDescription(firstNameField, ThemeDescription.FLAG_BACKGROUNDFILTER, null, null, null, null, Theme.key_windowBackgroundWhiteInputField),
new ThemeDescription(firstNameField, ThemeDescription.FLAG_BACKGROUNDFILTER | ThemeDescription.FLAG_DRAWABLESELECTEDSTATE, null, null, null, null, Theme.key_windowBackgroundWhiteInputFieldActivated),
new ThemeDescription(helpTextView, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_windowBackgroundWhiteGrayText8),
new ThemeDescription(checkTextView, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_windowBackgroundWhiteGrayText4),
};
}
}

View File

@ -2120,7 +2120,7 @@ public class ChannelAdminLogActivity extends BaseFragment implements PhotoViewer
MessageObject message = cell.getMessageObject();
if (message.type == 13) {
showDialog(new StickersAlert(getParentActivity(), ChannelAdminLogActivity.this, message.getInputStickerSet(), null, null));
} else if (Build.VERSION.SDK_INT >= 16 && message.isVideo() || message.type == 1 || message.type == 0 && !message.isWebpageDocument() || message.isGif()) {
} else if (message.isVideo() || message.type == 1 || message.type == 0 && !message.isWebpageDocument() || message.isGif()) {
PhotoViewer.getInstance().setParentActivity(getParentActivity());
PhotoViewer.getInstance().openPhoto(message, message.type != 0 ? dialog_id : 0, 0, ChannelAdminLogActivity.this);
} else if (message.type == 3) {

View File

@ -285,7 +285,6 @@ public class ChannelRightsEditActivity extends BaseFragment {
} else if (position == removeAdminRow) {
if (currentType == 0) {
MessagesController.setUserAdminRole(chatId, currentUser, new TLRPC.TL_channelAdminRights(), isMegagroup, getFragmentForAlert(0));
finishFragment();
} else if (currentType == 1) {
bannedRights = new TLRPC.TL_channelBannedRights();
bannedRights.view_messages = true;
@ -298,11 +297,11 @@ public class ChannelRightsEditActivity extends BaseFragment {
bannedRights.embed_links = true;
bannedRights.until_date = 0;
MessagesController.setUserBannedRole(chatId, currentUser, bannedRights, isMegagroup, getFragmentForAlert(0));
finishFragment();
}
if (delegate != null) {
delegate.didSetRights(0, adminRights, bannedRights);
}
finishFragment();
} else if (position == untilDateRow) {
if (getParentActivity() == null) {
return;

View File

@ -698,7 +698,8 @@ public class ChannelUsersActivity extends BaseFragment implements NotificationCe
public void didReceivedNotification(int id, Object... args) {
if (id == NotificationCenter.chatInfoDidLoaded) {
TLRPC.ChatFull chatFull = (TLRPC.ChatFull) args[0];
if (chatFull.id == chatId) {
boolean byChannelUsers = (Boolean) args[2];
if (chatFull.id == chatId && !byChannelUsers) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
@ -733,8 +734,9 @@ public class ChannelUsersActivity extends BaseFragment implements NotificationCe
}
TLRPC.TL_channels_getParticipants req = new TLRPC.TL_channels_getParticipants();
req.channel = MessagesController.getInputChannel(chatId);
final boolean byEndReached = firstEndReached;
if (type == 0) {
if (firstEndReached) {
if (byEndReached) {
req.filter = new TLRPC.TL_channelParticipantsKicked();
} else {
req.filter = new TLRPC.TL_channelParticipantsBanned();
@ -772,9 +774,10 @@ public class ChannelUsersActivity extends BaseFragment implements NotificationCe
}
}
if (type == 0) {
if (firstEndReached) {
if (byEndReached) {
participants2 = res.participants;
} else {
participants2 = new ArrayList<>();
participantsMap.clear();
participants = res.participants;
if (changeFirst) {

View File

@ -310,8 +310,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
private MessageObject replyingMessageObject;
private int editingMessageObjectReqId;
private boolean paused = true;
private boolean wasPaused = false;
private boolean readWhenResume = false;
private boolean wasPaused;
private boolean readWhenResume;
private TLRPC.FileLocation replyImageLocation;
private TLRPC.FileLocation pinnedImageLocation;
private int linkSearchRequestId;
@ -373,7 +373,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
private String currentPicturePath;
protected TLRPC.ChatFull info = null;
protected TLRPC.ChatFull info;
private HashMap<Integer, TLRPC.BotInfo> botInfo = new HashMap<>();
private String botUser;
@ -382,14 +382,10 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
private MessageObject botReplyButtons;
private int botsCount;
private boolean hasBotsCommands;
private long chatEnterTime = 0;
private long chatLeaveTime = 0;
private long chatEnterTime;
private long chatLeaveTime;
private String startVideoEdit = null;
private Runnable openSecretPhotoRunnable = null;
private float startX = 0;
private float startY = 0;
private String startVideoEdit;
private FrameLayout roundVideoContainer;
private AspectRatioFrameLayout aspectRatioFrameLayout;
@ -681,11 +677,14 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
dialog_id = ((long) encId) << 32;
maxMessageId[0] = maxMessageId[1] = Integer.MIN_VALUE;
minMessageId[0] = minMessageId[1] = Integer.MAX_VALUE;
MediaController.getInstance().startMediaObserver();
} else {
return false;
}
if (currentUser != null) {
MediaController.getInstance().startMediaObserver();
}
NotificationCenter.getInstance().addObserver(this, NotificationCenter.messagesDidLoaded);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.emojiDidLoaded);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces);
@ -863,8 +862,10 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (AndroidUtilities.isTablet()) {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.openedChatChanged, dialog_id, true);
}
if (currentEncryptedChat != null) {
if (currentUser != null) {
MediaController.getInstance().stopMediaObserver();
}
if (currentEncryptedChat != null) {
try {
if (Build.VERSION.SDK_INT >= 23 && (UserConfig.passcodeHash.length() == 0 || UserConfig.allowScreenCapture)) {
getParentActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
@ -1736,116 +1737,6 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
updateMessagesVisisblePart();
}
});
chatListView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (openSecretPhotoRunnable != null || SecretPhotoViewer.getInstance().isVisible()) {
if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_POINTER_UP) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
chatListView.setOnItemClickListener(onItemClickListener);
}
}, 150);
if (openSecretPhotoRunnable != null) {
AndroidUtilities.cancelRunOnUIThread(openSecretPhotoRunnable);
openSecretPhotoRunnable = null;
try {
Toast.makeText(v.getContext(), LocaleController.getString("PhotoTip", R.string.PhotoTip), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
FileLog.e(e);
}
} else if (SecretPhotoViewer.getInstance().isVisible()) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
chatListView.setOnItemLongClickListener(onItemLongClickListener);
chatListView.setLongClickable(true);
}
});
SecretPhotoViewer.getInstance().closePhoto();
}
} else if (event.getAction() != MotionEvent.ACTION_DOWN) {
if (SecretPhotoViewer.getInstance().isVisible()) {
return true;
} else if (openSecretPhotoRunnable != null) {
if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (Math.hypot(startX - event.getX(), startY - event.getY()) > AndroidUtilities.dp(5)) {
AndroidUtilities.cancelRunOnUIThread(openSecretPhotoRunnable);
openSecretPhotoRunnable = null;
}
} else {
AndroidUtilities.cancelRunOnUIThread(openSecretPhotoRunnable);
openSecretPhotoRunnable = null;
}
chatListView.setOnItemClickListener(onItemClickListener);
chatListView.setOnItemLongClickListener(onItemLongClickListener);
chatListView.setLongClickable(true);
}
}
}
return false;
}
});
chatListView.setOnInterceptTouchListener(new RecyclerListView.OnInterceptTouchListener() {
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (chatActivityEnterView != null && chatActivityEnterView.isEditingMessage()) {
return true;
}
if (actionBar.isActionModeShowed()) {
return false;
}
if (event.getAction() == MotionEvent.ACTION_DOWN) {
int x = (int) event.getX();
int y = (int) event.getY();
int count = chatListView.getChildCount();
for (int a = 0; a < count; a++) {
View view = chatListView.getChildAt(a);
int top = view.getTop();
int bottom = view.getBottom();
if (top > y || bottom < y) {
continue;
}
if (!(view instanceof ChatMessageCell)) {
break;
}
final ChatMessageCell cell = (ChatMessageCell) view;
final MessageObject messageObject = cell.getMessageObject();
if (messageObject == null || messageObject.isSending() || messageObject.isRoundVideo() || !messageObject.isSecretPhoto() || !cell.getPhotoImage().isInsideImage(x, y - top)) {
break;
}
File file = FileLoader.getPathToMessage(messageObject.messageOwner);
if (!file.exists()) {
break;
}
startX = x;
startY = y;
chatListView.setOnItemClickListener(null);
openSecretPhotoRunnable = new Runnable() {
@Override
public void run() {
if (openSecretPhotoRunnable == null) {
return;
}
chatListView.requestDisallowInterceptTouchEvent(true);
chatListView.setOnItemLongClickListener(null);
chatListView.setLongClickable(false);
openSecretPhotoRunnable = null;
if (sendSecretMessageRead(messageObject)) {
cell.invalidate();
}
SecretPhotoViewer.getInstance().setParentActivity(getParentActivity());
SecretPhotoViewer.getInstance().openPhoto(messageObject);
}
};
AndroidUtilities.runOnUIThread(openSecretPhotoRunnable, 100);
return true;
}
}
return false;
}
});
if (scrollToPositionOnRecreate != -1) {
chatLayoutManager.scrollToPositionWithOffset(scrollToPositionOnRecreate, scrollToOffsetOnRecreate);
scrollToPositionOnRecreate = -1;
@ -2450,8 +2341,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
return;
}
TLRPC.BotInlineResult result = (TLRPC.BotInlineResult) object;
if (Build.VERSION.SDK_INT >= 16 &&
(result.type.equals("photo") && (result.photo != null || result.content_url != null) ||
if ((result.type.equals("photo") && (result.photo != null || result.content_url != null) ||
result.type.equals("gif") && (result.document != null || result.content_url != null) ||
result.type.equals("video") && (result.document != null/* || result.content_url != null*/))) {
ArrayList<Object> arrayList = botContextResults = new ArrayList<Object>(mentionsAdapter.getSearchResultBotContext());
@ -2570,10 +2460,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
contentView.addView(overlayView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
overlayView.setVisibility(View.GONE);
if (Build.VERSION.SDK_INT >= 16) {
instantCameraView = new InstantCameraView(context, this);
contentView.addView(instantCameraView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
}
instantCameraView = new InstantCameraView(context, this);
contentView.addView(instantCameraView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
chatActivityEnterView = new ChatActivityEnterView(getParentActivity(), contentView, this, true);
chatActivityEnterView.setDialogId(dialog_id);
@ -2899,7 +2787,6 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
searchContainer.setFocusableInTouchMode(true);
searchContainer.setClickable(true);
searchContainer.setPadding(0, AndroidUtilities.dp(3), 0, 0);
contentView.addView(searchContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));
searchUpButton = new ImageView(context);
searchUpButton.setScaleType(ImageView.ScaleType.CENTER);
@ -3096,6 +2983,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
bottomOverlayChatText.setTextColor(Theme.getColor(Theme.key_chat_fieldOverlayText));
bottomOverlayChat.addView(bottomOverlayChatText, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
contentView.addView(searchContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));
chatAdapter.updateRows();
if (loading && messages.isEmpty()) {
progressView.setVisibility(chatAdapter.botInfoRow == -1 ? View.VISIBLE : View.INVISIBLE);
@ -3335,14 +3224,15 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (!selectedPhotos.isEmpty()) {
ArrayList<String> photos = new ArrayList<>();
ArrayList<String> captions = new ArrayList<>();
ArrayList<Integer> ttls = new ArrayList<>();
ArrayList<ArrayList<TLRPC.InputDocument>> masks = new ArrayList<>();
for (HashMap.Entry<Integer, MediaController.PhotoEntry> entry : selectedPhotos.entrySet()) {
MediaController.PhotoEntry photoEntry = entry.getValue();
if (photoEntry.isVideo) {
if (photoEntry.editedInfo != null) {
SendMessagesHelper.prepareSendingVideo(photoEntry.path, photoEntry.editedInfo.estimatedSize, photoEntry.editedInfo.estimatedDuration, photoEntry.editedInfo.resultWidth, photoEntry.editedInfo.resultHeight, photoEntry.editedInfo, dialog_id, replyingMessageObject, photoEntry.caption);
SendMessagesHelper.prepareSendingVideo(photoEntry.path, photoEntry.editedInfo.estimatedSize, photoEntry.editedInfo.estimatedDuration, photoEntry.editedInfo.resultWidth, photoEntry.editedInfo.resultHeight, photoEntry.editedInfo, dialog_id, replyingMessageObject, photoEntry.caption, photoEntry.ttl);
} else {
SendMessagesHelper.prepareSendingVideo(photoEntry.path, 0, 0, 0, 0, null, dialog_id, replyingMessageObject, photoEntry.caption);
SendMessagesHelper.prepareSendingVideo(photoEntry.path, 0, 0, 0, 0, null, dialog_id, replyingMessageObject, photoEntry.caption, photoEntry.ttl);
}
continue;
}
@ -3350,17 +3240,16 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
photos.add(photoEntry.imagePath);
captions.add(photoEntry.caption != null ? photoEntry.caption.toString() : null);
masks.add(!photoEntry.stickers.isEmpty() ? new ArrayList<>(photoEntry.stickers) : null);
ttls.add(photoEntry.ttl);
} else if (photoEntry.path != null) {
photos.add(photoEntry.path);
captions.add(photoEntry.caption != null ? photoEntry.caption.toString() : null);
masks.add(!photoEntry.stickers.isEmpty() ? new ArrayList<>(photoEntry.stickers) : null);
ttls.add(photoEntry.ttl);
}
photoEntry.imagePath = null;
photoEntry.thumbPath = null;
photoEntry.caption = null;
photoEntry.stickers.clear();
photoEntry.reset();
}
SendMessagesHelper.prepareSendingPhotos(photos, null, dialog_id, replyingMessageObject, captions, masks, null, button == 4);
SendMessagesHelper.prepareSendingPhotos(photos, null, dialog_id, replyingMessageObject, captions, masks, null, button == 4, ttls);
showReplyPanel(false, null, null, null, false);
DraftQuery.cleanDraft(dialog_id, true);
}
@ -3413,7 +3302,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
for (int a = messages.size() - 1; a >= 0; a--) {
MessageObject messageObject = messages.get(a);
if ((messageObject.isVoice() || messageObject.isRoundVideo()) && messageObject.isContentUnread() && !messageObject.isOut() && messageObject.messageOwner.to_id.channel_id == 0) {
MediaController.getInstance().setVoiceMessagesPlaylist(MediaController.getInstance().playMessage(messageObject) ? createVoiceMessagesPlaylist(messageObject, true) : null, true); //TODO
MediaController.getInstance().setVoiceMessagesPlaylist(MediaController.getInstance().playMessage(messageObject) ? createVoiceMessagesPlaylist(messageObject, true) : null, true);
return true;
}
}
@ -3978,16 +3867,16 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
PhotoAlbumPickerActivity fragment = new PhotoAlbumPickerActivity(false, currentEncryptedChat == null || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46, true, ChatActivity.this);
fragment.setDelegate(new PhotoAlbumPickerActivity.PhotoAlbumPickerActivityDelegate() {
@Override
public void didSelectPhotos(ArrayList<String> photos, ArrayList<String> captions, ArrayList<MediaController.PhotoEntry> videos, ArrayList<ArrayList<TLRPC.InputDocument>> masks, ArrayList<MediaController.SearchImage> webPhotos) {
public void didSelectPhotos(ArrayList<String> photos, ArrayList<String> captions, ArrayList<Integer> ttls, ArrayList<MediaController.PhotoEntry> videos, ArrayList<ArrayList<TLRPC.InputDocument>> masks, ArrayList<MediaController.SearchImage> webPhotos) {
for (int a = 0; a < videos.size(); a++) {
MediaController.PhotoEntry video = videos.get(a);
if (video.editedInfo != null) {
SendMessagesHelper.prepareSendingVideo(video.path, video.editedInfo.estimatedSize, video.editedInfo.estimatedDuration, video.editedInfo.resultWidth, video.editedInfo.resultHeight, video.editedInfo, dialog_id, replyingMessageObject, video.caption);
SendMessagesHelper.prepareSendingVideo(video.path, video.editedInfo.estimatedSize, video.editedInfo.estimatedDuration, video.editedInfo.resultWidth, video.editedInfo.resultHeight, video.editedInfo, dialog_id, replyingMessageObject, video.caption, video.ttl);
} else {
SendMessagesHelper.prepareSendingVideo(video.path, 0, 0, 0, 0, null, dialog_id, replyingMessageObject, video.caption);
SendMessagesHelper.prepareSendingVideo(video.path, 0, 0, 0, 0, null, dialog_id, replyingMessageObject, video.caption, video.ttl);
}
}
SendMessagesHelper.prepareSendingPhotos(photos, null, dialog_id, replyingMessageObject, captions, masks, null, false);
SendMessagesHelper.prepareSendingPhotos(photos, null, dialog_id, replyingMessageObject, captions, masks, null, false, ttls);
SendMessagesHelper.prepareSendingPhotosSearch(webPhotos, dialog_id, replyingMessageObject);
showReplyPanel(false, null, null, null, false);
DraftQuery.cleanDraft(dialog_id, true);
@ -4011,17 +3900,6 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
FileLog.e(e);
}
}
@Override
public void didSelectVideo(String path, VideoEditedInfo info, long estimatedSize, long estimatedDuration, String caption) {
if (info != null) {
SendMessagesHelper.prepareSendingVideo(path, estimatedSize, estimatedDuration, info.resultWidth, info.resultHeight, info, dialog_id, replyingMessageObject, caption);
} else {
SendMessagesHelper.prepareSendingVideo(path, 0, 0, 0, 0, null, dialog_id, replyingMessageObject, null);
}
showReplyPanel(false, null, null, null, false);
DraftQuery.cleanDraft(dialog_id, true);
}
});
presentFragment(fragment);
} else if (which == attach_video) {
@ -4572,7 +4450,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
private void moveScrollToLastMessage() {
if (chatListView != null && !messages.isEmpty()) {
chatLayoutManager.scrollToPositionWithOffset(messages.size() - 1, -100000 - chatListView.getPaddingTop());
chatLayoutManager.scrollToPositionWithOffset(messages.size() - 1, -999999 - chatListView.getPaddingTop());
}
}
@ -4580,7 +4458,11 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (messageObject == null || messageObject.isOut() || !messageObject.isSecretMedia() || messageObject.messageOwner.destroyTime != 0 || messageObject.messageOwner.ttl <= 0) {
return false;
}
MessagesController.getInstance().markMessageAsRead(dialog_id, messageObject.messageOwner.random_id, messageObject.messageOwner.ttl);
if (currentEncryptedChat != null) {
MessagesController.getInstance().markMessageAsRead(dialog_id, messageObject.messageOwner.random_id, messageObject.messageOwner.ttl);
} else {
MessagesController.getInstance().markMessageAsRead(messageObject.getId(), ChatObject.isChannel(currentChat) ? currentChat.id : 0, messageObject.messageOwner.ttl);
}
messageObject.messageOwner.destroyTime = messageObject.messageOwner.ttl + ConnectionsManager.getInstance().getCurrentTime();
return true;
}
@ -4626,7 +4508,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
highlightMessageId = Integer.MAX_VALUE;
updateVisibleRows();
} else {
chatLayoutManager.scrollToPositionWithOffset(messages.size() - 1, -100000 - chatListView.getPaddingTop());
chatLayoutManager.scrollToPositionWithOffset(messages.size() - 1, -999999 - chatListView.getPaddingTop());
}
} else {
clearChatData();
@ -5422,7 +5304,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
}
public boolean openVideoEditor(String videoPath, boolean removeLast, boolean animated) {
Bundle args = new Bundle();
/*Bundle args = new Bundle(); TODO
args.putString("videoPath", videoPath);
VideoEditorActivity fragment = new VideoEditorActivity(args);
fragment.setDelegate(new VideoEditorActivity.VideoEditorActivityDelegate() {
@ -5439,22 +5321,22 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
videoEditedInfo.resultHeight = resultHeight;
videoEditedInfo.originalPath = videoPath;
videoEditedInfo.muted = videoEditedInfo.bitrate == -1;
SendMessagesHelper.prepareSendingVideo(videoPath, estimatedSize, estimatedDuration, resultWidth, resultHeight, videoEditedInfo, dialog_id, replyingMessageObject, caption);
SendMessagesHelper.prepareSendingVideo(videoPath, estimatedSize, estimatedDuration, resultWidth, resultHeight, videoEditedInfo, dialog_id, replyingMessageObject, caption, 0);
showReplyPanel(false, null, null, null, false);
DraftQuery.cleanDraft(dialog_id, true);
}
});
});*/
if (parentLayout == null || !fragment.onFragmentCreate()) {
SendMessagesHelper.prepareSendingVideo(videoPath, 0, 0, 0, 0, null, dialog_id, replyingMessageObject, null);
//if (parentLayout == null || !fragment.onFragmentCreate()) {
SendMessagesHelper.prepareSendingVideo(videoPath, 0, 0, 0, 0, null, dialog_id, replyingMessageObject, null, 0);
showReplyPanel(false, null, null, null, false);
DraftQuery.cleanDraft(dialog_id, true);
return false;
}
if (parentLayout.presentFragment(fragment, removeLast, !animated, true)) {
fragment.setParentChatActivity(this);
}
return true;
//}
//if (parentLayout.presentFragment(fragment, removeLast, !animated, true)) {
// fragment.setParentChatActivity(this);
//}
//return true;
}
private void showAttachmentError() {
@ -5515,17 +5397,13 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (videoPath == null) {
showAttachmentError();
}
if (Build.VERSION.SDK_INT >= 16) {
if (paused) {
startVideoEdit = videoPath;
} else {
openVideoEditor(videoPath, false, false);
}
if (paused) {
startVideoEdit = videoPath;
} else {
SendMessagesHelper.prepareSendingVideo(videoPath, 0, 0, 0, 0, null, dialog_id, replyingMessageObject, null);
openVideoEditor(videoPath, false, false);
}
} else {
SendMessagesHelper.prepareSendingPhoto(null, uri, dialog_id, replyingMessageObject, null, null, null);
SendMessagesHelper.prepareSendingPhoto(null, uri, dialog_id, replyingMessageObject, null, null, null, 0);
}
showReplyPanel(false, null, null, null, false);
DraftQuery.cleanDraft(dialog_id, true);
@ -5559,16 +5437,10 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
}
currentPicturePath = null;
}
if (Build.VERSION.SDK_INT >= 16) {
if (paused) {
startVideoEdit = videoPath;
} else {
openVideoEditor(videoPath, false, false);
}
if (paused) {
startVideoEdit = videoPath;
} else {
SendMessagesHelper.prepareSendingVideo(videoPath, 0, 0, 0, 0, null, dialog_id, replyingMessageObject, null);
showReplyPanel(false, null, null, null, false);
DraftQuery.cleanDraft(dialog_id, true);
openVideoEditor(videoPath, false, false);
}
} else if (requestCode == 21) {
if (data == null || data.getData() == null) {
@ -7031,13 +6903,23 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
}
}
} else if (id == NotificationCenter.didCreatedNewDeleteTask) {
SparseArray<ArrayList<Integer>> mids = (SparseArray<ArrayList<Integer>>) args[0];
SparseArray<ArrayList<Long>> mids = (SparseArray<ArrayList<Long>>) args[0];
boolean changed = false;
for (int i = 0; i < mids.size(); i++) {
int key = mids.keyAt(i);
ArrayList<Integer> arr = mids.get(key);
for (Integer mid : arr) {
MessageObject messageObject = messagesDict[0].get(mid);
ArrayList<Long> arr = mids.get(key);
for (int a = 0; a < arr.size(); a++) {
long mid = arr.get(a);
if (a == 0) {
int channelId = (int) (mid >> 32);
if (channelId < 0) {
channelId = 0;
}
if (channelId != (ChatObject.isChannel(currentChat) ? currentChat.id : 0)) {
return;
}
}
MessageObject messageObject = messagesDict[0].get((int) mid);
if (messageObject != null) {
messageObject.messageOwner.destroyTime = key;
changed = true;
@ -7143,14 +7025,19 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
}
}
} else if (id == NotificationCenter.updateMessageMedia) {
MessageObject messageObject = (MessageObject) args[0];
MessageObject existMessageObject = messagesDict[0].get(messageObject.getId());
TLRPC.Message message = (TLRPC.Message) args[0];
MessageObject existMessageObject = messagesDict[0].get(message.id);
if (existMessageObject != null) {
existMessageObject.messageOwner.media = messageObject.messageOwner.media;
existMessageObject.messageOwner.attachPath = messageObject.messageOwner.attachPath;
existMessageObject.messageOwner.media = message.media;
existMessageObject.messageOwner.attachPath = message.attachPath;
existMessageObject.generateThumbs(false);
if (message.media.ttl_seconds != 0 && (message.media.photo instanceof TLRPC.TL_photoEmpty || message.media.document instanceof TLRPC.TL_documentEmpty)) {
existMessageObject.setType();
chatAdapter.updateRowWithMessageObject(existMessageObject);
} else {
updateVisibleRows();
}
}
updateVisibleRows();
} else if (id == NotificationCenter.replaceMessagesObjects) {
long did = (long) args[0];
if (did != dialog_id && did != mergeDialogId) {
@ -8084,7 +7971,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (chatActivityEnterView != null) {
chatActivityEnterView.onResume();
}
if (currentEncryptedChat != null) {
if (currentUser != null) {
chatEnterTime = System.currentTimeMillis();
chatLeaveTime = 0;
}
@ -8170,7 +8057,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
}
editor.commit();
if (currentEncryptedChat != null) {
if (currentUser != null) {
chatLeaveTime = System.currentTimeMillis();
updateInformationForScreenshotDetector();
}
@ -8246,25 +8133,35 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
}
private void updateInformationForScreenshotDetector() {
if (currentEncryptedChat == null) {
if (currentUser == null) {
return;
}
ArrayList<Long> visibleMessages = new ArrayList<>();
if (chatListView != null) {
int count = chatListView.getChildCount();
for (int a = 0; a < count; a++) {
View view = chatListView.getChildAt(a);
MessageObject object = null;
if (view instanceof ChatMessageCell) {
ChatMessageCell cell = (ChatMessageCell) view;
object = cell.getMessageObject();
}
if (object != null && object.getId() < 0 && object.messageOwner.random_id != 0) {
visibleMessages.add(object.messageOwner.random_id);
ArrayList<Long> visibleMessages;
int messageId = 0;
if (currentEncryptedChat != null) {
visibleMessages = new ArrayList<>();
if (chatListView != null) {
int count = chatListView.getChildCount();
for (int a = 0; a < count; a++) {
View view = chatListView.getChildAt(a);
MessageObject object = null;
if (view instanceof ChatMessageCell) {
ChatMessageCell cell = (ChatMessageCell) view;
object = cell.getMessageObject();
}
if (object != null && object.getId() < 0 && object.messageOwner.random_id != 0) {
visibleMessages.add(object.messageOwner.random_id);
}
}
}
MediaController.getInstance().setLastVisibleMessageIds(chatEnterTime, chatLeaveTime, currentUser, currentEncryptedChat, visibleMessages, messageId);
} else {
SecretMediaViewer viewer = SecretMediaViewer.getInstance();
MessageObject messageObject = viewer.getCurrentMessageObject();
if (messageObject != null && !messageObject.isOut()) {
MediaController.getInstance().setLastVisibleMessageIds(viewer.getOpenTime(), viewer.getCloseTime(), currentUser, null, null, messageObject.getId());
}
}
MediaController.getInstance().setLastEncryptedChatParams(chatEnterTime, chatLeaveTime, currentEncryptedChat, visibleMessages);
}
private boolean fixLayoutInternal() {
@ -8656,14 +8553,14 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
boolean allowUnpin = message.getDialogId() != mergeDialogId && info != null && info.pinned_msg_id == message.getId() && (currentChat.creator || currentChat.admin_rights != null && currentChat.admin_rights.pin_messages);
boolean allowEdit = message.canEditMessage(currentChat) && !chatActivityEnterView.hasAudioToSend() && message.getDialogId() != mergeDialogId;
if (currentEncryptedChat != null && AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) < 46 ||
type == 1 && message.getDialogId() == mergeDialogId ||
type == 1 && (message.getDialogId() == mergeDialogId || message.isSecretPhoto()) ||
currentEncryptedChat == null && message.getId() < 0 ||
isBroadcast ||
currentChat != null && (ChatObject.isNotInChat(currentChat) || ChatObject.isChannel(currentChat) && !ChatObject.canPost(currentChat) && !currentChat.megagroup || !ChatObject.canSendMessages(currentChat))) {
allowChatActions = false;
}
if (single || type < 2 || type == 20) {
if (single || type < 2 || type == 20 || message.isSecretPhoto()) {
if (type >= 0) {
selectedObject = message;
if (getParentActivity() == null) {
@ -8743,10 +8640,12 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
}
} else if (type == 4) {
if (selectedObject.isVideo()) {
items.add(LocaleController.getString("SaveToGallery", R.string.SaveToGallery));
options.add(4);
items.add(LocaleController.getString("ShareFile", R.string.ShareFile));
options.add(6);
if (!selectedObject.isSecretPhoto()) {
items.add(LocaleController.getString("SaveToGallery", R.string.SaveToGallery));
options.add(4);
items.add(LocaleController.getString("ShareFile", R.string.ShareFile));
options.add(6);
}
} else if (selectedObject.isMusic()) {
items.add(LocaleController.getString("SaveToMusic", R.string.SaveToMusic));
options.add(10);
@ -8762,8 +8661,10 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
items.add(LocaleController.getString("ShareFile", R.string.ShareFile));
options.add(6);
} else {
items.add(LocaleController.getString("SaveToGallery", R.string.SaveToGallery));
options.add(4);
if (!selectedObject.isSecretPhoto()) {
items.add(LocaleController.getString("SaveToGallery", R.string.SaveToGallery));
options.add(4);
}
}
} else if (type == 5) {
items.add(LocaleController.getString("ApplyLocalizationFile", R.string.ApplyLocalizationFile));
@ -8806,8 +8707,10 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
options.add(17);
}
}
items.add(LocaleController.getString("Forward", R.string.Forward));
options.add(2);
if (!selectedObject.isSecretPhoto()) {
items.add(LocaleController.getString("Forward", R.string.Forward));
options.add(2);
}
if (allowUnpin) {
items.add(LocaleController.getString("UnpinMessage", R.string.UnpinMessage));
options.add(14);
@ -9650,16 +9553,16 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
public void sendMedia(MediaController.PhotoEntry photoEntry, VideoEditedInfo videoEditedInfo) {
if (photoEntry.isVideo) {
SendMessagesHelper.prepareSendingVideo(photoEntry.path, videoEditedInfo.estimatedSize, videoEditedInfo.estimatedDuration, videoEditedInfo.resultWidth, videoEditedInfo.resultHeight, videoEditedInfo, dialog_id, replyingMessageObject, photoEntry.caption != null ? photoEntry.caption.toString() : null);
SendMessagesHelper.prepareSendingVideo(photoEntry.path, videoEditedInfo.estimatedSize, videoEditedInfo.estimatedDuration, videoEditedInfo.resultWidth, videoEditedInfo.resultHeight, videoEditedInfo, dialog_id, replyingMessageObject, photoEntry.caption != null ? photoEntry.caption.toString() : null, photoEntry.ttl);
showReplyPanel(false, null, null, null, false);
DraftQuery.cleanDraft(dialog_id, true);
} else {
if (photoEntry.imagePath != null) {
SendMessagesHelper.prepareSendingPhoto(photoEntry.imagePath, null, dialog_id, replyingMessageObject, photoEntry.caption, photoEntry.stickers, null);
SendMessagesHelper.prepareSendingPhoto(photoEntry.imagePath, null, dialog_id, replyingMessageObject, photoEntry.caption, photoEntry.stickers, null, photoEntry.ttl);
showReplyPanel(false, null, null, null, false);
DraftQuery.cleanDraft(dialog_id, true);
} else if (photoEntry.path != null) {
SendMessagesHelper.prepareSendingPhoto(photoEntry.path, null, dialog_id, replyingMessageObject, photoEntry.caption, photoEntry.stickers, null);
SendMessagesHelper.prepareSendingPhoto(photoEntry.path, null, dialog_id, replyingMessageObject, photoEntry.caption, photoEntry.stickers, null, photoEntry.ttl);
showReplyPanel(false, null, null, null, false);
DraftQuery.cleanDraft(dialog_id, true);
}
@ -9838,8 +9741,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
@Override
public void didPressedOther(ChatMessageCell cell) {
if (cell.getMessageObject().type == 16) {
if(currentUser!=null)
VoIPHelper.startCall(currentUser, getParentActivity(), MessagesController.getInstance().getUserFull(currentUser.id));
if (currentUser != null) {
VoIPHelper.startCall(currentUser, getParentActivity(), MessagesController.getInstance().getUserFull(currentUser.id));
}
} else {
createMenu(cell, true);
}
@ -9993,9 +9897,15 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
} else if (message.isSending()) {
return;
}
if (message.type == 13) {
if (message.isSecretPhoto()) {
if (sendSecretMessageRead(message)) {
cell.invalidate();
}
SecretMediaViewer.getInstance().setParentActivity(getParentActivity());
SecretMediaViewer.getInstance().openMedia(message, ChatActivity.this);
} else if (message.type == 13) {
showDialog(new StickersAlert(getParentActivity(), ChatActivity.this, message.getInputStickerSet(), null, bottomOverlayChat.getVisibility() != View.VISIBLE && ChatObject.canSendStickers(currentChat) ? chatActivityEnterView : null));
} else if (Build.VERSION.SDK_INT >= 16 && message.isVideo() || message.type == 1 || message.type == 0 && !message.isWebpageDocument() || message.isGif()) {
} else if (message.isVideo() || message.type == 1 || message.type == 0 && !message.isWebpageDocument() || message.isGif()) {
if (message.isVideo()) {
sendSecretMessageRead(message);
}

View File

@ -165,17 +165,13 @@ public class AvatarDrawable extends Drawable {
}
lastch = lastName.codePointAt(a);
}
if (Build.VERSION.SDK_INT >= 16) {
stringBuilder.append("\u200C");
}
stringBuilder.append("\u200C");
stringBuilder.appendCodePoint(lastch);
} else if (firstName != null && firstName.length() > 0) {
for (int a = firstName.length() - 1; a >= 0; a--) {
if (firstName.charAt(a) == ' ') {
if (a != firstName.length() - 1 && firstName.charAt(a + 1) != ' ') {
if (Build.VERSION.SDK_INT >= 16) {
stringBuilder.append("\u200C");
}
stringBuilder.append("\u200C");
stringBuilder.appendCodePoint(firstName.codePointAt(a + 1));
break;
}

View File

@ -103,7 +103,7 @@ public class AvatarUpdater implements NotificationCenter.NotificationCenterDeleg
PhotoAlbumPickerActivity fragment = new PhotoAlbumPickerActivity(true, false, false, null);
fragment.setDelegate(new PhotoAlbumPickerActivity.PhotoAlbumPickerActivityDelegate() {
@Override
public void didSelectPhotos(ArrayList<String> photos, ArrayList<String> captions, ArrayList<MediaController.PhotoEntry> videos, ArrayList<ArrayList<TLRPC.InputDocument>> masks, ArrayList<MediaController.SearchImage> webPhotos) {
public void didSelectPhotos(ArrayList<String> photos, ArrayList<String> captions, ArrayList<Integer> ttls, ArrayList<MediaController.PhotoEntry> videos, ArrayList<ArrayList<TLRPC.InputDocument>> masks, ArrayList<MediaController.SearchImage> webPhotos) {
if (!photos.isEmpty()) {
Bitmap bitmap = ImageLoader.loadBitmap(photos.get(0), null, 800, 800, true);
processBitmap(bitmap);
@ -120,11 +120,6 @@ public class AvatarUpdater implements NotificationCenter.NotificationCenterDeleg
FileLog.e(e);
}
}
@Override
public void didSelectVideo(String path, VideoEditedInfo info, long estimatedSize, long estimatedDuration, String caption) {
}
});
parentFragment.presentFragment(fragment);
}

View File

@ -81,7 +81,7 @@ public class BackupImageView extends View {
if (thumbBitmap != null) {
thumb = new BitmapDrawable(null, thumbBitmap);
}
imageReceiver.setImage(path, httpUrl, filter, thumb, thumbLocation, thumbFilter, size, ext, false);
imageReceiver.setImage(path, httpUrl, filter, thumb, thumbLocation, thumbFilter, size, ext, 0);
}
public void setImageBitmap(Bitmap bitmap) {

View File

@ -13,6 +13,7 @@ import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.ClipDescription;
import android.content.Context;
@ -20,7 +21,9 @@ import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.RectF;
@ -39,6 +42,7 @@ import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.util.Property;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
@ -169,6 +173,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
private ImageView sendButton;
private ImageView cancelBotButton;
private ImageView emojiButton;
private ImageView expandStickersButton;
private EmojiView emojiView;
private TextView recordTimeText;
private FrameLayout audioVideoButtonContainer;
@ -289,9 +294,48 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
}
}
};
private Runnable updateExpandabilityRunnable = new Runnable() {
private int lastKnownPage = -1;
@Override
public void run() {
if (emojiView != null) {
int curPage = emojiView.getCurrentPage();
if (curPage != lastKnownPage) {
lastKnownPage = curPage;
boolean prevOpen = stickersTabOpen;
stickersTabOpen = curPage == 1 || curPage == 2;
if (prevOpen != stickersTabOpen && curPage != 2)
checkSendButton(false);
if (!stickersTabOpen && stickersExpanded)
setStickersExpanded(false, true);
}
}
}
};
private Property<View, Integer> roundedTranslationYProperty=new Property<View, Integer>(Integer.class, "translationY"){
@Override
public Integer get(View object){
return Math.round(object.getTranslationY());
}
@Override
public void set(View object, Integer value){
object.setTranslationY(value);
}
};
private Paint redDotPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private boolean stickersTabOpen;
private boolean gifsTabOpen;
private boolean stickersExpanded;
private Animator stickersExpansionAnim;
private float stickersExpansionProgress;
private int stickersExpandedHeight;
private boolean stickersDragging;
private AnimatedArrowDrawable stickersArrow;
private boolean recordAudioVideoRunnableStarted;
private boolean calledRecordRunnable;
private Runnable recordAudioVideoRunnable = new Runnable() {
@ -726,7 +770,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
if (description.hasMimeType("image/gif")) {
SendMessagesHelper.prepareSendingDocument(null, null, inputContentInfo.getContentUri(), "image/gif", dialog_id, replyingMessageObject, inputContentInfo);
} else {
SendMessagesHelper.prepareSendingPhoto(null, inputContentInfo.getContentUri(), dialog_id, replyingMessageObject, null, null, inputContentInfo);
SendMessagesHelper.prepareSendingPhoto(null, inputContentInfo.getContentUri(), dialog_id, replyingMessageObject, null, null, inputContentInfo, 0);
}
if (delegate != null) {
delegate.onMessageSend(null);
@ -1009,7 +1053,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
}
@Override
public void onRifhtProgressChanged(float progress) {
public void onRightProgressChanged(float progress) {
if (videoToSendMessageObject == null) {
return;
}
@ -1314,6 +1358,23 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
}
});
expandStickersButton = new ImageView(context);
expandStickersButton.setScaleType(ImageView.ScaleType.CENTER);
expandStickersButton.setImageDrawable(stickersArrow = new AnimatedArrowDrawable(Theme.getColor(Theme.key_chat_messagePanelIcons)));
expandStickersButton.setVisibility(GONE);
expandStickersButton.setScaleX(0.1f);
expandStickersButton.setScaleY(0.1f);
expandStickersButton.setAlpha(0.0f);
sendButtonContainer.addView(expandStickersButton, LayoutHelper.createFrame(48, 48));
expandStickersButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!stickersDragging)
setStickersExpanded(!stickersExpanded, true);
}
});
doneButtonContainer = new FrameLayout(context);
doneButtonContainer.setVisibility(GONE);
textFieldContainer.addView(doneButtonContainer, LayoutHelper.createLinear(48, 48, Gravity.BOTTOM));
@ -1702,6 +1763,8 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
LayoutParams layoutParams = (LayoutParams) textFieldContainer.getLayoutParams();
layoutParams.topMargin = AndroidUtilities.dp(2) + (show ? topView.getLayoutParams().height : 0);
textFieldContainer.setLayoutParams(layoutParams);
if(stickersExpanded)
setStickersExpanded(false, true);
}
public void onDestroy() {
@ -1925,7 +1988,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
if (playing != null && playing == audioToSendMessageObject) {
MediaController.getInstance().cleanupPlayer(true, true);
}
SendMessagesHelper.getInstance().sendMessage(audioToSend, null, audioToSendPath, dialog_id, replyingMessageObject, null, null);
SendMessagesHelper.getInstance().sendMessage(audioToSend, null, audioToSendPath, dialog_id, replyingMessageObject, null, null, 0);
if (delegate != null) {
delegate.onMessageSend(null);
}
@ -1951,7 +2014,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
if (editingMessageObject != null) {
delegate.onMessageEditEnd(true);
showEditDoneProgress(true, true);
CharSequence[] message = new CharSequence[] {messageEditText.getText()};
CharSequence[] message = new CharSequence[]{messageEditText.getText()};
ArrayList<TLRPC.MessageEntity> entities = MessagesQuery.getEntities(message);
editingMessageReqId = SendMessagesHelper.getInstance().editMessage(editingMessageObject, message[0].toString(), messageWebPageSearch, parentFragment, entities, new Runnable() {
@Override
@ -1968,7 +2031,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
if (text.length() != 0) {
int count = (int) Math.ceil(text.length() / 4096.0f);
for (int a = 0; a < count; a++) {
CharSequence[] message = new CharSequence[] {text.subSequence(a * 4096, Math.min((a + 1) * 4096, text.length()))};
CharSequence[] message = new CharSequence[]{text.subSequence(a * 4096, Math.min((a + 1) * 4096, text.length()))};
ArrayList<TLRPC.MessageEntity> entities = MessagesQuery.getEntities(message);
SendMessagesHelper.getInstance().sendMessage(message[0].toString(), dialog_id, replyingMessageObject, messageWebPage, messageWebPageSearch, entities, null, null);
}
@ -1987,8 +2050,8 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
CharSequence message = AndroidUtilities.getTrimmedString(messageEditText.getText());
if (message.length() > 0 || forceShowSendButton || audioToSend != null || videoToSendMessageObject != null) {
final String caption = messageEditText.getCaption();
boolean showBotButton = caption != null && sendButton.getVisibility() == VISIBLE;
boolean showSendButton = caption == null && cancelBotButton.getVisibility() == VISIBLE;
boolean showBotButton = caption != null && (sendButton.getVisibility() == VISIBLE || expandStickersButton.getVisibility() == VISIBLE);
boolean showSendButton = caption == null && (cancelBotButton.getVisibility() == VISIBLE || expandStickersButton.getVisibility() == VISIBLE);
if (audioVideoButtonContainer.getVisibility() == VISIBLE || showBotButton || showSendButton) {
if (animated) {
if (runningAnimationType == 1 && messageEditText.getCaption() == null || runningAnimationType == 3 && caption != null) {
@ -2040,6 +2103,11 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
animators.add(ObjectAnimator.ofFloat(audioVideoButtonContainer, "scaleY", 0.1f));
animators.add(ObjectAnimator.ofFloat(audioVideoButtonContainer, "alpha", 0.0f));
}
if (expandStickersButton.getVisibility() == VISIBLE) {
animators.add(ObjectAnimator.ofFloat(expandStickersButton, "scaleX", 0.1f));
animators.add(ObjectAnimator.ofFloat(expandStickersButton, "scaleY", 0.1f));
animators.add(ObjectAnimator.ofFloat(expandStickersButton, "alpha", 0.0f));
}
if (showBotButton) {
animators.add(ObjectAnimator.ofFloat(sendButton, "scaleX", 0.1f));
animators.add(ObjectAnimator.ofFloat(sendButton, "scaleY", 0.1f));
@ -2077,6 +2145,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
cancelBotButton.setVisibility(GONE);
}
audioVideoButtonContainer.setVisibility(GONE);
expandStickersButton.setVisibility(GONE);
runningAnimation = null;
runningAnimationType = 0;
}
@ -2123,7 +2192,112 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
}
}
}
} else if (sendButton.getVisibility() == VISIBLE || cancelBotButton.getVisibility() == VISIBLE) {
} else if (emojiView != null && emojiView.getVisibility() == VISIBLE && stickersTabOpen && !AndroidUtilities.isInMultiwindow) {
if (animated) {
if (runningAnimationType == 4) {
return;
}
if (runningAnimation != null) {
runningAnimation.cancel();
runningAnimation = null;
}
if (runningAnimation2 != null) {
runningAnimation2.cancel();
runningAnimation2 = null;
}
if (attachLayout != null) {
attachLayout.setVisibility(VISIBLE);
runningAnimation2 = new AnimatorSet();
runningAnimation2.playTogether(
ObjectAnimator.ofFloat(attachLayout, "alpha", 1.0f),
ObjectAnimator.ofFloat(attachLayout, "scaleX", 1.0f)
);
runningAnimation2.setDuration(100);
runningAnimation2.start();
updateFieldRight(1);
if (getVisibility() == VISIBLE) {
delegate.onAttachButtonShow();
}
}
expandStickersButton.setVisibility(VISIBLE);
runningAnimation = new AnimatorSet();
runningAnimationType = 4;
ArrayList<Animator> animators = new ArrayList<>();
animators.add(ObjectAnimator.ofFloat(expandStickersButton, "scaleX", 1.0f));
animators.add(ObjectAnimator.ofFloat(expandStickersButton, "scaleY", 1.0f));
animators.add(ObjectAnimator.ofFloat(expandStickersButton, "alpha", 1.0f));
if (cancelBotButton.getVisibility() == VISIBLE) {
animators.add(ObjectAnimator.ofFloat(cancelBotButton, "scaleX", 0.1f));
animators.add(ObjectAnimator.ofFloat(cancelBotButton, "scaleY", 0.1f));
animators.add(ObjectAnimator.ofFloat(cancelBotButton, "alpha", 0.0f));
} else if (audioVideoButtonContainer.getVisibility() == VISIBLE) {
animators.add(ObjectAnimator.ofFloat(audioVideoButtonContainer, "scaleX", 0.1f));
animators.add(ObjectAnimator.ofFloat(audioVideoButtonContainer, "scaleY", 0.1f));
animators.add(ObjectAnimator.ofFloat(audioVideoButtonContainer, "alpha", 0.0f));
} else {
animators.add(ObjectAnimator.ofFloat(sendButton, "scaleX", 0.1f));
animators.add(ObjectAnimator.ofFloat(sendButton, "scaleY", 0.1f));
animators.add(ObjectAnimator.ofFloat(sendButton, "alpha", 0.0f));
}
runningAnimation.playTogether(animators);
runningAnimation.setDuration(150);
runningAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (runningAnimation != null && runningAnimation.equals(animation)) {
sendButton.setVisibility(GONE);
cancelBotButton.setVisibility(GONE);
audioVideoButtonContainer.setVisibility(GONE);
expandStickersButton.setVisibility(VISIBLE);
runningAnimation = null;
runningAnimationType = 0;
}
}
@Override
public void onAnimationCancel(Animator animation) {
if (runningAnimation != null && runningAnimation.equals(animation)) {
runningAnimation = null;
}
}
});
runningAnimation.start();
} else {
sendButton.setScaleX(0.1f);
sendButton.setScaleY(0.1f);
sendButton.setAlpha(0.0f);
cancelBotButton.setScaleX(0.1f);
cancelBotButton.setScaleY(0.1f);
cancelBotButton.setAlpha(0.0f);
audioVideoButtonContainer.setScaleX(0.1f);
audioVideoButtonContainer.setScaleY(0.1f);
audioVideoButtonContainer.setAlpha(0.0f);
expandStickersButton.setScaleX(1.0f);
expandStickersButton.setScaleY(1.0f);
expandStickersButton.setAlpha(1.0f);
cancelBotButton.setVisibility(GONE);
sendButton.setVisibility(GONE);
audioVideoButtonContainer.setVisibility(GONE);
expandStickersButton.setVisibility(VISIBLE);
if (attachLayout != null) {
if (getVisibility() == VISIBLE) {
delegate.onAttachButtonShow();
}
attachLayout.setVisibility(VISIBLE);
updateFieldRight(1);
}
}
/*expandStickersButton.setAlpha(1f);
expandStickersButton.setScaleX(1);
expandStickersButton.setScaleY(1);
expandStickersButton.setVisibility(VISIBLE);
audioVideoButtonContainer.setVisibility(GONE);*/
} else if (sendButton.getVisibility() == VISIBLE || cancelBotButton.getVisibility() == VISIBLE || expandStickersButton.getVisibility() == VISIBLE) {
if (animated) {
if (runningAnimationType == 2) {
return;
@ -2165,6 +2339,10 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
animators.add(ObjectAnimator.ofFloat(cancelBotButton, "scaleX", 0.1f));
animators.add(ObjectAnimator.ofFloat(cancelBotButton, "scaleY", 0.1f));
animators.add(ObjectAnimator.ofFloat(cancelBotButton, "alpha", 0.0f));
} else if (expandStickersButton.getVisibility() == VISIBLE) {
animators.add(ObjectAnimator.ofFloat(expandStickersButton, "scaleX", 0.1f));
animators.add(ObjectAnimator.ofFloat(expandStickersButton, "scaleY", 0.1f));
animators.add(ObjectAnimator.ofFloat(expandStickersButton, "alpha", 0.0f));
} else {
animators.add(ObjectAnimator.ofFloat(sendButton, "scaleX", 0.1f));
animators.add(ObjectAnimator.ofFloat(sendButton, "scaleY", 0.1f));
@ -2200,11 +2378,15 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
cancelBotButton.setScaleX(0.1f);
cancelBotButton.setScaleY(0.1f);
cancelBotButton.setAlpha(0.0f);
expandStickersButton.setScaleX(0.1f);
expandStickersButton.setScaleY(0.1f);
expandStickersButton.setAlpha(0.0f);
audioVideoButtonContainer.setScaleX(1.0f);
audioVideoButtonContainer.setScaleY(1.0f);
audioVideoButtonContainer.setAlpha(1.0f);
cancelBotButton.setVisibility(GONE);
sendButton.setVisibility(GONE);
expandStickersButton.setVisibility(GONE);
audioVideoButtonContainer.setVisibility(VISIBLE);
if (attachLayout != null) {
if (getVisibility() == VISIBLE) {
@ -2840,6 +3022,8 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
}
public void onStickerSelected(TLRPC.Document sticker) {
if(stickersExpanded)
setStickersExpanded(false, true);
ChatActivityEnterView.this.onStickerSelected(sticker);
StickersQuery.addRecentSticker(StickersQuery.TYPE_IMAGE, sticker, (int) (System.currentTimeMillis() / 1000));
if ((int) dialog_id == 0) {
@ -2856,6 +3040,8 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
@Override
public void onGifSelected(TLRPC.Document gif) {
if(stickersExpanded)
setStickersExpanded(false, true);
SendMessagesHelper.getInstance().sendSticker(gif, dialog_id, replyingMessageObject);
StickersQuery.addRecentGif(gif, (int) (System.currentTimeMillis() / 1000));
if ((int) dialog_id == 0) {
@ -2868,6 +3054,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
@Override
public void onGifTab(boolean opened) {
post(updateExpandabilityRunnable);
if (!AndroidUtilities.usingHardwareInput) {
if (opened) {
if (messageEditText.length() == 0) {
@ -2883,6 +3070,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
@Override
public void onStickersTab(boolean opened) {
delegate.onStickersTab(opened);
post(updateExpandabilityRunnable);
}
@Override
@ -2926,6 +3114,68 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
StickersQuery.removeStickersSet(parentActivity, stickerSet.set, 0, parentFragment, false);
}
});
emojiView.setDragListener(new EmojiView.DragListener() {
boolean wasExpanded;
int initialOffset;
@Override
public void onDragStart() {
if (!allowDragging()) {
return;
}
if (stickersExpansionAnim != null)
stickersExpansionAnim.cancel();
stickersDragging = true;
wasExpanded = stickersExpanded;
stickersExpanded = true;
stickersExpandedHeight = sizeNotifierLayout.getHeight() - (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? AndroidUtilities.statusBarHeight : 0) - ActionBar.getCurrentActionBarHeight() - getHeight() + Theme.chat_composeShadowDrawable.getIntrinsicHeight();
emojiView.getLayoutParams().height = stickersExpandedHeight;
emojiView.setLayerType(LAYER_TYPE_HARDWARE, null);
sizeNotifierLayout.requestLayout();
((FrameLayout) sizeNotifierLayout).setForeground(new ScrimDrawable());
initialOffset = (int) getTranslationY();
}
@Override
public void onDragEnd(float velocity) {
if (!allowDragging())
return;
stickersDragging = false;
if ((wasExpanded && velocity >= AndroidUtilities.dp(200)) || (!wasExpanded && velocity <= AndroidUtilities.dp(-200)) || (wasExpanded && stickersExpansionProgress <= 0.6f) || (!wasExpanded && stickersExpansionProgress >= 0.4f)) {
setStickersExpanded(!wasExpanded, true);
} else {
setStickersExpanded(wasExpanded, true);
}
}
@Override
public void onDragCancel() {
if (!stickersTabOpen) {
return;
}
stickersDragging = false;
setStickersExpanded(wasExpanded, true);
}
@Override
public void onDrag(int offset) {
if (!allowDragging()) {
return;
}
int origHeight = AndroidUtilities.displaySize.x > AndroidUtilities.displaySize.y ? keyboardHeightLand : keyboardHeight;
offset += initialOffset;
offset = Math.max(Math.min(offset, 0), -(stickersExpandedHeight - origHeight));
emojiView.setTranslationY(offset);
setTranslationY(offset);
stickersExpansionProgress = (float) offset / (-(stickersExpandedHeight - origHeight));
sizeNotifierLayout.invalidate();
}
private boolean allowDragging(){
return stickersTabOpen && !(!stickersExpanded && messageEditText.length()>0) && emojiView.areThereAnyStickers();
}
});
emojiView.setVisibility(GONE);
sizeNotifierLayout.addView(emojiView);
checkChannelRights();
@ -3020,6 +3270,12 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
}
updateBotButton();
}
if (stickersTabOpen) {
checkSendButton(true);
}
if (stickersExpanded && show != 1)
setStickersExpanded(false, false);
}
private void setEmojiButtonImage() {
@ -3036,6 +3292,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
} else if (currentPage == 2) {
emojiButton.setImageResource(R.drawable.ic_msg_panel_gif);
}
stickersTabOpen = currentPage == 1 || currentPage == 2;
}
public void hidePopup(boolean byBackButton) {
@ -3112,6 +3369,8 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (w != oldw && stickersExpanded)
setStickersExpanded(false, false);
videoTimelineView.clearFrames();
}
@ -3144,7 +3403,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
}
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) currentView.getLayoutParams();
if (layoutParams.width != AndroidUtilities.displaySize.x || layoutParams.height != newHeight) {
if ((layoutParams.width != AndroidUtilities.displaySize.x || layoutParams.height != newHeight) && !stickersExpanded) {
layoutParams.width = AndroidUtilities.displaySize.x;
layoutParams.height = newHeight;
currentView.setLayoutParams(layoutParams);
@ -3290,6 +3549,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
message.message = "-1";
message.attachPath = audioToSendPath;
message.media = new TLRPC.TL_messageMediaDocument();
message.media.flags |= 3;
message.media.document = audioToSend;
message.flags |= TLRPC.MESSAGE_FLAG_HAS_MEDIA | TLRPC.MESSAGE_FLAG_HAS_FROM_ID;
audioToSendMessageObject = new MessageObject(message, null, false);
@ -3363,4 +3623,190 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe
}
}
}
private void setStickersExpanded(boolean expanded, boolean animated) {
if(expanded && !emojiView.areThereAnyStickers())
return;
stickersExpanded = expanded;
//expandStickersButton.setRotationX(stickersExpanded ? 0 : 180);
final int origHeight = AndroidUtilities.displaySize.x > AndroidUtilities.displaySize.y ? keyboardHeightLand : keyboardHeight;
if (stickersExpansionAnim != null)
stickersExpansionAnim.cancel();
if (stickersExpanded) {
stickersExpandedHeight = sizeNotifierLayout.getHeight() - (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? AndroidUtilities.statusBarHeight : 0) - ActionBar.getCurrentActionBarHeight() - getHeight() + Theme.chat_composeShadowDrawable.getIntrinsicHeight();
emojiView.getLayoutParams().height = stickersExpandedHeight;
sizeNotifierLayout.requestLayout();
((FrameLayout) sizeNotifierLayout).setForeground(new ScrimDrawable());
messageEditText.setText(messageEditText.getText()); // dismiss action mode, if any
if (animated) {
AnimatorSet anims = new AnimatorSet();
anims.playTogether(
ObjectAnimator.ofInt(this, roundedTranslationYProperty, -(stickersExpandedHeight - origHeight)),
ObjectAnimator.ofInt(emojiView, roundedTranslationYProperty, -(stickersExpandedHeight - origHeight)),
ObjectAnimator.ofFloat(stickersArrow, "animationProgress", 1)
);
anims.setDuration(400);
anims.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT);
((ObjectAnimator) anims.getChildAnimations().get(0)).addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
//stickersExpansionProgress=animation.getAnimatedFraction();
stickersExpansionProgress = getTranslationY() / (-(stickersExpandedHeight - origHeight));
sizeNotifierLayout.invalidate();
}
});
anims.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
stickersExpansionAnim = null;
emojiView.setLayerType(LAYER_TYPE_NONE, null);
}
});
stickersExpansionAnim = anims;
emojiView.setLayerType(LAYER_TYPE_HARDWARE, null);
anims.start();
} else {
stickersExpansionProgress = 1;
setTranslationY(-(stickersExpandedHeight - origHeight));
emojiView.setTranslationY(-(stickersExpandedHeight - origHeight));
stickersArrow.setAnimationProgress(1);
}
} else {
if (animated) {
AnimatorSet anims = new AnimatorSet();
anims.playTogether(
ObjectAnimator.ofInt(this, roundedTranslationYProperty, 0),
ObjectAnimator.ofInt(emojiView, roundedTranslationYProperty, 0),
ObjectAnimator.ofFloat(stickersArrow, "animationProgress", 0)
);
anims.setDuration(400);
anims.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT);
((ObjectAnimator) anims.getChildAnimations().get(0)).addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
stickersExpansionProgress = getTranslationY() / (-(stickersExpandedHeight - origHeight));
sizeNotifierLayout.invalidate();
}
});
anims.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
stickersExpansionAnim = null;
emojiView.getLayoutParams().height = origHeight;
sizeNotifierLayout.requestLayout();
emojiView.setLayerType(LAYER_TYPE_NONE, null);
((FrameLayout) sizeNotifierLayout).setForeground(null);
sizeNotifierLayout.setWillNotDraw(false);
}
});
stickersExpansionAnim = anims;
emojiView.setLayerType(LAYER_TYPE_HARDWARE, null);
anims.start();
} else {
stickersExpansionProgress = 0;
setTranslationY(0);
emojiView.setTranslationY(0);
emojiView.getLayoutParams().height = origHeight;
sizeNotifierLayout.requestLayout();
((FrameLayout) sizeNotifierLayout).setForeground(null);
sizeNotifierLayout.setWillNotDraw(false);
stickersArrow.setAnimationProgress(0);
}
}
}
private class ScrimDrawable extends Drawable {
private Paint paint;
public ScrimDrawable() {
paint = new Paint();
paint.setColor(0);
}
@Override
public void draw(Canvas canvas) {
paint.setAlpha(Math.round(102 * stickersExpansionProgress));
canvas.drawRect(0, 0, getWidth(), emojiView.getY() - getHeight() + Theme.chat_composeShadowDrawable.getIntrinsicHeight(), paint);
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
}
@Override
public int getOpacity() {
return 0;
}
}
private class AnimatedArrowDrawable extends Drawable {
private Paint paint;
private Path path = new Path();
private float animProgress = 0;
public AnimatedArrowDrawable(int color) {
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(AndroidUtilities.dp(2));
paint.setColor(color);
updatePath();
}
@Override
public void draw(Canvas c) {
c.drawPath(path, paint);
}
private void updatePath() {
path.reset();
float p = animProgress * 2 - 1;
path.moveTo(AndroidUtilities.dp(3), AndroidUtilities.dp(12) - AndroidUtilities.dp(4) * p);
path.lineTo(AndroidUtilities.dp(13), AndroidUtilities.dp(12) + AndroidUtilities.dp(4) * p);
path.lineTo(AndroidUtilities.dp(23), AndroidUtilities.dp(12) - AndroidUtilities.dp(4) * p);
}
public void setAnimationProgress(float progress) {
animProgress = progress;
updatePath();
invalidateSelf();
}
public float getAnimationProgress() {
return animProgress;
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
}
@Override
public int getOpacity() {
return 0;
}
@Override
public int getIntrinsicWidth() {
return AndroidUtilities.dp(26);
}
@Override
public int getIntrinsicHeight() {
return AndroidUtilities.dp(26);
}
}
}

View File

@ -694,308 +694,306 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N
progressView.showTextView();
}
if (Build.VERSION.SDK_INT >= 16) {
recordTime = new TextView(context);
recordTime.setBackgroundResource(R.drawable.system);
recordTime.getBackground().setColorFilter(new PorterDuffColorFilter(0x66000000, PorterDuff.Mode.MULTIPLY));
recordTime.setText("00:00");
recordTime.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
recordTime.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
recordTime.setAlpha(0.0f);
recordTime.setTextColor(0xffffffff);
recordTime.setPadding(AndroidUtilities.dp(10), AndroidUtilities.dp(5), AndroidUtilities.dp(10), AndroidUtilities.dp(5));
container.addView(recordTime, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 16, 0, 0));
recordTime = new TextView(context);
recordTime.setBackgroundResource(R.drawable.system);
recordTime.getBackground().setColorFilter(new PorterDuffColorFilter(0x66000000, PorterDuff.Mode.MULTIPLY));
recordTime.setText("00:00");
recordTime.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
recordTime.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
recordTime.setAlpha(0.0f);
recordTime.setTextColor(0xffffffff);
recordTime.setPadding(AndroidUtilities.dp(10), AndroidUtilities.dp(5), AndroidUtilities.dp(10), AndroidUtilities.dp(5));
container.addView(recordTime, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 16, 0, 0));
cameraPanel = new FrameLayout(context) {
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
int cx = getMeasuredWidth() / 2;
int cy = getMeasuredHeight() / 2;
int cx2;
int cy2;
shutterButton.layout(cx - shutterButton.getMeasuredWidth() / 2, cy - shutterButton.getMeasuredHeight() / 2, cx + shutterButton.getMeasuredWidth() / 2, cy + shutterButton.getMeasuredHeight() / 2);
if (getMeasuredWidth() == AndroidUtilities.dp(100)) {
cx = cx2 = getMeasuredWidth() / 2;
cy2 = cy + cy / 2 + AndroidUtilities.dp(17);
cy = cy / 2 - AndroidUtilities.dp(17);
} else {
cx2 = cx + cx / 2 + AndroidUtilities.dp(17);
cx = cx / 2 - AndroidUtilities.dp(17);
cy = cy2 = getMeasuredHeight() / 2;
}
switchCameraButton.layout(cx2 - switchCameraButton.getMeasuredWidth() / 2, cy2 - switchCameraButton.getMeasuredHeight() / 2, cx2 + switchCameraButton.getMeasuredWidth() / 2, cy2 + switchCameraButton.getMeasuredHeight() / 2);
for (int a = 0; a < 2; a++) {
flashModeButton[a].layout(cx - flashModeButton[a].getMeasuredWidth() / 2, cy - flashModeButton[a].getMeasuredHeight() / 2, cx + flashModeButton[a].getMeasuredWidth() / 2, cy + flashModeButton[a].getMeasuredHeight() / 2);
}
cameraPanel = new FrameLayout(context) {
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
int cx = getMeasuredWidth() / 2;
int cy = getMeasuredHeight() / 2;
int cx2;
int cy2;
shutterButton.layout(cx - shutterButton.getMeasuredWidth() / 2, cy - shutterButton.getMeasuredHeight() / 2, cx + shutterButton.getMeasuredWidth() / 2, cy + shutterButton.getMeasuredHeight() / 2);
if (getMeasuredWidth() == AndroidUtilities.dp(100)) {
cx = cx2 = getMeasuredWidth() / 2;
cy2 = cy + cy / 2 + AndroidUtilities.dp(17);
cy = cy / 2 - AndroidUtilities.dp(17);
} else {
cx2 = cx + cx / 2 + AndroidUtilities.dp(17);
cx = cx / 2 - AndroidUtilities.dp(17);
cy = cy2 = getMeasuredHeight() / 2;
}
};
cameraPanel.setVisibility(View.GONE);
cameraPanel.setAlpha(0.0f);
container.addView(cameraPanel, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 100, Gravity.LEFT | Gravity.BOTTOM));
switchCameraButton.layout(cx2 - switchCameraButton.getMeasuredWidth() / 2, cy2 - switchCameraButton.getMeasuredHeight() / 2, cx2 + switchCameraButton.getMeasuredWidth() / 2, cy2 + switchCameraButton.getMeasuredHeight() / 2);
for (int a = 0; a < 2; a++) {
flashModeButton[a].layout(cx - flashModeButton[a].getMeasuredWidth() / 2, cy - flashModeButton[a].getMeasuredHeight() / 2, cx + flashModeButton[a].getMeasuredWidth() / 2, cy + flashModeButton[a].getMeasuredHeight() / 2);
}
}
};
cameraPanel.setVisibility(View.GONE);
cameraPanel.setAlpha(0.0f);
container.addView(cameraPanel, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 100, Gravity.LEFT | Gravity.BOTTOM));
shutterButton = new ShutterButton(context);
cameraPanel.addView(shutterButton, LayoutHelper.createFrame(84, 84, Gravity.CENTER));
shutterButton.setDelegate(new ShutterButton.ShutterButtonDelegate() {
@Override
public boolean shutterLongPressed() {
if (mediaCaptured || takingPhoto || baseFragment == null || baseFragment.getParentActivity() == null || cameraView == null) {
shutterButton = new ShutterButton(context);
cameraPanel.addView(shutterButton, LayoutHelper.createFrame(84, 84, Gravity.CENTER));
shutterButton.setDelegate(new ShutterButton.ShutterButtonDelegate() {
@Override
public boolean shutterLongPressed() {
if (mediaCaptured || takingPhoto || baseFragment == null || baseFragment.getParentActivity() == null || cameraView == null) {
return false;
}
if (Build.VERSION.SDK_INT >= 23) {
if (baseFragment.getParentActivity().checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
requestingPermissions = true;
baseFragment.getParentActivity().requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, 21);
return false;
}
if (Build.VERSION.SDK_INT >= 23) {
if (baseFragment.getParentActivity().checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
requestingPermissions = true;
baseFragment.getParentActivity().requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, 21);
return false;
}
}
for (int a = 0; a < 2; a++) {
flashModeButton[a].setAlpha(0.0f);
}
switchCameraButton.setAlpha(0.0f);
cameraFile = AndroidUtilities.generateVideoPath();
recordTime.setAlpha(1.0f);
recordTime.setText("00:00");
videoRecordTime = 0;
videoRecordRunnable = new Runnable() {
@Override
public void run() {
if (videoRecordRunnable == null) {
return;
}
videoRecordTime++;
recordTime.setText(String.format("%02d:%02d", videoRecordTime / 60, videoRecordTime % 60));
AndroidUtilities.runOnUIThread(videoRecordRunnable, 1000);
}
};
AndroidUtilities.lockOrientation(parentFragment.getParentActivity());
CameraController.getInstance().recordVideo(cameraView.getCameraSession(), cameraFile, new CameraController.VideoTakeCallback() {
@Override
public void onFinishVideoRecording(final Bitmap thumb) {
if (cameraFile == null || baseFragment == null) {
return;
}
PhotoViewer.getInstance().setParentActivity(baseFragment.getParentActivity());
PhotoViewer.getInstance().setParentAlert(ChatAttachAlert.this);
cameraPhoto = new ArrayList<>();
cameraPhoto.add(new MediaController.PhotoEntry(0, 0, 0, cameraFile.getAbsolutePath(), 0, true));
PhotoViewer.getInstance().openPhotoForSelect(cameraPhoto, 0, 2, new PhotoViewer.EmptyPhotoViewerProvider() {
@Override
public Bitmap getThumbForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) {
return thumb;
}
@TargetApi(16)
@Override
public boolean cancelButtonPressed() {
if (cameraOpened && cameraView != null && cameraFile != null) {
cameraFile.delete();
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
if (cameraView != null && !isDismissed() && Build.VERSION.SDK_INT >= 21) {
cameraView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_FULLSCREEN);
}
}
}, 1000);
CameraController.getInstance().startPreview(cameraView.getCameraSession());
cameraFile = null;
}
return true;
}
@Override
public void sendButtonPressed(int index, VideoEditedInfo videoEditedInfo) {
if (cameraFile == null || baseFragment == null) {
return;
}
AndroidUtilities.addMediaToGallery(cameraFile.getAbsolutePath());
baseFragment.sendMedia((MediaController.PhotoEntry) cameraPhoto.get(0), videoEditedInfo);
closeCamera(false);
dismiss();
cameraFile = null;
}
@Override
public void willHidePhotoViewer() {
mediaCaptured = false;
}
}, baseFragment);
}
}, new Runnable() {
@Override
public void run() {
AndroidUtilities.runOnUIThread(videoRecordRunnable, 1000);
}
}, false);
shutterButton.setState(ShutterButton.State.RECORDING, true);
return true;
}
@Override
public void shutterCancel() {
if (mediaCaptured) {
return;
}
cameraFile.delete();
resetRecordState();
CameraController.getInstance().stopVideoRecording(cameraView.getCameraSession(), true);
for (int a = 0; a < 2; a++) {
flashModeButton[a].setAlpha(0.0f);
}
@Override
public void shutterReleased() {
if (takingPhoto || cameraView == null || mediaCaptured || cameraView.getCameraSession() == null) {
return;
}
mediaCaptured = true;
if (shutterButton.getState() == ShutterButton.State.RECORDING) {
resetRecordState();
CameraController.getInstance().stopVideoRecording(cameraView.getCameraSession(), false);
shutterButton.setState(ShutterButton.State.DEFAULT, true);
return;
}
cameraFile = AndroidUtilities.generatePicturePath();
final boolean sameTakePictureOrientation = cameraView.getCameraSession().isSameTakePictureOrientation();
takingPhoto = CameraController.getInstance().takePicture(cameraFile, cameraView.getCameraSession(), new Runnable() {
@Override
public void run() {
takingPhoto = false;
if (cameraFile == null || baseFragment == null) {
return;
}
PhotoViewer.getInstance().setParentActivity(baseFragment.getParentActivity());
PhotoViewer.getInstance().setParentAlert(ChatAttachAlert.this);
cameraPhoto = new ArrayList<>();
int orientation = 0;
try {
ExifInterface ei = new ExifInterface(cameraFile.getAbsolutePath());
int exif = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (exif) {
case ExifInterface.ORIENTATION_ROTATE_90:
orientation = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
orientation = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
orientation = 270;
break;
}
} catch (Exception e) {
FileLog.e(e);
}
cameraPhoto.add(new MediaController.PhotoEntry(0, 0, 0, cameraFile.getAbsolutePath(), orientation, false));
PhotoViewer.getInstance().openPhotoForSelect(cameraPhoto, 0, 2, new PhotoViewer.EmptyPhotoViewerProvider() {
@TargetApi(16)
@Override
public boolean cancelButtonPressed() {
if (cameraOpened && cameraView != null && cameraFile != null) {
cameraFile.delete();
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
if (cameraView != null && !isDismissed() && Build.VERSION.SDK_INT >= 21) {
cameraView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_FULLSCREEN);
}
}
}, 1000);
CameraController.getInstance().startPreview(cameraView.getCameraSession());
cameraFile = null;
}
return true;
}
@Override
public void sendButtonPressed(int index, VideoEditedInfo videoEditedInfo) {
if (cameraFile == null || baseFragment == null) {
return;
}
AndroidUtilities.addMediaToGallery(cameraFile.getAbsolutePath());
baseFragment.sendMedia((MediaController.PhotoEntry) cameraPhoto.get(0), null);
closeCamera(false);
dismiss();
cameraFile = null;
}
@Override
public boolean scaleToFill() {
if (baseFragment == null || baseFragment.getParentActivity() == null) {
return false;
}
int locked = Settings.System.getInt(baseFragment.getParentActivity().getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
return sameTakePictureOrientation || locked == 1;
}
@Override
public void willHidePhotoViewer() {
mediaCaptured = false;
}
}, baseFragment);
}
});
}
});
switchCameraButton = new ImageView(context);
switchCameraButton.setScaleType(ImageView.ScaleType.CENTER);
cameraPanel.addView(switchCameraButton, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.CENTER_VERTICAL));
switchCameraButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (takingPhoto || cameraView == null || !cameraView.isInitied()) {
return;
}
cameraInitied = false;
cameraView.switchCamera();
ObjectAnimator animator = ObjectAnimator.ofFloat(switchCameraButton, "scaleX", 0.0f).setDuration(100);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animator) {
switchCameraButton.setImageResource(cameraView.isFrontface() ? R.drawable.camera_revert1 : R.drawable.camera_revert2);
ObjectAnimator.ofFloat(switchCameraButton, "scaleX", 1.0f).setDuration(100).start();
}
});
animator.start();
}
});
for (int a = 0; a < 2; a++) {
flashModeButton[a] = new ImageView(context);
flashModeButton[a].setScaleType(ImageView.ScaleType.CENTER);
flashModeButton[a].setVisibility(View.INVISIBLE);
cameraPanel.addView(flashModeButton[a], LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP));
flashModeButton[a].setOnClickListener(new View.OnClickListener() {
switchCameraButton.setAlpha(0.0f);
cameraFile = AndroidUtilities.generateVideoPath();
recordTime.setAlpha(1.0f);
recordTime.setText("00:00");
videoRecordTime = 0;
videoRecordRunnable = new Runnable() {
@Override
public void onClick(final View currentImage) {
if (flashAnimationInProgress || cameraView == null || !cameraView.isInitied() || !cameraOpened) {
public void run() {
if (videoRecordRunnable == null) {
return;
}
String current = cameraView.getCameraSession().getCurrentFlashMode();
String next = cameraView.getCameraSession().getNextFlashMode();
if (current.equals(next)) {
videoRecordTime++;
recordTime.setText(String.format("%02d:%02d", videoRecordTime / 60, videoRecordTime % 60));
AndroidUtilities.runOnUIThread(videoRecordRunnable, 1000);
}
};
AndroidUtilities.lockOrientation(parentFragment.getParentActivity());
CameraController.getInstance().recordVideo(cameraView.getCameraSession(), cameraFile, new CameraController.VideoTakeCallback() {
@Override
public void onFinishVideoRecording(final Bitmap thumb) {
if (cameraFile == null || baseFragment == null) {
return;
}
cameraView.getCameraSession().setCurrentFlashMode(next);
flashAnimationInProgress = true;
ImageView nextImage = flashModeButton[0] == currentImage ? flashModeButton[1] : flashModeButton[0];
nextImage.setVisibility(View.VISIBLE);
setCameraFlashModeIcon(nextImage, next);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(
ObjectAnimator.ofFloat(currentImage, "translationY", 0, AndroidUtilities.dp(48)),
ObjectAnimator.ofFloat(nextImage, "translationY", -AndroidUtilities.dp(48), 0),
ObjectAnimator.ofFloat(currentImage, "alpha", 1.0f, 0.0f),
ObjectAnimator.ofFloat(nextImage, "alpha", 0.0f, 1.0f));
animatorSet.setDuration(200);
animatorSet.addListener(new AnimatorListenerAdapter() {
PhotoViewer.getInstance().setParentActivity(baseFragment.getParentActivity());
PhotoViewer.getInstance().setParentAlert(ChatAttachAlert.this);
cameraPhoto = new ArrayList<>();
cameraPhoto.add(new MediaController.PhotoEntry(0, 0, 0, cameraFile.getAbsolutePath(), 0, true));
PhotoViewer.getInstance().openPhotoForSelect(cameraPhoto, 0, 2, new PhotoViewer.EmptyPhotoViewerProvider() {
@Override
public void onAnimationEnd(Animator animator) {
flashAnimationInProgress = false;
currentImage.setVisibility(View.INVISIBLE);
public Bitmap getThumbForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) {
return thumb;
}
});
animatorSet.start();
@TargetApi(16)
@Override
public boolean cancelButtonPressed() {
if (cameraOpened && cameraView != null && cameraFile != null) {
cameraFile.delete();
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
if (cameraView != null && !isDismissed() && Build.VERSION.SDK_INT >= 21) {
cameraView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_FULLSCREEN);
}
}
}, 1000);
CameraController.getInstance().startPreview(cameraView.getCameraSession());
cameraFile = null;
}
return true;
}
@Override
public void sendButtonPressed(int index, VideoEditedInfo videoEditedInfo) {
if (cameraFile == null || baseFragment == null) {
return;
}
AndroidUtilities.addMediaToGallery(cameraFile.getAbsolutePath());
baseFragment.sendMedia((MediaController.PhotoEntry) cameraPhoto.get(0), videoEditedInfo);
closeCamera(false);
dismiss();
cameraFile = null;
}
@Override
public void willHidePhotoViewer() {
mediaCaptured = false;
}
}, baseFragment);
}
}, new Runnable() {
@Override
public void run() {
AndroidUtilities.runOnUIThread(videoRecordRunnable, 1000);
}
}, false);
shutterButton.setState(ShutterButton.State.RECORDING, true);
return true;
}
@Override
public void shutterCancel() {
if (mediaCaptured) {
return;
}
cameraFile.delete();
resetRecordState();
CameraController.getInstance().stopVideoRecording(cameraView.getCameraSession(), true);
}
@Override
public void shutterReleased() {
if (takingPhoto || cameraView == null || mediaCaptured || cameraView.getCameraSession() == null) {
return;
}
mediaCaptured = true;
if (shutterButton.getState() == ShutterButton.State.RECORDING) {
resetRecordState();
CameraController.getInstance().stopVideoRecording(cameraView.getCameraSession(), false);
shutterButton.setState(ShutterButton.State.DEFAULT, true);
return;
}
cameraFile = AndroidUtilities.generatePicturePath();
final boolean sameTakePictureOrientation = cameraView.getCameraSession().isSameTakePictureOrientation();
takingPhoto = CameraController.getInstance().takePicture(cameraFile, cameraView.getCameraSession(), new Runnable() {
@Override
public void run() {
takingPhoto = false;
if (cameraFile == null || baseFragment == null) {
return;
}
PhotoViewer.getInstance().setParentActivity(baseFragment.getParentActivity());
PhotoViewer.getInstance().setParentAlert(ChatAttachAlert.this);
cameraPhoto = new ArrayList<>();
int orientation = 0;
try {
ExifInterface ei = new ExifInterface(cameraFile.getAbsolutePath());
int exif = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (exif) {
case ExifInterface.ORIENTATION_ROTATE_90:
orientation = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
orientation = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
orientation = 270;
break;
}
} catch (Exception e) {
FileLog.e(e);
}
cameraPhoto.add(new MediaController.PhotoEntry(0, 0, 0, cameraFile.getAbsolutePath(), orientation, false));
PhotoViewer.getInstance().openPhotoForSelect(cameraPhoto, 0, 2, new PhotoViewer.EmptyPhotoViewerProvider() {
@TargetApi(16)
@Override
public boolean cancelButtonPressed() {
if (cameraOpened && cameraView != null && cameraFile != null) {
cameraFile.delete();
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
if (cameraView != null && !isDismissed() && Build.VERSION.SDK_INT >= 21) {
cameraView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_FULLSCREEN);
}
}
}, 1000);
CameraController.getInstance().startPreview(cameraView.getCameraSession());
cameraFile = null;
}
return true;
}
@Override
public void sendButtonPressed(int index, VideoEditedInfo videoEditedInfo) {
if (cameraFile == null || baseFragment == null) {
return;
}
AndroidUtilities.addMediaToGallery(cameraFile.getAbsolutePath());
baseFragment.sendMedia((MediaController.PhotoEntry) cameraPhoto.get(0), null);
closeCamera(false);
dismiss();
cameraFile = null;
}
@Override
public boolean scaleToFill() {
if (baseFragment == null || baseFragment.getParentActivity() == null) {
return false;
}
int locked = Settings.System.getInt(baseFragment.getParentActivity().getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
return sameTakePictureOrientation || locked == 1;
}
@Override
public void willHidePhotoViewer() {
mediaCaptured = false;
}
}, baseFragment);
}
});
}
});
switchCameraButton = new ImageView(context);
switchCameraButton.setScaleType(ImageView.ScaleType.CENTER);
cameraPanel.addView(switchCameraButton, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.CENTER_VERTICAL));
switchCameraButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (takingPhoto || cameraView == null || !cameraView.isInitied()) {
return;
}
cameraInitied = false;
cameraView.switchCamera();
ObjectAnimator animator = ObjectAnimator.ofFloat(switchCameraButton, "scaleX", 0.0f).setDuration(100);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animator) {
switchCameraButton.setImageResource(cameraView.isFrontface() ? R.drawable.camera_revert1 : R.drawable.camera_revert2);
ObjectAnimator.ofFloat(switchCameraButton, "scaleX", 1.0f).setDuration(100).start();
}
});
animator.start();
}
});
for (int a = 0; a < 2; a++) {
flashModeButton[a] = new ImageView(context);
flashModeButton[a].setScaleType(ImageView.ScaleType.CENTER);
flashModeButton[a].setVisibility(View.INVISIBLE);
cameraPanel.addView(flashModeButton[a], LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP));
flashModeButton[a].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View currentImage) {
if (flashAnimationInProgress || cameraView == null || !cameraView.isInitied() || !cameraOpened) {
return;
}
String current = cameraView.getCameraSession().getCurrentFlashMode();
String next = cameraView.getCameraSession().getNextFlashMode();
if (current.equals(next)) {
return;
}
cameraView.getCameraSession().setCurrentFlashMode(next);
flashAnimationInProgress = true;
ImageView nextImage = flashModeButton[0] == currentImage ? flashModeButton[1] : flashModeButton[0];
nextImage.setVisibility(View.VISIBLE);
setCameraFlashModeIcon(nextImage, next);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(
ObjectAnimator.ofFloat(currentImage, "translationY", 0, AndroidUtilities.dp(48)),
ObjectAnimator.ofFloat(nextImage, "translationY", -AndroidUtilities.dp(48), 0),
ObjectAnimator.ofFloat(currentImage, "alpha", 1.0f, 0.0f),
ObjectAnimator.ofFloat(nextImage, "alpha", 0.0f, 1.0f));
animatorSet.setDuration(200);
animatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animator) {
flashAnimationInProgress = false;
currentImage.setVisibility(View.INVISIBLE);
}
});
animatorSet.start();
}
});
}
}
@ -1666,10 +1664,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N
if (MediaController.allMediaAlbumEntry != null) {
for (int a = 0; a < Math.min(100, MediaController.allMediaAlbumEntry.photos.size()); a++) {
MediaController.PhotoEntry photoEntry = MediaController.allMediaAlbumEntry.photos.get(a);
photoEntry.caption = null;
photoEntry.imagePath = null;
photoEntry.thumbPath = null;
photoEntry.stickers.clear();
photoEntry.reset();
}
}
if (currentHintAnimation != null) {
@ -1876,7 +1871,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N
CameraController.getInstance().initCamera();
deviceHasGoodCamera = CameraController.getInstance().isCameraInitied();
}
} else if (Build.VERSION.SDK_INT >= 16) {
} else {
CameraController.getInstance().initCamera();
deviceHasGoodCamera = CameraController.getInstance().isCameraInitied();
}
@ -2008,11 +2003,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N
if (!selectedPhotos.isEmpty()) {
for (HashMap.Entry<Integer, MediaController.PhotoEntry> entry : selectedPhotos.entrySet()) {
MediaController.PhotoEntry photoEntry = entry.getValue();
photoEntry.imagePath = null;
photoEntry.thumbPath = null;
photoEntry.caption = null;
photoEntry.editedInfo = null;
photoEntry.stickers.clear();
photoEntry.reset();
}
selectedPhotos.clear();
updatePhotosButton();
@ -2032,9 +2023,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N
if (selectedPhotos.containsKey(photoEntry.imageId)) {
selectedPhotos.remove(photoEntry.imageId);
v.setChecked(false, true);
photoEntry.imagePath = null;
photoEntry.thumbPath = null;
photoEntry.stickers.clear();
photoEntry.reset();
v.setPhotoEntry(photoEntry, (Integer) v.getTag() == MediaController.allMediaAlbumEntry.photos.size() - 1);
} else {
selectedPhotos.put(photoEntry.imageId, photoEntry);

View File

@ -36,6 +36,7 @@ public class CheckBox extends View {
private Canvas checkCanvas;
private boolean drawBackground;
private boolean hasBorder;
private float progress;
private ObjectAnimator checkAnimator;
@ -94,6 +95,10 @@ public class CheckBox extends View {
drawBackground = value;
}
public void setHasBorder(boolean value) {
hasBorder = value;
}
public void setCheckOffset(int value) {
checkOffset = value;
}
@ -198,6 +203,9 @@ public class CheckBox extends View {
paint.setColor(color);
if (hasBorder) {
rad -= AndroidUtilities.dp(2);
}
bitmapCanvas.drawCircle(getMeasuredWidth() / 2, getMeasuredHeight() / 2, rad, paint);
bitmapCanvas.drawCircle(getMeasuredWidth() / 2, getMeasuredHeight() / 2, rad * (1 - roundProgress), eraser);
canvas.drawBitmap(drawBitmap, 0, 0, null);

View File

@ -4,6 +4,8 @@ import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.RectF;
import android.view.Gravity;
import android.view.MotionEvent;
@ -125,7 +127,7 @@ public class CropRotationWheel extends FrameLayout {
}
public void setAspectLock(boolean enabled) {
aspectRatioButton.setImageResource(enabled ? R.drawable.tool_cropfix_active : R.drawable.tool_cropfix);
aspectRatioButton.setColorFilter(enabled ? new PorterDuffColorFilter(0xff51bdf3, PorterDuff.Mode.MULTIPLY) : null);
}
@Override

View File

@ -5,10 +5,11 @@ import android.view.animation.Interpolator;
public class CubicBezierInterpolator implements Interpolator {
public static final CubicBezierInterpolator DEFAULT=new CubicBezierInterpolator(0.25, 0.1, 0.25, 1);
public static final CubicBezierInterpolator EASE_OUT=new CubicBezierInterpolator(0, 0, .58, 1);
public static final CubicBezierInterpolator EASE_IN=new CubicBezierInterpolator(.42, 0, 1, 1);
public static final CubicBezierInterpolator EASE_BOTH=new CubicBezierInterpolator(.42, 0, .58, 1);
public static final CubicBezierInterpolator DEFAULT = new CubicBezierInterpolator(0.25, 0.1, 0.25, 1);
public static final CubicBezierInterpolator EASE_OUT = new CubicBezierInterpolator(0, 0, .58, 1);
public static final CubicBezierInterpolator EASE_OUT_QUINT = new CubicBezierInterpolator(.23, 1, .32, 1);
public static final CubicBezierInterpolator EASE_IN = new CubicBezierInterpolator(.42, 0, 1, 1);
public static final CubicBezierInterpolator EASE_BOTH = new CubicBezierInterpolator(.42, 0, .58, 1);
protected PointF start;
protected PointF end;

View File

@ -33,7 +33,9 @@ import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.view.ViewTreeObserver;
@ -89,6 +91,13 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
void onStickerSetRemove(TLRPC.StickerSetCovered stickerSet);
}
public interface DragListener{
void onDragStart();
void onDragEnd(float velocity);
void onDragCancel();
void onDrag(int offset);
}
private StickerPreviewViewer.StickerPreviewViewerDelegate stickerPreviewViewerDelegate = new StickerPreviewViewer.StickerPreviewViewerDelegate() {
@Override
public void sentSticker(TLRPC.Document sticker) {
@ -582,6 +591,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
private RecyclerListView.OnItemClickListener stickersOnItemClickListener;
private PagerSlidingTabStrip pagerSlidingTabStrip;
private TextView mediaBanTooltip;
private DragListener dragListener;
private int currentChatId;
@ -873,12 +883,34 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
float lastX;
float lastTranslateX;
boolean first = true;
final int touchslop=ViewConfiguration.get(getContext()).getScaledTouchSlop();
float downX, downY;
boolean draggingVertically, draggingHorizontally;
VelocityTracker vTracker;
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (getParent() != null) {
getParent().requestDisallowInterceptTouchEvent(true);
}
if(ev.getAction()==MotionEvent.ACTION_DOWN){
draggingVertically=draggingHorizontally=false;
downX=ev.getRawX();
downY=ev.getRawY();
}else{
if(!draggingVertically && !draggingHorizontally && dragListener!=null){
if(Math.abs(ev.getRawY()-downY)>=touchslop){
draggingVertically=true;
downY=ev.getRawY();
dragListener.onDragStart();
if(startedScroll){
pager.endFakeDrag();
startedScroll=false;
}
return true;
}
}
}
return super.onInterceptTouchEvent(ev);
}
@ -888,6 +920,46 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
first = false;
lastX = ev.getX();
}
if(ev.getAction()==MotionEvent.ACTION_DOWN){
draggingVertically=draggingHorizontally=false;
downX=ev.getRawX();
downY=ev.getRawY();
}else{
if(!draggingVertically && !draggingHorizontally && dragListener!=null){
if(Math.abs(ev.getRawX()-downX)>=touchslop){
draggingHorizontally=true;
}else if(Math.abs(ev.getRawY()-downY)>=touchslop){
draggingVertically=true;
downY=ev.getRawY();
dragListener.onDragStart();
if(startedScroll){
pager.endFakeDrag();
startedScroll=false;
}
}
}
}
if(draggingVertically){
if(vTracker==null)
vTracker=VelocityTracker.obtain();
vTracker.addMovement(ev);
if(ev.getAction()==MotionEvent.ACTION_UP || ev.getAction()==MotionEvent.ACTION_CANCEL){
vTracker.computeCurrentVelocity(1000);
float velocity=vTracker.getYVelocity();
vTracker.recycle();
vTracker=null;
if(ev.getAction()==MotionEvent.ACTION_UP){
dragListener.onDragEnd(velocity);
}else{
dragListener.onDragCancel();
}
first=true;
draggingVertically=draggingHorizontally=false;
}else{
dragListener.onDrag(Math.round(ev.getRawY()-downY));
}
return true;
}
float newTranslationX = stickersTab.getTranslationX();
if (stickersTab.getScrollX() == 0 && newTranslationX == 0) {
if (!startedScroll && lastX - ev.getX() < 0) {
@ -920,6 +992,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
lastX = ev.getX();
if (ev.getAction() == MotionEvent.ACTION_CANCEL || ev.getAction() == MotionEvent.ACTION_UP) {
first = true;
draggingVertically=draggingHorizontally=false;
if (startedScroll) {
pager.endFakeDrag();
startedScroll = false;
@ -1618,6 +1691,10 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
listener = value;
}
public void setDragListener(DragListener dragListener){
this.dragListener=dragListener;
}
public void invalidateViews() {
for (int a = 0; a < emojiGrids.size(); a++) {
emojiGrids.get(a).invalidateViews();
@ -1851,6 +1928,10 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
}
}
public boolean areThereAnyStickers(){
return stickersGridAdapter!=null && stickersGridAdapter.getItemCount()>0;
}
@SuppressWarnings("unchecked")
@Override
public void didReceivedNotification(int id, Object... args) {

View File

@ -80,7 +80,7 @@ public class GroupCreateSpan extends View {
if (user.photo != null) {
photo = user.photo.photo_small;
}
imageReceiver.setImage(photo, null, "50_50", avatarDrawable, null, null, 0, null, true);
imageReceiver.setImage(photo, null, "50_50", avatarDrawable, null, null, 0, null, 1);
updateColors();
}

View File

@ -177,6 +177,15 @@ public class NumberPicker extends LinearLayout {
updateInputTextView();
}
public void setTextColor(int color) {
mInputText.setTextColor(color);
mSelectorWheelPaint.setColor(color);
}
public void setSelectorColor(int color) {
mSelectionDivider.setColor(color);
}
public NumberPicker(Context context) {
super(context);
init();

View File

@ -13,7 +13,6 @@ import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
@ -104,11 +103,7 @@ public class PagerSlidingTabStrip extends HorizontalScrollView {
getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < 16) {
getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
getViewTreeObserver().removeOnGlobalLayoutListener(this);
currentPosition = pager.getCurrentItem();
scrollToChild(currentPosition, 0);
}

View File

@ -30,6 +30,7 @@ public class ColorPicker extends FrameLayout {
void onColorValueChanged();
void onFinishedColorPicking();
void onSettingsPressed();
void onUndoPressed();
}
private ColorPickerDelegate delegate;
@ -63,6 +64,7 @@ public class ColorPicker extends FrameLayout {
};
private ImageView settingsButton;
private ImageView undoButton;
private Drawable shadowDrawable;
private Paint gradientPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
@ -97,10 +99,28 @@ public class ColorPicker extends FrameLayout {
}
});
undoButton = new ImageView(context);
undoButton.setScaleType(ImageView.ScaleType.CENTER);
undoButton.setImageResource(R.drawable.photo_undo);
addView(undoButton, LayoutHelper.createFrame(60, 52));
undoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (delegate != null) {
delegate.onUndoPressed();
}
}
});
location = context.getSharedPreferences("paint", Activity.MODE_PRIVATE).getFloat("last_color_location", 1.0f);
setLocation(location);
}
public void setUndoEnabled(boolean enabled) {
undoButton.setAlpha(enabled ? 1.0f : 0.3f);
undoButton.setEnabled(enabled);
}
public void setDelegate(ColorPickerDelegate colorPickerDelegate) {
delegate = colorPickerDelegate;
}
@ -202,7 +222,7 @@ public class ColorPicker extends FrameLayout {
float x = event.getX() - rectF.left;
float y = event.getY() - rectF.top;
if (!interacting && x < -AndroidUtilities.dp(10)) {
if (!interacting && y < -AndroidUtilities.dp(10)) {
return false;
}
@ -225,14 +245,14 @@ public class ColorPicker extends FrameLayout {
}
}
float colorLocation = Math.max(0.0f, Math.min(1.0f, y / rectF.height()));
float colorLocation = Math.max(0.0f, Math.min(1.0f, x / rectF.width()));
setLocation(colorLocation);
setDragging(true, true);
if (x < -AndroidUtilities.dp(10)) {
if (y < -AndroidUtilities.dp(10)) {
changingWeight = true;
float weightLocation = (-x - AndroidUtilities.dp(10)) / AndroidUtilities.dp(190);
float weightLocation = (-y - AndroidUtilities.dp(10)) / AndroidUtilities.dp(190);
weightLocation = Math.max(0.0f, Math.min(1.0f, weightLocation));
setWeight(weightLocation);
}
@ -251,21 +271,20 @@ public class ColorPicker extends FrameLayout {
int width = right - left;
int height = bottom - top;
int backHeight = getMeasuredHeight() - AndroidUtilities.dp(26) - AndroidUtilities.dp(64);
gradientPaint.setShader(new LinearGradient(0, AndroidUtilities.dp(26), 0, backHeight + AndroidUtilities.dp(26), COLORS, LOCATIONS, Shader.TileMode.REPEAT));
int x = width - AndroidUtilities.dp(26) - AndroidUtilities.dp(8);
int y = AndroidUtilities.dp(26);
rectF.set(x, y, x + AndroidUtilities.dp(8), y + backHeight);
gradientPaint.setShader(new LinearGradient(AndroidUtilities.dp(56), 0, width - AndroidUtilities.dp(56), 0, COLORS, LOCATIONS, Shader.TileMode.REPEAT));
int y = height - AndroidUtilities.dp(32);
rectF.set(AndroidUtilities.dp(56), y, width - AndroidUtilities.dp(56), y + AndroidUtilities.dp(12));
settingsButton.layout(width - settingsButton.getMeasuredWidth(), height - AndroidUtilities.dp(52), width, height);
undoButton.layout(0, height - AndroidUtilities.dp(52), settingsButton.getMeasuredWidth(), height);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawRoundRect(rectF, AndroidUtilities.dp(6), AndroidUtilities.dp(6), gradientPaint);
int cx = (int) (rectF.centerX() + draggingFactor * -AndroidUtilities.dp(70) - (changingWeight ? weight * AndroidUtilities.dp(190) : 0.0f));
int cy = (int) (rectF.top - AndroidUtilities.dp(22) + rectF.height() * location) + AndroidUtilities.dp(22);
int cx = (int) (rectF.left + rectF.width() * location);
int cy = (int) (rectF.centerY() + draggingFactor * -AndroidUtilities.dp(70) - (changingWeight ? weight * AndroidUtilities.dp(190) : 0.0f));
int side = (int) (AndroidUtilities.dp(24) * (0.5f * (1 + draggingFactor)));
shadowDrawable.setBounds(cx - side, cy - side, cx + side, cy + side);

View File

@ -21,8 +21,6 @@ public class EntityView extends FrameLayout {
boolean onEntitySelected(EntityView entityView);
boolean onEntityLongClicked(EntityView entityView);
boolean allowInteraction(EntityView entityView);
void onBeganEntityDragging(EntityView entityView);
void onFinishedEntityDragging(EntityView entityView);
}
private float previousLocationX;
@ -31,7 +29,6 @@ public class EntityView extends FrameLayout {
private boolean hasReleased = false;
private boolean hasTransformed = false;
private boolean announcedSelection = false;
private boolean announcedDragging = false;
private boolean recognizedLongPress = false;
private EntityViewDelegate delegate;
@ -112,12 +109,6 @@ public class EntityView extends FrameLayout {
pan(translation);
previousLocationX = x;
previousLocationY = y;
if (!announcedDragging) {
announcedDragging = true;
if (delegate != null) {
delegate.onBeganEntityDragging(this);
}
}
hasPanned = true;
return true;
}
@ -128,15 +119,11 @@ public class EntityView extends FrameLayout {
if (!recognizedLongPress && !hasPanned && !hasTransformed && !announcedSelection && delegate != null) {
delegate.onEntitySelected(this);
}
if (announcedDragging && delegate != null) {
delegate.onFinishedEntityDragging(this);
}
recognizedLongPress = false;
hasPanned = false;
hasTransformed = false;
hasReleased = true;
announcedSelection = false;
announcedDragging = false;
}
@Override
@ -347,12 +334,6 @@ public class EntityView extends FrameLayout {
previousLocationX = event.getRawX();
previousLocationY = event.getRawY();
if (!announcedDragging) {
announcedDragging = true;
if (delegate != null) {
delegate.onBeganEntityDragging(EntityView.this);
}
}
handled = true;
}
}

View File

@ -65,7 +65,7 @@ public class StickerView extends EntityView {
centerImage.setAspectFit(true);
centerImage.setInvalidateAll(true);
centerImage.setParentView(containerView);
centerImage.setImage(sticker, null, sticker.thumb.location, null, "webp", true);
centerImage.setImage(sticker, null, sticker.thumb.location, null, "webp", 1);
updatePosition();
}

View File

@ -29,14 +29,14 @@ public class PhotoEditorSeekBar extends View {
private PhotoEditorSeekBarDelegate delegate;
public interface PhotoEditorSeekBarDelegate {
void onProgressChanged();
void onProgressChanged(int i, int progress);
}
public PhotoEditorSeekBar(Context context) {
super(context);
innerPaint.setColor(0x99383838);
outerPaint.setColor(0xff53aeef);
innerPaint.setColor(0xff4d4d4d);
outerPaint.setColor(0xffffffff);
}
public void setDelegate(PhotoEditorSeekBarDelegate delegate) {
@ -76,7 +76,7 @@ public class PhotoEditorSeekBar extends View {
}
progress = thumbX / (getMeasuredWidth() - thumbSize);
if (delegate != null) {
delegate.onProgressChanged();
delegate.onProgressChanged((Integer) getTag(), getProgress());
}
invalidate();
return true;
@ -98,7 +98,7 @@ public class PhotoEditorSeekBar extends View {
this.progress = (progress - minValue) / (float) (maxValue - minValue);
invalidate();
if (notify && delegate != null) {
delegate.onProgressChanged();
delegate.onProgressChanged((Integer) getTag(), getProgress());
}
}

View File

@ -38,11 +38,8 @@ import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;
import org.telegram.messenger.query.StickersQuery;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.ActionBar;
import org.telegram.ui.ActionBar.ActionBarMenu;
import org.telegram.ui.ActionBar.ActionBarMenuItem;
import org.telegram.ui.ActionBar.ActionBarPopupWindow;
import org.telegram.ui.ActionBar.AlertDialog;
import org.telegram.ui.ActionBar.Theme;
@ -90,10 +87,6 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
private ImageView paintButton;
private ActionBar actionBar;
private ActionBarMenuItem undoItem;
private ActionBarMenuItem doneItem;
private EntityView currentEntityView;
private boolean editingText;
@ -119,7 +112,6 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
private ArrayList<PhotoFace> faces;
private final static int gallery_menu_done = 1;
private final static int gallery_menu_undo = 2;
public PhotoPaintView(Context context, Bitmap bitmap, int rotation) {
super(context);
@ -132,7 +124,7 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
undoStore.setDelegate(new UndoStore.UndoStoreDelegate() {
@Override
public void historyChanged() {
setMenuItemEnabled(undoStore.canUndo());
colorPicker.setUndoEnabled(undoStore.canUndo());
}
});
@ -146,7 +138,6 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
@Override
public void onBeganDrawing() {
setColorPickerVisibilityFade(false);
if (currentEntityView != null) {
selectEntity(null);
}
@ -154,10 +145,7 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
@Override
public void onFinishedDrawing(boolean moved) {
if (moved) {
setColorPickerVisibilityFade(true);
}
setMenuItemEnabled(undoStore.canUndo());
colorPicker.setUndoEnabled(undoStore.canUndo());
}
@Override
@ -256,6 +244,11 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
showBrushSettings();
}
}
@Override
public void onUndoPressed() {
undoStore.undo();
}
});
toolsView = new FrameLayout(context);
@ -282,23 +275,11 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
doneTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
toolsView.addView(doneTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.RIGHT));
ImageView stickerButton = new ImageView(context);
stickerButton.setScaleType(ImageView.ScaleType.CENTER);
stickerButton.setImageResource(R.drawable.photo_sticker);
stickerButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
toolsView.addView(stickerButton, LayoutHelper.createFrame(54, LayoutHelper.MATCH_PARENT, Gravity.CENTER, 0, 0, 56, 0));
stickerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openStickersView();
}
});
paintButton = new ImageView(context);
paintButton.setScaleType(ImageView.ScaleType.CENTER);
paintButton.setImageResource(R.drawable.photo_paint);
paintButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
toolsView.addView(paintButton, LayoutHelper.createFrame(54, LayoutHelper.MATCH_PARENT, Gravity.CENTER));
toolsView.addView(paintButton, LayoutHelper.createFrame(54, LayoutHelper.MATCH_PARENT, Gravity.CENTER, 0, 0, 56, 0));
paintButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
@ -306,6 +287,18 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
}
});
ImageView stickerButton = new ImageView(context);
stickerButton.setScaleType(ImageView.ScaleType.CENTER);
stickerButton.setImageResource(R.drawable.photo_sticker);
stickerButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
toolsView.addView(stickerButton, LayoutHelper.createFrame(54, LayoutHelper.MATCH_PARENT, Gravity.CENTER));
stickerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openStickersView();
}
});
ImageView textButton = new ImageView(context);
textButton.setScaleType(ImageView.ScaleType.CENTER);
textButton.setImageResource(R.drawable.photo_paint_text);
@ -318,57 +311,22 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
}
});
actionBar = new ActionBar(context);
actionBar.setBackgroundColor(Theme.ACTION_BAR_PHOTO_VIEWER_COLOR);
actionBar.setOccupyStatusBar(Build.VERSION.SDK_INT >= 21);
actionBar.setTitleColor(0xffffffff);
actionBar.setItemsBackgroundColor(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR, false);
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setTitle(LocaleController.getString("PaintDraw", R.string.PaintDraw));
addView(actionBar, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
@Override
public void onItemClick(int id) {
if (id == -1) {
cancelTextView.callOnClick();
} else if (id == gallery_menu_done) {
closeTextEnter(true);
} else if (id == gallery_menu_undo) {
undoStore.undo();
}
}
@Override
public boolean canOpenMenu() {
return false;
}
});
ActionBarMenu menu = actionBar.createMenu();
undoItem = menu.addItem(gallery_menu_undo, R.drawable.photo_undo, AndroidUtilities.dp(56));
setMenuItemEnabled(false);
doneItem = menu.addItemWithWidth(gallery_menu_done, R.drawable.ic_done, AndroidUtilities.dp(56));
doneItem.setVisibility(GONE);
colorPicker.setUndoEnabled(false);
setCurrentSwatch(colorPicker.getSwatch(), false);
updateSettingsButton();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getY() > actionBar.getHeight()) {
if (currentEntityView != null) {
if (editingText) {
closeTextEnter(true);
}
else {
selectEntity(null);
}
if (currentEntityView != null) {
if (editingText) {
closeTextEnter(true);
}
else {
selectEntity(null);
}
return true;
}
return false;
return true;
}
private Size getPaintingSize() {
@ -402,8 +360,10 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
resource = R.drawable.photo_outline;
}
paintButton.setImageResource(R.drawable.photo_paint);
paintButton.setColorFilter(null);
} else {
paintButton.setImageResource(R.drawable.photo_paint2);
paintButton.setColorFilter(new PorterDuffColorFilter(0xff51bdf3, PorterDuff.Mode.MULTIPLY));
paintButton.setImageResource(R.drawable.photo_paint);
}
colorPicker.setSettingsButtonImage(resource);
@ -430,19 +390,10 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
});
}
private void setMenuItemEnabled(boolean enabled) {
undoItem.setAlpha(enabled ? 1.0f : 0.3f);
undoItem.setEnabled(enabled);
}
public FrameLayout getToolsView() {
return toolsView;
}
public ActionBar getActionBar() {
return actionBar;
}
public TextView getDoneTextView() {
return doneTextView;
}
@ -538,35 +489,6 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
}
}
private void setColorPickerVisibilitySlide(boolean visible) {
Animator animator = ObjectAnimator.ofFloat(colorPicker, "translationX", visible ? AndroidUtilities.dp(60) : 0, visible ? 0 : AndroidUtilities.dp(60));
animator.setDuration(200);
animator.start();
}
private void setColorPickerVisibilityFade(boolean visible) {
if (visible) {
colorPickerAnimator = ObjectAnimator.ofFloat(colorPicker, "alpha", colorPicker.getAlpha(), 1.0f);
colorPickerAnimator.setStartDelay(200);
colorPickerAnimator.setDuration(200);
colorPickerAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (colorPickerAnimator != null) {
colorPickerAnimator = null;
}
}
});
colorPickerAnimator.start();
} else {
if (colorPickerAnimator != null) {
colorPickerAnimator.cancel();
colorPickerAnimator = null;
}
colorPicker.setAlpha(0.0f);
}
}
private void setDimVisibility(final boolean visible) {
Animator animator;
if (visible) {
@ -627,7 +549,6 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
int height = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width, height);
actionBar.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST));
float bitmapW;
float bitmapH;
@ -655,7 +576,7 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
colorPicker.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.EXACTLY));
toolsView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(48), MeasureSpec.EXACTLY));
if (stickersView != null) {
stickersView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(fullHeight, MeasureSpec.EXACTLY));
stickersView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(AndroidUtilities.displaySize.y, MeasureSpec.EXACTLY));
}
}
@ -664,9 +585,9 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
int width = right - left;
int height = bottom - top;
int status = (Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0);
int actionBarHeight = ActionBar.getCurrentActionBarHeight();
int actionBarHeight2 = actionBar.getMeasuredHeight();
actionBar.layout(0, 0, actionBar.getMeasuredWidth(), actionBarHeight2);
int actionBarHeight2 = ActionBar.getCurrentActionBarHeight() + status;
float bitmapW;
float bitmapH;
@ -687,7 +608,7 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
}
int x = (int) Math.ceil((width - renderView.getMeasuredWidth()) / 2);
int y = actionBarHeight2 + (height - actionBarHeight2 - AndroidUtilities.dp(48) - renderView.getMeasuredHeight()) / 2;
int y = actionBarHeight2 + (height - actionBarHeight2 - AndroidUtilities.dp(48) - renderView.getMeasuredHeight()) / 2 - ActionBar.getCurrentActionBarHeight() + AndroidUtilities.dp(8);
renderView.layout(x, y, x + renderView.getMeasuredWidth(), y + renderView.getMeasuredHeight());
@ -695,17 +616,17 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
entitiesView.setScaleX(scale);
entitiesView.setScaleY(scale);
entitiesView.layout(x, y, x + entitiesView.getMeasuredWidth(), y + entitiesView.getMeasuredHeight());
dimView.layout(0, actionBarHeight2, dimView.getMeasuredWidth(), actionBarHeight2 + dimView.getMeasuredHeight());
selectionContainerView.layout(0, actionBarHeight2, selectionContainerView.getMeasuredWidth(), actionBarHeight2 + selectionContainerView.getMeasuredHeight());
dimView.layout(0, status, dimView.getMeasuredWidth(), status + dimView.getMeasuredHeight());
selectionContainerView.layout(0, status, selectionContainerView.getMeasuredWidth(), status + selectionContainerView.getMeasuredHeight());
colorPicker.layout(0, actionBarHeight2, colorPicker.getMeasuredWidth(), actionBarHeight2 + colorPicker.getMeasuredHeight());
toolsView.layout(0, height - toolsView.getMeasuredHeight(), toolsView.getMeasuredWidth(), height);
curtainView.layout(0, 0, width, maxHeight);
if (stickersView != null) {
stickersView.layout(0, actionBarHeight2, stickersView.getMeasuredWidth(), actionBarHeight2 + stickersView.getMeasuredHeight());
stickersView.layout(0, status, stickersView.getMeasuredWidth(), status + stickersView.getMeasuredHeight());
}
if (currentEntityView != null) {
currentEntityView.updateSelectionView();
currentEntityView.updateSelectionView(); //TODO this is bug
currentEntityView.setOffset(entitiesView.getLeft() - selectionContainerView.getLeft(), entitiesView.getTop() - selectionContainerView.getTop());
}
}
@ -726,16 +647,6 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
return !editingText;
}
@Override
public void onBeganEntityDragging(EntityView entityView) {
setColorPickerVisibilityFade(false);
}
@Override
public void onFinishedEntityDragging(EntityView entityView) {
setColorPickerVisibilityFade(true);
}
private Point centerPositionForEntity() {
Size paintingSize = getPaintingSize();
return new Point(paintingSize.width / 2.0f, paintingSize.height / 2.0f);
@ -879,7 +790,7 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
@Override
public void onTypeChanged() {
updateStickersTitle();
}
});
addView(stickersView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
@ -889,23 +800,6 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
Animator a = ObjectAnimator.ofFloat(stickersView, "alpha", 0.0f, 1.0f);
a.setDuration(200);
a.start();
undoItem.setVisibility(GONE);
updateStickersTitle();
}
private void updateStickersTitle() {
if (stickersView == null || stickersView.getVisibility() != VISIBLE) {
return;
}
switch (stickersView.getCurrentType()) {
case StickersQuery.TYPE_IMAGE:
actionBar.setTitle(LocaleController.getString("PaintStickers", R.string.PaintStickers));
break;
case StickersQuery.TYPE_MASK:
actionBar.setTitle(LocaleController.getString("Masks", R.string.Masks));
break;
}
}
private void closeStickersView() {
@ -923,9 +817,6 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
}
});
a.start();
undoItem.setVisibility(VISIBLE);
actionBar.setTitle(LocaleController.getString("PaintDraw", R.string.PaintDraw));
}
private Size baseStickerSize() {
@ -996,11 +887,7 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
textPaintView.setRotation(0.0f);
textPaintView.setScale(1.0f);
undoItem.setVisibility(GONE);
doneItem.setVisibility(VISIBLE);
actionBar.setTitle(LocaleController.getString("PaintText", R.string.PaintText));
toolsView.setVisibility(GONE);
setColorPickerVisibilitySlide(false);
setTextDimVisibility(true, textPaintView);
textPaintView.beginEditing();
@ -1016,11 +903,7 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
TextPaintView textPaintView = (TextPaintView) currentEntityView;
undoItem.setVisibility(VISIBLE);
doneItem.setVisibility(GONE);
actionBar.setTitle(LocaleController.getString("PaintDraw", R.string.PaintDraw));
toolsView.setVisibility(VISIBLE);
setColorPickerVisibilitySlide(true);
AndroidUtilities.hideKeyboard(textPaintView.getFocusedView());
@ -1173,7 +1056,7 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
if (selected) {
ImageView check = new ImageView(getContext());
check.setImageResource(R.drawable.ic_ab_done);//TODO color
check.setImageResource(R.drawable.ic_ab_done);
check.setScaleType(ImageView.ScaleType.CENTER);
button.addView(check, LayoutHelper.createFrame(50, LayoutHelper.MATCH_PARENT));
}
@ -1246,7 +1129,7 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView
if (selected) {
ImageView check = new ImageView(getContext());
check.setImageResource(R.drawable.ic_ab_done); //TODO color
check.setImageResource(R.drawable.ic_ab_done);
check.setScaleType(ImageView.ScaleType.CENTER);
button.addView(check, LayoutHelper.createFrame(50, LayoutHelper.MATCH_PARENT));
}

View File

@ -223,7 +223,7 @@ public class PopupAudioView extends BaseCell implements SeekBar.SeekBarDelegate,
invalidate();
}
} else if (buttonState == 2) {
FileLoader.getInstance().loadFile(currentMessageObject.getDocument(), true, false);
FileLoader.getInstance().loadFile(currentMessageObject.getDocument(), true, 0);
buttonState = 4;
invalidate();
} else if (buttonState == 3) {
@ -264,7 +264,7 @@ public class PopupAudioView extends BaseCell implements SeekBar.SeekBarDelegate,
public void downloadAudioIfNeed() {
if (buttonState == 2) {
FileLoader.getInstance().loadFile(currentMessageObject.getDocument(), true, false);
FileLoader.getInstance().loadFile(currentMessageObject.getDocument(), true, 0);
buttonState = 3;
invalidate();
}

View File

@ -399,7 +399,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not
stickerEmojiTextView.setText(Emoji.replaceEmoji(StickersQuery.getEmojiForSticker(selectedSticker.id), stickerEmojiTextView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(30), false));
}
stickerImageView.getImageReceiver().setImage(selectedSticker, null, selectedSticker.thumb.location, null, "webp", true);
stickerImageView.getImageReceiver().setImage(selectedSticker, null, selectedSticker.thumb.location, null, "webp", 1);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) stickerPreviewLayout.getLayoutParams();
layoutParams.topMargin = scrollOffsetY;
stickerPreviewLayout.setLayoutParams(layoutParams);

View File

@ -14,6 +14,7 @@ import android.net.Uri;
import android.os.Handler;
import android.view.TextureView;
import org.telegram.messenger.secretmedia.ExtendedDefaultDataSourceFactory;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.exoplayer2.DefaultLoadControl;
import org.telegram.messenger.exoplayer2.DefaultRenderersFactory;
@ -41,7 +42,6 @@ import org.telegram.messenger.exoplayer2.trackselection.TrackSelection;
import org.telegram.messenger.exoplayer2.trackselection.TrackSelectionArray;
import org.telegram.messenger.exoplayer2.upstream.DataSource;
import org.telegram.messenger.exoplayer2.upstream.DefaultBandwidthMeter;
import org.telegram.messenger.exoplayer2.upstream.DefaultDataSourceFactory;
import org.telegram.messenger.exoplayer2.upstream.DefaultHttpDataSourceFactory;
@SuppressLint("NewApi")
@ -79,7 +79,7 @@ public class VideoPlayer implements ExoPlayer.EventListener, SimpleExoPlayer.Vid
private static final DefaultBandwidthMeter BANDWIDTH_METER = new DefaultBandwidthMeter();
public VideoPlayer() {
mediaDataSourceFactory = new DefaultDataSourceFactory(ApplicationLoader.applicationContext, BANDWIDTH_METER, new DefaultHttpDataSourceFactory("Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20150101 Firefox/47.0 (Chrome)", BANDWIDTH_METER));
mediaDataSourceFactory = new ExtendedDefaultDataSourceFactory(ApplicationLoader.applicationContext, BANDWIDTH_METER, new DefaultHttpDataSourceFactory("Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20150101 Firefox/47.0 (Chrome)", BANDWIDTH_METER));
mainHandler = new Handler();

View File

@ -0,0 +1,445 @@
/*
* This is the source code of Telegram for Android v. 3.x.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-2017.
*/
package org.telegram.ui.Components;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.os.AsyncTask;
import android.view.MotionEvent;
import android.view.View;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.R;
import java.util.ArrayList;
@TargetApi(10)
public class VideoTimelinePlayView extends View {
private long videoLength;
private float progressLeft;
private float progressRight = 1;
private Paint paint;
private Paint paint2;
private boolean pressedLeft;
private boolean pressedRight;
private boolean pressedPlay;
private float playProgress = 0.5f;
private float pressDx;
private MediaMetadataRetriever mediaMetadataRetriever;
private VideoTimelineViewDelegate delegate;
private ArrayList<Bitmap> frames = new ArrayList<>();
private AsyncTask<Integer, Integer, Bitmap> currentTask;
private static final Object sync = new Object();
private long frameTimeOffset;
private int frameWidth;
private int frameHeight;
private int framesToLoad;
private float maxProgressDiff = 1.0f;
private float minProgressDiff = 0.0f;
private boolean isRoundFrames;
private Rect rect1;
private Rect rect2;
private RectF rect3 = new RectF();
private Drawable drawableLeft;
private Drawable drawableRight;
private int lastWidth;
public interface VideoTimelineViewDelegate {
void onLeftProgressChanged(float progress);
void onRightProgressChanged(float progress);
void onPlayProgressChanged(float progress);
void didStartDragging();
void didStopDragging();
}
public VideoTimelinePlayView(Context context) {
super(context);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(0xffffffff);
paint2 = new Paint();
paint2.setColor(0x7f000000);
drawableLeft = context.getResources().getDrawable(R.drawable.video_cropleft);
drawableLeft.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
drawableRight = context.getResources().getDrawable(R.drawable.video_cropright);
drawableRight.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
}
public float getProgress() {
return playProgress;
}
public float getLeftProgress() {
return progressLeft;
}
public float getRightProgress() {
return progressRight;
}
public void setMinProgressDiff(float value) {
minProgressDiff = value;
}
public void setMaxProgressDiff(float value) {
maxProgressDiff = value;
if (progressRight - progressLeft > maxProgressDiff) {
progressRight = progressLeft + maxProgressDiff;
invalidate();
}
}
public void setRoundFrames(boolean value) {
isRoundFrames = value;
if (isRoundFrames) {
rect1 = new Rect(AndroidUtilities.dp(14), AndroidUtilities.dp(14), AndroidUtilities.dp(14 + 28), AndroidUtilities.dp(14 + 28));
rect2 = new Rect();
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event == null) {
return false;
}
float x = event.getX();
float y = event.getY();
int width = getMeasuredWidth() - AndroidUtilities.dp(32);
int startX = (int) (width * progressLeft) + AndroidUtilities.dp(16);
int playX = (int) (width * (progressLeft + (progressRight - progressLeft) * playProgress)) + AndroidUtilities.dp(16);
int endX = (int) (width * progressRight) + AndroidUtilities.dp(16);
if (event.getAction() == MotionEvent.ACTION_DOWN) {
getParent().requestDisallowInterceptTouchEvent(true);
if (mediaMetadataRetriever == null) {
return false;
}
int additionWidth = AndroidUtilities.dp(12);
int additionWidthPlay = AndroidUtilities.dp(8);
if (playX - additionWidthPlay <= x && x <= playX + additionWidthPlay && y >= 0 && y <= getMeasuredHeight()) {
if (delegate != null) {
delegate.didStartDragging();
}
pressedPlay = true;
pressDx = (int) (x - playX);
invalidate();
return true;
} else if (startX - additionWidth <= x && x <= startX + additionWidth && y >= 0 && y <= getMeasuredHeight()) {
if (delegate != null) {
delegate.didStartDragging();
}
pressedLeft = true;
pressDx = (int) (x - startX);
invalidate();
return true;
} else if (endX - additionWidth <= x && x <= endX + additionWidth && y >= 0 && y <= getMeasuredHeight()) {
if (delegate != null) {
delegate.didStartDragging();
}
pressedRight = true;
pressDx = (int) (x - endX);
invalidate();
return true;
}
} else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
if (pressedLeft) {
if (delegate != null) {
delegate.didStopDragging();
}
pressedLeft = false;
return true;
} else if (pressedRight) {
if (delegate != null) {
delegate.didStopDragging();
}
pressedRight = false;
return true;
} else if (pressedPlay) {
if (delegate != null) {
delegate.didStopDragging();
}
pressedPlay = false;
return true;
}
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (pressedPlay) {
playX = (int) (x - pressDx);
playProgress = (float) (playX - AndroidUtilities.dp(16)) / (float) width;
if (playProgress < progressLeft) {
playProgress = progressLeft;
} else if (playProgress > progressRight) {
playProgress = progressRight;
}
playProgress = (playProgress - progressLeft) / (progressRight - progressLeft);
if (delegate != null) {
delegate.onPlayProgressChanged(progressLeft + (progressRight - progressLeft) * playProgress);
}
invalidate();
return true;
} else if (pressedLeft) {
startX = (int) (x - pressDx);
if (startX < AndroidUtilities.dp(16)) {
startX = AndroidUtilities.dp(16);
} else if (startX > endX) {
startX = endX;
}
progressLeft = (float) (startX - AndroidUtilities.dp(16)) / (float) width;
if (progressRight - progressLeft > maxProgressDiff) {
progressRight = progressLeft + maxProgressDiff;
} else if (minProgressDiff != 0 && progressRight - progressLeft < minProgressDiff) {
progressLeft = progressRight - minProgressDiff;
if (progressLeft < 0) {
progressLeft = 0;
}
}
if (delegate != null) {
delegate.onLeftProgressChanged(progressLeft);
}
invalidate();
return true;
} else if (pressedRight) {
endX = (int) (x - pressDx);
if (endX < startX) {
endX = startX;
} else if (endX > width + AndroidUtilities.dp(16)) {
endX = width + AndroidUtilities.dp(16);
}
progressRight = (float) (endX - AndroidUtilities.dp(16)) / (float) width;
if (progressRight - progressLeft > maxProgressDiff) {
progressLeft = progressRight - maxProgressDiff;
} else if (minProgressDiff != 0 && progressRight - progressLeft < minProgressDiff) {
progressRight = progressLeft + minProgressDiff;
if (progressRight > 1.0f) {
progressRight = 1.0f;
}
}
if (delegate != null) {
delegate.onRightProgressChanged(progressRight);
}
invalidate();
return true;
}
}
return false;
}
public void setColor(int color) {
paint.setColor(color);
}
public void setVideoPath(String path) {
destroy();
mediaMetadataRetriever = new MediaMetadataRetriever();
progressLeft = 0.0f;
progressRight = 1.0f;
try {
mediaMetadataRetriever.setDataSource(path);
String duration = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
videoLength = Long.parseLong(duration);
} catch (Exception e) {
FileLog.e(e);
}
invalidate();
}
public void setDelegate(VideoTimelineViewDelegate delegate) {
this.delegate = delegate;
}
private void reloadFrames(int frameNum) {
if (mediaMetadataRetriever == null) {
return;
}
if (frameNum == 0) {
if (isRoundFrames) {
frameHeight = frameWidth = AndroidUtilities.dp(56);
framesToLoad = (int) Math.ceil((getMeasuredWidth() - AndroidUtilities.dp(16)) / (frameHeight / 2.0f));
} else {
frameHeight = AndroidUtilities.dp(40);
framesToLoad = (getMeasuredWidth() - AndroidUtilities.dp(16)) / frameHeight;
frameWidth = (int) Math.ceil((float) (getMeasuredWidth() - AndroidUtilities.dp(16)) / (float) framesToLoad);
}
frameTimeOffset = videoLength / framesToLoad;
}
currentTask = new AsyncTask<Integer, Integer, Bitmap>() {
private int frameNum = 0;
@Override
protected Bitmap doInBackground(Integer... objects) {
frameNum = objects[0];
Bitmap bitmap = null;
if (isCancelled()) {
return null;
}
try {
bitmap = mediaMetadataRetriever.getFrameAtTime(frameTimeOffset * frameNum * 1000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
if (isCancelled()) {
return null;
}
if (bitmap != null) {
Bitmap result = Bitmap.createBitmap(frameWidth, frameHeight, bitmap.getConfig());
Canvas canvas = new Canvas(result);
float scaleX = (float) frameWidth / (float) bitmap.getWidth();
float scaleY = (float) frameHeight / (float) bitmap.getHeight();
float scale = scaleX > scaleY ? scaleX : scaleY;
int w = (int) (bitmap.getWidth() * scale);
int h = (int) (bitmap.getHeight() * scale);
Rect srcRect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
Rect destRect = new Rect((frameWidth - w) / 2, (frameHeight - h) / 2, w, h);
canvas.drawBitmap(bitmap, srcRect, destRect, null);
bitmap.recycle();
bitmap = result;
}
} catch (Exception e) {
FileLog.e(e);
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (!isCancelled()) {
frames.add(bitmap);
invalidate();
if (frameNum < framesToLoad) {
reloadFrames(frameNum + 1);
}
}
}
};
currentTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, frameNum, null, null);
}
public void destroy() {
synchronized (sync) {
try {
if (mediaMetadataRetriever != null) {
mediaMetadataRetriever.release();
mediaMetadataRetriever = null;
}
} catch (Exception e) {
FileLog.e(e);
}
}
for (Bitmap bitmap : frames) {
if (bitmap != null) {
bitmap.recycle();
}
}
frames.clear();
if (currentTask != null) {
currentTask.cancel(true);
currentTask = null;
}
}
public boolean isDragging() {
return pressedPlay;
}
public void setProgress(float value) {
playProgress = value;
invalidate();
}
public void clearFrames() {
for (Bitmap bitmap : frames) {
if (bitmap != null) {
bitmap.recycle();
}
}
frames.clear();
if (currentTask != null) {
currentTask.cancel(true);
currentTask = null;
}
invalidate();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
if (lastWidth != widthSize) {
clearFrames();
lastWidth = widthSize;
}
}
@Override
protected void onDraw(Canvas canvas) {
int width = getMeasuredWidth() - AndroidUtilities.dp(36);
int startX = (int) (width * progressLeft) + AndroidUtilities.dp(16);
int endX = (int) (width * progressRight) + AndroidUtilities.dp(16);
canvas.save();
canvas.clipRect(AndroidUtilities.dp(16), AndroidUtilities.dp(4), width + AndroidUtilities.dp(20), AndroidUtilities.dp(48));
if (frames.isEmpty() && currentTask == null) {
reloadFrames(0);
} else {
int offset = 0;
for (int a = 0; a < frames.size(); a++) {
Bitmap bitmap = frames.get(a);
if (bitmap != null) {
int x = AndroidUtilities.dp(16) + offset * (isRoundFrames ? frameWidth / 2 : frameWidth);
int y = AndroidUtilities.dp(2 + 4);
if (isRoundFrames) {
rect2.set(x, y, x + AndroidUtilities.dp(28), y + AndroidUtilities.dp(28));
canvas.drawBitmap(bitmap, rect1, rect2, null);
} else {
canvas.drawBitmap(bitmap, x, y, null);
}
}
offset++;
}
}
int top = AndroidUtilities.dp(2 + 4);
int end = AndroidUtilities.dp(48);
canvas.drawRect(AndroidUtilities.dp(16), top, startX, AndroidUtilities.dp(46), paint2);
canvas.drawRect(endX + AndroidUtilities.dp(4), top, AndroidUtilities.dp(16) + width + AndroidUtilities.dp(4), AndroidUtilities.dp(46), paint2);
canvas.drawRect(startX, AndroidUtilities.dp(4), startX + AndroidUtilities.dp(2), end, paint);
canvas.drawRect(endX + AndroidUtilities.dp(2), AndroidUtilities.dp(4), endX + AndroidUtilities.dp(4), end, paint);
canvas.drawRect(startX + AndroidUtilities.dp(2), AndroidUtilities.dp(4), endX + AndroidUtilities.dp(4), top, paint);
canvas.drawRect(startX + AndroidUtilities.dp(2), end - AndroidUtilities.dp(2), endX + AndroidUtilities.dp(4), end, paint);
canvas.restore();
rect3.set(startX - AndroidUtilities.dp(8), AndroidUtilities.dp(4), startX + AndroidUtilities.dp(2), end);
canvas.drawRoundRect(rect3, AndroidUtilities.dp(2), AndroidUtilities.dp(2), paint);
drawableLeft.setBounds(startX - AndroidUtilities.dp(8), AndroidUtilities.dp(4) + (AndroidUtilities.dp(44) - AndroidUtilities.dp(18)) / 2, startX + AndroidUtilities.dp(2), (AndroidUtilities.dp(44) - AndroidUtilities.dp(18)) / 2 + AndroidUtilities.dp(18 + 4));
drawableLeft.draw(canvas);
rect3.set(endX + AndroidUtilities.dp(2), AndroidUtilities.dp(4), endX + AndroidUtilities.dp(12), end);
canvas.drawRoundRect(rect3, AndroidUtilities.dp(2), AndroidUtilities.dp(2), paint);
drawableRight.setBounds(endX + AndroidUtilities.dp(2), AndroidUtilities.dp(4) + (AndroidUtilities.dp(44) - AndroidUtilities.dp(18)) / 2, endX + AndroidUtilities.dp(12), (AndroidUtilities.dp(44) - AndroidUtilities.dp(18)) / 2 + AndroidUtilities.dp(18 + 4));
drawableRight.draw(canvas);
float cx = AndroidUtilities.dp(18) + width * (progressLeft + (progressRight - progressLeft) * playProgress);
rect3.set(cx - AndroidUtilities.dp(1.5f), AndroidUtilities.dp(2), cx + AndroidUtilities.dp(1.5f), AndroidUtilities.dp(50));
canvas.drawRoundRect(rect3, AndroidUtilities.dp(1), AndroidUtilities.dp(1), paint2);
canvas.drawCircle(cx, AndroidUtilities.dp(52), AndroidUtilities.dp(3.5f), paint2);
rect3.set(cx - AndroidUtilities.dp(1), AndroidUtilities.dp(2), cx + AndroidUtilities.dp(1), AndroidUtilities.dp(50));
canvas.drawRoundRect(rect3, AndroidUtilities.dp(1), AndroidUtilities.dp(1), paint);
canvas.drawCircle(cx, AndroidUtilities.dp(52), AndroidUtilities.dp(3), paint);
}
}

View File

@ -52,7 +52,7 @@ public class VideoTimelineView extends View {
public interface VideoTimelineViewDelegate {
void onLeftProgressChanged(float progress);
void onRifhtProgressChanged(float progress);
void onRightProgressChanged(float progress);
void didStartDragging();
void didStopDragging();
}
@ -181,7 +181,7 @@ public class VideoTimelineView extends View {
}
}
if (delegate != null) {
delegate.onRifhtProgressChanged(progressRight);
delegate.onRightProgressChanged(progressRight);
}
invalidate();
return true;

View File

@ -1968,7 +1968,7 @@ public class WebPlayerView extends ViewGroup implements VideoPlayer.VideoPlayerD
if (thumb != null) {
TLRPC.PhotoSize photoSize = FileLoader.getClosestPhotoSizeWithSize(thumb.sizes, 80, true);
if (photoSize != null) {
controlsView.imageReceiver.setImage(null, null, thumb != null ? photoSize.location : null, thumb != null ? "80_80_b" : null, 0, null, true);
controlsView.imageReceiver.setImage(null, null, thumb != null ? photoSize.location : null, thumb != null ? "80_80_b" : null, 0, null, 1);
drawImage = true;
}
} else {

View File

@ -272,7 +272,7 @@ public class VoIPHelper{
.setPositiveButton(LocaleController.getString("Send", R.string.Send), new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which){
TLRPC.TL_phone_setCallRating req = new TLRPC.TL_phone_setCallRating();
final TLRPC.TL_phone_setCallRating req = new TLRPC.TL_phone_setCallRating();
req.rating = bar.getRating();
if (req.rating < 5)
req.comment = commentBox.getText().toString();
@ -287,7 +287,7 @@ public class VoIPHelper{
if (response instanceof TLRPC.TL_updates) {
TLRPC.TL_updates updates = (TLRPC.TL_updates) response;
MessagesController.getInstance().processUpdates(updates, false);
if(includeLogs[0] && log.exists()){
if(includeLogs[0] && log.exists() && req.rating<4){
SendMessagesHelper.prepareSendingDocument(log.getAbsolutePath(), log.getAbsolutePath(), null, "text/plain", VOIP_SUPPORT_ID, null, null);
Toast.makeText(context, LocaleController.getString("CallReportSent", R.string.CallReportSent), Toast.LENGTH_LONG).show();
}

View File

@ -968,11 +968,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter.
floatingButton.setTranslationY(floatingHidden ? AndroidUtilities.dp(100) : 0);
floatingButton.setClickable(!floatingHidden);
if (floatingButton != null) {
if (Build.VERSION.SDK_INT < 16) {
floatingButton.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
floatingButton.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
floatingButton.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
}
});

View File

@ -16,23 +16,28 @@ import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.SurfaceTexture;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.opengl.GLES20;
import android.opengl.GLUtils;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
@ -42,6 +47,9 @@ import android.widget.TextView;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.BuildVars;
import org.telegram.messenger.DispatchQueue;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.Intro;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
@ -51,6 +59,14 @@ import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.Components.LayoutHelper;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import javax.microedition.khronos.opengles.GL;
import javax.microedition.khronos.opengles.GL10;
public class IntroActivity extends Activity implements NotificationCenter.NotificationCenterDelegate {
private class BottomPagesView extends View {
@ -84,7 +100,7 @@ public class IntroActivity extends Activity implements NotificationCenter.Notifi
paint.setColor(0xffbbbbbb);
int x;
currentPage = viewPager.getCurrentItem();
for (int a = 0; a < 7; a++) {
for (int a = 0; a < 6; a++) {
if (a == currentPage) {
continue;
}
@ -108,18 +124,19 @@ public class IntroActivity extends Activity implements NotificationCenter.Notifi
}
private ViewPager viewPager;
private ImageView topImage1;
private ImageView topImage2;
private BottomPagesView bottomPages;
private TextView textView;
private int lastPage = 0;
private boolean justCreated = false;
private boolean startPressed = false;
private int[] icons;
private int[] titles;
private String[] titlesString;
private int[] messages;
private String[] messagesString;
private String[] titles;
private String[] messages;
private int currentViewPagerPage;
private EGLThread eglThread;
private long currentDate;
private boolean justEndDragging;
private boolean dragging;
private int startDragX;
private LocaleController.LocaleInfo localeInfo;
@ -129,117 +146,74 @@ public class IntroActivity extends Activity implements NotificationCenter.Notifi
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
if (LocaleController.isRTL) {
icons = new int[]{
R.drawable.intro7,
R.drawable.intro6,
R.drawable.intro5,
R.drawable.intro4,
R.drawable.intro3,
R.drawable.intro2,
R.drawable.intro1
};
titles = new int[]{
R.string.Page7Title,
R.string.Page6Title,
R.string.Page5Title,
R.string.Page4Title,
R.string.Page3Title,
R.string.Page2Title,
R.string.Page1Title
};
titlesString = new String[]{
"Page7Title",
"Page6Title",
"Page5Title",
"Page4Title",
"Page3Title",
"Page2Title",
"Page1Title"
};
messages = new int[]{
R.string.Page7Message,
R.string.Page6Message,
R.string.Page5Message,
R.string.Page4Message,
R.string.Page3Message,
R.string.Page2Message,
R.string.Page1Message
};
messagesString = new String[]{
"Page7Message",
"Page6Message",
"Page5Message",
"Page4Message",
"Page3Message",
"Page2Message",
"Page1Message"
};
} else {
icons = new int[]{
R.drawable.intro1,
R.drawable.intro2,
R.drawable.intro3,
R.drawable.intro4,
R.drawable.intro5,
R.drawable.intro6,
R.drawable.intro7
};
titles = new int[]{
R.string.Page1Title,
R.string.Page2Title,
R.string.Page3Title,
R.string.Page4Title,
R.string.Page5Title,
R.string.Page6Title,
R.string.Page7Title
};
titlesString = new String[]{
"Page1Title",
"Page2Title",
"Page3Title",
"Page4Title",
"Page5Title",
"Page6Title",
"Page7Title"
};
messages = new int[]{
R.string.Page1Message,
R.string.Page2Message,
R.string.Page3Message,
R.string.Page4Message,
R.string.Page5Message,
R.string.Page6Message,
R.string.Page7Message
};
messagesString = new String[]{
"Page1Message",
"Page2Message",
"Page3Message",
"Page4Message",
"Page5Message",
"Page6Message",
"Page7Message"
};
}
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
preferences.edit().putLong("intro_crashed_time", System.currentTimeMillis()).commit();
titles = new String[]{
LocaleController.getString("Page1Title", R.string.Page1Title),
LocaleController.getString("Page2Title", R.string.Page2Title),
LocaleController.getString("Page3Title", R.string.Page3Title),
LocaleController.getString("Page5Title", R.string.Page5Title),
LocaleController.getString("Page4Title", R.string.Page4Title),
LocaleController.getString("Page6Title", R.string.Page6Title)
};
messages = new String[]{
LocaleController.getString("Page1Message", R.string.Page1Message),
LocaleController.getString("Page2Message", R.string.Page2Message),
LocaleController.getString("Page3Message", R.string.Page3Message),
LocaleController.getString("Page5Message", R.string.Page5Message),
LocaleController.getString("Page4Message", R.string.Page4Message),
LocaleController.getString("Page6Message", R.string.Page6Message)
};
ScrollView scrollView = new ScrollView(this);
scrollView.setFillViewport(true);
FrameLayout frameLayout = new FrameLayout(this);
frameLayout.setBackgroundColor(0xfffafafa);
frameLayout.setBackgroundColor(0xffffffff);
scrollView.addView(frameLayout, LayoutHelper.createScroll(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP));
FrameLayout frameLayout2 = new FrameLayout(this);
frameLayout.addView(frameLayout2, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 0, 88, 0, 0));
frameLayout.addView(frameLayout2, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 0, 78, 0, 0));
topImage1 = new ImageView(this);
topImage1.setImageResource(R.drawable.intro1);
frameLayout2.addView(topImage1, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
TextureView textureView = new TextureView(this);
frameLayout2.addView(textureView, LayoutHelper.createFrame(180, 140, Gravity.CENTER));
textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
if (eglThread == null && surface != null) {
eglThread = new EGLThread(surface);
eglThread.setSurfaceTextureSize(width, height);
eglThread.postRunnable(new Runnable() {
@Override
public void run() {
eglThread.drawRunnable.run();
}
});
}
}
topImage2 = new ImageView(this);
topImage2.setVisibility(View.GONE);
frameLayout2.addView(topImage2, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, final int width, final int height) {
if (eglThread != null) {
eglThread.setSurfaceTextureSize(width, height);
}
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
if (eglThread != null) {
eglThread.shutdown();
eglThread = null;
}
return true;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
});
viewPager = new ViewPager(this);
viewPager.setAdapter(new IntroAdapter());
@ -250,72 +224,32 @@ public class IntroActivity extends Activity implements NotificationCenter.Notifi
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
bottomPages.setPageOffset(position, positionOffset);
float width = viewPager.getMeasuredWidth();
if (width == 0) {
return;
}
float offset = (position * width + positionOffsetPixels - currentViewPagerPage * width) / width;
Intro.setScrollOffset(offset);
}
@Override
public void onPageSelected(int i) {
currentViewPagerPage = i;
}
@Override
public void onPageScrollStateChanged(int i) {
if (i == ViewPager.SCROLL_STATE_IDLE || i == ViewPager.SCROLL_STATE_SETTLING) {
if (i == ViewPager.SCROLL_STATE_DRAGGING) {
dragging = true;
startDragX = viewPager.getCurrentItem() * viewPager.getMeasuredWidth();
} else if (i == ViewPager.SCROLL_STATE_IDLE || i == ViewPager.SCROLL_STATE_SETTLING) {
if (dragging) {
justEndDragging = true;
dragging = false;
}
if (lastPage != viewPager.getCurrentItem()) {
lastPage = viewPager.getCurrentItem();
final ImageView fadeoutImage;
final ImageView fadeinImage;
if (topImage1.getVisibility() == View.VISIBLE) {
fadeoutImage = topImage1;
fadeinImage = topImage2;
} else {
fadeoutImage = topImage2;
fadeinImage = topImage1;
}
fadeinImage.bringToFront();
fadeinImage.setImageResource(icons[lastPage]);
fadeinImage.clearAnimation();
fadeoutImage.clearAnimation();
Animation outAnimation = AnimationUtils.loadAnimation(IntroActivity.this, R.anim.icon_anim_fade_out);
outAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
fadeoutImage.setVisibility(View.GONE);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
Animation inAnimation = AnimationUtils.loadAnimation(IntroActivity.this, R.anim.icon_anim_fade_in);
inAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
fadeinImage.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationEnd(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
fadeoutImage.startAnimation(outAnimation);
fadeinImage.startAnimation(inAnimation);
}
}
}
@ -323,7 +257,6 @@ public class IntroActivity extends Activity implements NotificationCenter.Notifi
TextView startMessagingButton = new TextView(this);
startMessagingButton.setText(LocaleController.getString("StartMessaging", R.string.StartMessaging).toUpperCase());
startMessagingButton.setPadding(AndroidUtilities.dp(20), AndroidUtilities.dp(10), AndroidUtilities.dp(20), AndroidUtilities.dp(10));
startMessagingButton.setGravity(Gravity.CENTER);
startMessagingButton.setTextColor(0xffffffff);
startMessagingButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
@ -334,6 +267,7 @@ public class IntroActivity extends Activity implements NotificationCenter.Notifi
animator.addState(new int[]{}, ObjectAnimator.ofFloat(startMessagingButton, "translationZ", AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200));
startMessagingButton.setStateListAnimator(animator);
}
startMessagingButton.setPadding(AndroidUtilities.dp(20), AndroidUtilities.dp(10), AndroidUtilities.dp(20), AndroidUtilities.dp(10));
frameLayout.addView(startMessagingButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 10, 0, 10, 76));
startMessagingButton.setOnClickListener(new View.OnClickListener() {
@Override
@ -359,7 +293,7 @@ public class IntroActivity extends Activity implements NotificationCenter.Notifi
}
bottomPages = new BottomPagesView(this);
frameLayout.addView(bottomPages, LayoutHelper.createFrame(77, 5, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 350, 0, 0));
frameLayout.addView(bottomPages, LayoutHelper.createFrame(66, 5, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 350, 0, 0));
textView = new TextView(this);
textView.setTextColor(0xff1393d2);
@ -436,6 +370,8 @@ public class IntroActivity extends Activity implements NotificationCenter.Notifi
protected void onDestroy() {
super.onDestroy();
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.suggestedLangpack);
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
preferences.edit().putLong("intro_crashed_time", 0).commit();
}
private void checkContinueText() {
@ -502,7 +438,7 @@ public class IntroActivity extends Activity implements NotificationCenter.Notifi
private class IntroAdapter extends PagerAdapter {
@Override
public int getCount() {
return 7;
return titles.length;
}
@Override
@ -523,8 +459,8 @@ public class IntroActivity extends Activity implements NotificationCenter.Notifi
container.addView(frameLayout, 0);
headerTextView.setText(LocaleController.getString(titlesString[position], titles[position]));
messageTextView.setText(AndroidUtilities.replaceTags(LocaleController.getString(messagesString[position], messages[position])));
headerTextView.setText(titles[position]);
messageTextView.setText(AndroidUtilities.replaceTags(messages[position]));
return frameLayout;
}
@ -538,6 +474,7 @@ public class IntroActivity extends Activity implements NotificationCenter.Notifi
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
bottomPages.setCurrentPage(position);
currentViewPagerPage = position;
}
@Override
@ -561,4 +498,218 @@ public class IntroActivity extends Activity implements NotificationCenter.Notifi
}
}
}
public class EGLThread extends DispatchQueue {
private final int EGL_CONTEXT_CLIENT_VERSION = 0x3098;
private final int EGL_OPENGL_ES2_BIT = 4;
private SurfaceTexture surfaceTexture;
private EGL10 egl10;
private EGLDisplay eglDisplay;
private EGLConfig eglConfig;
private EGLContext eglContext;
private EGLSurface eglSurface;
private GL gl;
private boolean initied;
private int textures[] = new int[23];
private int surfaceWidth;
private int surfaceHeight;
private long lastRenderCallTime;
public EGLThread(SurfaceTexture surface) {
super("EGLThread");
surfaceTexture = surface;
}
private boolean initGL() {
egl10 = (EGL10) EGLContext.getEGL();
eglDisplay = egl10.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
if (eglDisplay == EGL10.EGL_NO_DISPLAY) {
FileLog.e("eglGetDisplay failed " + GLUtils.getEGLErrorString(egl10.eglGetError()));
finish();
return false;
}
int[] version = new int[2];
if (!egl10.eglInitialize(eglDisplay, version)) {
FileLog.e("eglInitialize failed " + GLUtils.getEGLErrorString(egl10.eglGetError()));
finish();
return false;
}
int[] configsCount = new int[1];
EGLConfig[] configs = new EGLConfig[1];
int[] configSpec = new int[] {
EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL10.EGL_RED_SIZE, 8,
EGL10.EGL_GREEN_SIZE, 8,
EGL10.EGL_BLUE_SIZE, 8,
EGL10.EGL_ALPHA_SIZE, 8,
EGL10.EGL_DEPTH_SIZE, 24,
EGL10.EGL_STENCIL_SIZE, 0,
EGL10.EGL_SAMPLE_BUFFERS, 1,
EGL10.EGL_SAMPLES, 2,
EGL10.EGL_NONE
};
if (!egl10.eglChooseConfig(eglDisplay, configSpec, configs, 1, configsCount)) {
FileLog.e("eglChooseConfig failed " + GLUtils.getEGLErrorString(egl10.eglGetError()));
finish();
return false;
} else if (configsCount[0] > 0) {
eglConfig = configs[0];
} else {
FileLog.e("eglConfig not initialized");
finish();
return false;
}
int[] attrib_list = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE };
eglContext = egl10.eglCreateContext(eglDisplay, eglConfig, EGL10.EGL_NO_CONTEXT, attrib_list);
if (eglContext == null) {
FileLog.e("eglCreateContext failed " + GLUtils.getEGLErrorString(egl10.eglGetError()));
finish();
return false;
}
if (surfaceTexture instanceof SurfaceTexture) {
eglSurface = egl10.eglCreateWindowSurface(eglDisplay, eglConfig, surfaceTexture, null);
} else {
finish();
return false;
}
if (eglSurface == null || eglSurface == EGL10.EGL_NO_SURFACE) {
FileLog.e("createWindowSurface failed " + GLUtils.getEGLErrorString(egl10.eglGetError()));
finish();
return false;
}
if (!egl10.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)) {
FileLog.e("eglMakeCurrent failed " + GLUtils.getEGLErrorString(egl10.eglGetError()));
finish();
return false;
}
gl = eglContext.getGL();
GLES20.glGenTextures(23, textures, 0);
loadTexture(R.drawable.intro_fast_arrow_shadow, 0);
loadTexture(R.drawable.intro_fast_arrow, 1);
loadTexture(R.drawable.intro_fast_body, 2);
loadTexture(R.drawable.intro_fast_spiral, 3);
loadTexture(R.drawable.intro_ic_bubble_dot, 4);
loadTexture(R.drawable.intro_ic_bubble, 5);
loadTexture(R.drawable.intro_ic_cam_lens, 6);
loadTexture(R.drawable.intro_ic_cam, 7);
loadTexture(R.drawable.intro_ic_pencil, 8);
loadTexture(R.drawable.intro_ic_pin, 9);
loadTexture(R.drawable.intro_ic_smile_eye, 10);
loadTexture(R.drawable.intro_ic_smile, 11);
loadTexture(R.drawable.intro_ic_videocam, 12);
loadTexture(R.drawable.intro_knot_down, 13);
loadTexture(R.drawable.intro_knot_up, 14);
loadTexture(R.drawable.intro_powerful_infinity_white, 15);
loadTexture(R.drawable.intro_powerful_infinity, 16);
loadTexture(R.drawable.intro_powerful_mask, 17);
loadTexture(R.drawable.intro_powerful_star, 18);
loadTexture(R.drawable.intro_private_door, 19);
loadTexture(R.drawable.intro_private_screw, 20);
loadTexture(R.drawable.intro_tg_plane, 21);
loadTexture(R.drawable.intro_tg_sphere, 22);
Intro.setTelegramTextures(textures[22], textures[21]);
Intro.setPowerfulTextures(textures[17], textures[18], textures[16], textures[15]);
Intro.setPrivateTextures(textures[19], textures[20]);
Intro.setFreeTextures(textures[14], textures[13]);
Intro.setFastTextures(textures[2], textures[3], textures[1], textures[0]);
Intro.setIcTextures(textures[4], textures[5], textures[6], textures[7], textures[8], textures[9], textures[10], textures[11], textures[12]);
Intro.onSurfaceCreated();
currentDate = System.currentTimeMillis() - 1000;
return true;
}
public void finish() {
if (eglSurface != null) {
egl10.eglMakeCurrent(eglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
egl10.eglDestroySurface(eglDisplay, eglSurface);
eglSurface = null;
}
if (eglContext != null) {
egl10.eglDestroyContext(eglDisplay, eglContext);
eglContext = null;
}
if (eglDisplay != null) {
egl10.eglTerminate(eglDisplay);
eglDisplay = null;
}
}
private Runnable drawRunnable = new Runnable() {
@Override
public void run() {
if (!initied) {
return;
}
if (!eglContext.equals(egl10.eglGetCurrentContext()) || !eglSurface.equals(egl10.eglGetCurrentSurface(EGL10.EGL_DRAW))) {
if (!egl10.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)) {
FileLog.e("eglMakeCurrent failed " + GLUtils.getEGLErrorString(egl10.eglGetError()));
return;
}
}
float time = (System.currentTimeMillis() - currentDate) / 1000.0f;
Intro.setPage(currentViewPagerPage);
Intro.setDate(time);
Intro.onDrawFrame();
egl10.eglSwapBuffers(eglDisplay, eglSurface);
postRunnable(new Runnable() {
@Override
public void run() {
drawRunnable.run();
}
}, 16);
}
};
private void loadTexture(int resId, int index) {
Drawable drawable = getResources().getDrawable(resId);
if (drawable instanceof BitmapDrawable) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
GLES20.glBindTexture(GL10.GL_TEXTURE_2D, textures[index]);
GLES20.glTexParameteri(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
GLES20.glTexParameteri(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
GLES20.glTexParameteri(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
}
}
public void shutdown() {
postRunnable(new Runnable() {
@Override
public void run() {
finish();
Looper looper = Looper.myLooper();
if (looper != null) {
looper.quit();
}
}
});
}
public void setSurfaceTextureSize(int width, int height) {
surfaceWidth = width;
surfaceHeight = height;
Intro.onSurfaceChanged(width, height, Math.min(surfaceWidth / 148.0f, surfaceHeight / 148.0f), 0);
}
@Override
public void run() {
initied = initGL();
super.run();
}
}
}

View File

@ -56,19 +56,7 @@ public class LanguageSelectActivity extends BaseFragment {
@Override
public boolean onFragmentCreate() {
sortedLanguages = new ArrayList<>(LocaleController.getInstance().languages);
final LocaleController.LocaleInfo currentLocale = LocaleController.getInstance().getCurrentLocaleInfo();
Collections.sort(sortedLanguages, new Comparator<LocaleController.LocaleInfo>() {
@Override
public int compare(LocaleController.LocaleInfo o, LocaleController.LocaleInfo o2) {
if (o == currentLocale) {
return -1;
} else if (o2 == currentLocale) {
return 1;
}
return o.name.compareTo(o2.name);
}
});
fillLanguages();
return super.onFragmentCreate();
}
@ -186,6 +174,7 @@ public class LanguageSelectActivity extends BaseFragment {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (LocaleController.getInstance().deleteLanguage(finalLocaleInfo)) {
fillLanguages();
if (searchResult != null) {
searchResult.remove(finalLocaleInfo);
}
@ -216,6 +205,22 @@ public class LanguageSelectActivity extends BaseFragment {
return fragmentView;
}
private void fillLanguages() {
sortedLanguages = new ArrayList<>(LocaleController.getInstance().languages);
final LocaleController.LocaleInfo currentLocale = LocaleController.getInstance().getCurrentLocaleInfo();
Collections.sort(sortedLanguages, new Comparator<LocaleController.LocaleInfo>() {
@Override
public int compare(LocaleController.LocaleInfo o, LocaleController.LocaleInfo o2) {
if (o == currentLocale) {
return -1;
} else if (o2 == currentLocale) {
return 1;
}
return o.name.compareTo(o2.name);
}
});
}
@Override
public void onResume() {
super.onResume();

View File

@ -25,7 +25,6 @@ import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.ActionMode;
import android.view.KeyEvent;
@ -148,8 +147,14 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
finish();
return;
}
if (intent != null && !intent.getBooleanExtra("fromIntro", false)) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("logininfo2", MODE_PRIVATE);
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
long crashed_time = preferences.getLong("intro_crashed_time", 0);
boolean fromIntro = intent.getBooleanExtra("fromIntro", false);
if (fromIntro) {
preferences.edit().putLong("intro_crashed_time", 0).commit();
}
if (Math.abs(crashed_time - System.currentTimeMillis()) >= 60 * 2 * 1000 && intent != null && !fromIntro) {
preferences = ApplicationLoader.applicationContext.getSharedPreferences("logininfo2", MODE_PRIVATE);
Map<String, ?> state = preferences.getAll();
if (state.isEmpty()) {
Intent intent2 = new Intent(this, IntroActivity.class);
@ -627,7 +632,9 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
return;
}
UserConfig.appLocked = true;
if (PhotoViewer.getInstance().isVisible()) {
if (SecretMediaViewer.getInstance().isVisible()) {
SecretMediaViewer.getInstance().closePhoto(false, false);
} else if (PhotoViewer.getInstance().isVisible()) {
PhotoViewer.getInstance().closePhoto(false, true);
} else if (ArticleViewer.getInstance().isVisible()) {
ArticleViewer.getInstance().close(false, true);
@ -903,7 +910,8 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
if (!(parcelable instanceof Uri)) {
parcelable = Uri.parse(parcelable.toString());
}
String path = AndroidUtilities.getPath((Uri) parcelable);
Uri uri = (Uri) parcelable;
String path = AndroidUtilities.getPath(uri);
String originalPath = parcelable.toString();
if (originalPath == null) {
originalPath = path;
@ -918,6 +926,12 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
}
documentsPathsArray.add(path);
documentsOriginalPathsArray.add(originalPath);
} else {
if (documentsUrisArray == null) {
documentsUrisArray = new ArrayList<>();
}
documentsUrisArray.add(uri);
documentsMimeType = type;
}
}
}
@ -1218,7 +1232,9 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
}
actionBarLayout.presentFragment(fragment, removeLast, true, true);
pushOpened = true;
if (PhotoViewer.getInstance().isVisible()) {
if (SecretMediaViewer.getInstance().isVisible()) {
SecretMediaViewer.getInstance().closePhoto(false, false);
} else if (PhotoViewer.getInstance().isVisible()) {
PhotoViewer.getInstance().closePhoto(false, true);
} else if (ArticleViewer.getInstance().isVisible()) {
ArticleViewer.getInstance().close(false, true);
@ -1373,7 +1389,9 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
removeLast = actionBarLayout.fragmentsStack.size() > 1 && actionBarLayout.fragmentsStack.get(actionBarLayout.fragmentsStack.size() - 1) instanceof DialogsActivity;
}
actionBarLayout.presentFragment(fragment, removeLast, true, true);
if (PhotoViewer.getInstance().isVisible()) {
if (SecretMediaViewer.getInstance().isVisible()) {
SecretMediaViewer.getInstance().closePhoto(false, false);
} else if (PhotoViewer.getInstance().isVisible()) {
PhotoViewer.getInstance().closePhoto(false, true);
} else if (ArticleViewer.getInstance().isVisible()) {
ArticleViewer.getInstance().close(false, true);
@ -1711,30 +1729,25 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
ChatActivity fragment = new ChatActivity(args);
if (videoPath != null) {
if (Build.VERSION.SDK_INT >= 16) {
if (AndroidUtilities.isTablet()) {
if (tabletFullSize) {
actionBarLayout.presentFragment(fragment, false, true, false);
} else {
rightActionBarLayout.removeAllFragments();
rightActionBarLayout.addFragmentToStack(fragment);
rightActionBarLayout.setVisibility(View.VISIBLE);
rightActionBarLayout.showLastFragment();
}
if (AndroidUtilities.isTablet()) {
if (tabletFullSize) {
actionBarLayout.presentFragment(fragment, false, true, false);
} else {
actionBarLayout.addFragmentToStack(fragment, dialogsFragment != null ? actionBarLayout.fragmentsStack.size() - 1 : actionBarLayout.fragmentsStack.size());
}
if (!fragment.openVideoEditor(videoPath, dialogsFragment != null, false) && !AndroidUtilities.isTablet()) {
if (dialogsFragment != null) {
dialogsFragment.finishFragment(true);
} else {
actionBarLayout.showLastFragment();
}
rightActionBarLayout.removeAllFragments();
rightActionBarLayout.addFragmentToStack(fragment);
rightActionBarLayout.setVisibility(View.VISIBLE);
rightActionBarLayout.showLastFragment();
}
} else {
actionBarLayout.presentFragment(fragment, dialogsFragment != null, dialogsFragment == null, true);
SendMessagesHelper.prepareSendingVideo(videoPath, 0, 0, 0, 0, null, dialog_id, null, null);
actionBarLayout.addFragmentToStack(fragment, dialogsFragment != null ? actionBarLayout.fragmentsStack.size() - 1 : actionBarLayout.fragmentsStack.size());
}
if (!fragment.openVideoEditor(videoPath, dialogsFragment != null, false) && !AndroidUtilities.isTablet()) {
if (dialogsFragment != null) {
dialogsFragment.finishFragment(true);
} else {
actionBarLayout.showLastFragment();
}
}
} else {
actionBarLayout.presentFragment(fragment, dialogsFragment != null, dialogsFragment == null, true);
@ -1746,7 +1759,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
captions.add(sendingText);
sendingText = null;
}
SendMessagesHelper.prepareSendingPhotos(null, photoPathsArray, dialog_id, null, captions, null, null, false);
SendMessagesHelper.prepareSendingPhotos(null, photoPathsArray, dialog_id, null, captions, null, null, false, null);
}
if (sendingText != null) {
@ -1952,7 +1965,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
@Override
protected void onDestroy() {
PhotoViewer.getInstance().destroyPhotoViewer();
SecretPhotoViewer.getInstance().destroyPhotoViewer();
SecretMediaViewer.getInstance().destroyPhotoViewer();
ArticleViewer.getInstance().destroyArticleViewer();
StickerPreviewViewer.getInstance().destroy();
PipRoundVideoView pipRoundVideoView = PipRoundVideoView.getInstance();
@ -1980,11 +1993,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
try {
if (onGlobalLayoutListener != null) {
final View view = getWindow().getDecorView().getRootView();
if (Build.VERSION.SDK_INT < 16) {
view.getViewTreeObserver().removeGlobalOnLayoutListener(onGlobalLayoutListener);
} else {
view.getViewTreeObserver().removeOnGlobalLayoutListener(onGlobalLayoutListener);
}
view.getViewTreeObserver().removeOnGlobalLayoutListener(onGlobalLayoutListener);
}
} catch (Exception e) {
FileLog.e(e);
@ -2512,7 +2521,9 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
finish();
return;
}
if (PhotoViewer.getInstance().isVisible()) {
if (SecretMediaViewer.getInstance().isVisible()) {
SecretMediaViewer.getInstance().closePhoto(true, false);
} else if (PhotoViewer.getInstance().isVisible()) {
PhotoViewer.getInstance().closePhoto(true, false);
} else if (ArticleViewer.getInstance().isVisible()) {
ArticleViewer.getInstance().close(true, false);
@ -2588,7 +2599,10 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
@Override
public boolean onPreIme() {
if (PhotoViewer.getInstance().isVisible()) {
if (SecretMediaViewer.getInstance().isVisible()) {
SecretMediaViewer.getInstance().closePhoto(true, false);
return true;
} else if (PhotoViewer.getInstance().isVisible()) {
PhotoViewer.getInstance().closePhoto(true, false);
return true;
} else if (ArticleViewer.getInstance().isVisible()) {
@ -2599,7 +2613,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
}
@Override
public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) {
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && !UserConfig.isWaitingForPasscodeEnter) {
if (PhotoViewer.getInstance().isVisible()) {
return super.onKeyUp(keyCode, event);

View File

@ -243,11 +243,7 @@ public class ManageSpaceActivity extends Activity implements ActionBarLayout.Act
public void onGlobalLayout() {
needLayout();
if (actionBarLayout != null) {
if (Build.VERSION.SDK_INT < 16) {
actionBarLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
actionBarLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
actionBarLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
}
});

View File

@ -830,8 +830,9 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No
ArrayList<MessageObject> arr = (ArrayList<MessageObject>) args[1];
boolean enc = ((int) dialog_id) == 0;
boolean updated = false;
for (MessageObject obj : arr) {
if (obj.messageOwner.media == null) {
for (int a = 0; a < arr.size(); a++) {
MessageObject obj = arr.get(a);
if (obj.messageOwner.media == null || obj.isSecretPhoto()) {
continue;
}
int type = SharedMediaQuery.getMediaType(obj.messageOwner);
@ -1252,7 +1253,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No
}
}
} else if (!cell.isLoading()) {
FileLoader.getInstance().loadFile(cell.getMessage().getDocument(), false, false);
FileLoader.getInstance().loadFile(cell.getMessage().getDocument(), false, 0);
cell.updateFileExistIcon();
} else {
FileLoader.getInstance().cancelLoadFile(cell.getMessage().getDocument());
@ -1264,7 +1265,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No
TLRPC.WebPage webPage = message.messageOwner.media.webpage;
String link = null;
if (webPage != null && !(webPage instanceof TLRPC.TL_webPageEmpty)) {
if (Build.VERSION.SDK_INT >= 16 && webPage.embed_url != null && webPage.embed_url.length() != 0) {
if (webPage.embed_url != null && webPage.embed_url.length() != 0) {
openWebView(webPage);
return;
} else {

View File

@ -27,7 +27,6 @@ import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.R;
import org.telegram.messenger.VideoEditedInfo;
import org.telegram.messenger.support.widget.LinearLayoutManager;
import org.telegram.messenger.support.widget.RecyclerView;
import org.telegram.tgnet.TLRPC;
@ -48,8 +47,7 @@ import java.util.HashMap;
public class PhotoAlbumPickerActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate {
public interface PhotoAlbumPickerActivityDelegate {
void didSelectPhotos(ArrayList<String> photos, ArrayList<String> captions, ArrayList<MediaController.PhotoEntry> videos, ArrayList<ArrayList<TLRPC.InputDocument>> masks, ArrayList<MediaController.SearchImage> webPhotos);
void didSelectVideo(String path, VideoEditedInfo info, long estimatedSize, long estimatedDuration, String caption);
void didSelectPhotos(ArrayList<String> photos, ArrayList<String> captions, ArrayList<Integer> ttls, ArrayList<MediaController.PhotoEntry> videos, ArrayList<ArrayList<TLRPC.InputDocument>> masks, ArrayList<MediaController.SearchImage> webPhotos);
void startPhotoSelectActivity();
}
@ -287,6 +285,7 @@ public class PhotoAlbumPickerActivity extends BaseFragment implements Notificati
ArrayList<String> photos = new ArrayList<>();
ArrayList<MediaController.PhotoEntry> videos = new ArrayList<>();
ArrayList<String> captions = new ArrayList<>();
ArrayList<Integer> ttls = new ArrayList<>();
ArrayList<ArrayList<TLRPC.InputDocument>> masks = new ArrayList<>();
for (HashMap.Entry<Integer, MediaController.PhotoEntry> entry : selectedPhotos.entrySet()) {
MediaController.PhotoEntry photoEntry = entry.getValue();
@ -296,10 +295,12 @@ public class PhotoAlbumPickerActivity extends BaseFragment implements Notificati
photos.add(photoEntry.imagePath);
captions.add(photoEntry.caption != null ? photoEntry.caption.toString() : null);
masks.add(!photoEntry.stickers.isEmpty() ? new ArrayList<>(photoEntry.stickers) : null);
ttls.add(photoEntry.ttl);
} else if (photoEntry.path != null) {
photos.add(photoEntry.path);
captions.add(photoEntry.caption != null ? photoEntry.caption.toString() : null);
masks.add(!photoEntry.stickers.isEmpty() ? new ArrayList<>(photoEntry.stickers) : null);
ttls.add(photoEntry.ttl);
}
}
ArrayList<MediaController.SearchImage> webPhotos = new ArrayList<>();
@ -311,6 +312,7 @@ public class PhotoAlbumPickerActivity extends BaseFragment implements Notificati
photos.add(searchImage.imagePath);
captions.add(searchImage.caption != null ? searchImage.caption.toString() : null);
masks.add(!searchImage.stickers.isEmpty() ? new ArrayList<>(searchImage.stickers) : null);
ttls.add(searchImage.ttl);
} else {
webPhotos.add(searchImage);
}
@ -343,7 +345,7 @@ public class PhotoAlbumPickerActivity extends BaseFragment implements Notificati
MessagesStorage.getInstance().putWebRecent(recentGifImages);
}
delegate.didSelectPhotos(photos, captions, videos, masks, webPhotos);
delegate.didSelectPhotos(photos, captions, ttls, videos, masks, webPhotos);
}
private void fixLayout() {
@ -401,12 +403,6 @@ public class PhotoAlbumPickerActivity extends BaseFragment implements Notificati
sendSelectedPhotos();
}
}
@Override
public void didSelectVideo(String path, VideoEditedInfo info, long estimatedSize, long estimatedDuration, String caption) {
removeSelfFromStack();
delegate.didSelectVideo(path, info, estimatedSize, estimatedDuration, caption);
}
});
presentFragment(fragment);
}

View File

@ -77,10 +77,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen
public interface PhotoPickerActivityDelegate {
void selectedPhotosChanged();
void actionButtonPressed(boolean canceled);
void didSelectVideo(String path, VideoEditedInfo info, long estimatedSize, long estimatedDuration, String caption);
}
private int type;
@ -298,65 +295,24 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen
listView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
/*if (selectedAlbum != null && selectedAlbum.isVideo) {
if (position < 0 || position >= selectedAlbum.photos.size()) {
return;
}
String path = selectedAlbum.photos.get(position).path;
if (Build.VERSION.SDK_INT >= 16) {
Bundle args = new Bundle();
args.putString("videoPath", path);
VideoEditorActivity fragment = new VideoEditorActivity(args);
fragment.setDelegate(new VideoEditorActivity.VideoEditorActivityDelegate() {
@Override
public void didFinishEditVideo(String videoPath, long startTime, long endTime, int resultWidth, int resultHeight, int rotationValue, int originalWidth, int originalHeight, int bitrate, long estimatedSize, long estimatedDuration, String caption) {
removeSelfFromStack();
VideoEditedInfo videoEditedInfo = new VideoEditedInfo();
videoEditedInfo.startTime = startTime;
videoEditedInfo.endTime = endTime;
videoEditedInfo.rotationValue = rotationValue;
videoEditedInfo.originalWidth = originalWidth;
videoEditedInfo.originalHeight = originalHeight;
videoEditedInfo.bitrate = bitrate;
videoEditedInfo.resultWidth = resultWidth;
videoEditedInfo.resultHeight = resultHeight;
videoEditedInfo.originalPath = videoPath;
videoEditedInfo.muted = videoEditedInfo.bitrate == -1;
delegate.didSelectVideo(videoPath, videoEditedInfo, estimatedSize, estimatedDuration, caption);
}
});
if (!fragment.onFragmentCreate()) {
delegate.didSelectVideo(path, null, 0, 0, null);
finishFragment();
} else if (parentLayout.presentFragment(fragment, false, false, true)) {
fragment.setParentChatActivity(chatActivity);
}
ArrayList<Object> arrayList;
if (selectedAlbum != null) {
arrayList = (ArrayList) selectedAlbum.photos;
} else {
if (searchResult.isEmpty() && lastSearchString == null) {
arrayList = (ArrayList) recentImages;
} else {
delegate.didSelectVideo(path, null, 0, 0, null);
finishFragment();
arrayList = (ArrayList) searchResult;
}
} else {*/
ArrayList<Object> arrayList;
if (selectedAlbum != null) {
arrayList = (ArrayList) selectedAlbum.photos;
} else {
if (searchResult.isEmpty() && lastSearchString == null) {
arrayList = (ArrayList) recentImages;
} else {
arrayList = (ArrayList) searchResult;
}
}
if (position < 0 || position >= arrayList.size()) {
return;
}
if (searchItem != null) {
AndroidUtilities.hideKeyboard(searchItem.getSearchField());
}
PhotoViewer.getInstance().setParentActivity(getParentActivity());
PhotoViewer.getInstance().openPhotoForSelect(arrayList, position, singlePhoto ? 1 : 0, PhotoPickerActivity.this, chatActivity);
//}
}
if (position < 0 || position >= arrayList.size()) {
return;
}
if (searchItem != null) {
AndroidUtilities.hideKeyboard(searchItem.getSearchField());
}
PhotoViewer.getInstance().setParentActivity(getParentActivity());
PhotoViewer.getInstance().openPhotoForSelect(arrayList, position, singlePhoto ? 1 : 0, PhotoPickerActivity.this, chatActivity);
}
});
@ -1172,9 +1128,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen
MediaController.PhotoEntry photoEntry = selectedAlbum.photos.get(index);
if (selectedPhotos.containsKey(photoEntry.imageId)) {
selectedPhotos.remove(photoEntry.imageId);
photoEntry.imagePath = null;
photoEntry.thumbPath = null;
photoEntry.stickers.clear();
photoEntry.reset();
updatePhotoAtIndex(index);
} else {
selectedPhotos.put(photoEntry.imageId, photoEntry);

File diff suppressed because it is too large Load Diff

View File

@ -196,6 +196,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter.
private int sectionRow;
private int userSectionRow;
private int userInfoRow;
private int userInfoDetailedRow;
private int membersSectionRow;
private int membersEndRow;
private int loadMoreMembersRow;
@ -1256,7 +1257,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter.
});
showDialog(builder.create());
return true;
} else if (position == channelInfoRow || position == userInfoRow) {
} else if (position == channelInfoRow || position == userInfoRow || position == userInfoDetailedRow) {
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setItems(new CharSequence[]{LocaleController.getString("Copy", R.string.Copy)}, new DialogInterface.OnClickListener() {
@Override
@ -1869,9 +1870,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter.
if (playProfileAnimation && allowProfileAnimation) {
final AnimatorSet animatorSet = new AnimatorSet();
animatorSet.setDuration(180);
if (Build.VERSION.SDK_INT > 15) {
listView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
listView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
ActionBarMenu menu = actionBar.createMenu();
if (menu.getItem(10) == null) {
if (animatingItem == null) {
@ -1955,9 +1954,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter.
animatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (Build.VERSION.SDK_INT > 15) {
listView.setLayerType(View.LAYER_TYPE_NONE, null);
}
listView.setLayerType(View.LAYER_TYPE_NONE, null);
if (animatingItem != null) {
ActionBarMenu menu = actionBar.createMenu();
menu.clearItems();
@ -2185,6 +2182,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter.
emptyRow = -1;
phoneRow = -1;
userInfoRow = -1;
userInfoDetailedRow = -1;
userSectionRow = -1;
sectionRow = -1;
sharedMediaRow = -1;
@ -2211,20 +2209,24 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter.
if (user_id != 0) {
TLRPC.User user = MessagesController.getInstance().getUser(user_id);
emptyRow = rowCount++;
if (user == null || !user.bot) {
if ((user == null || !user.bot) && !TextUtils.isEmpty(user.phone)) {
phoneRow = rowCount++;
}
if (user != null && user.username != null && user.username.length() > 0) {
usernameRow = rowCount++;
}
TLRPC.TL_userFull userFull = MessagesController.getInstance().getUserFull(user.id);
String about = userFull != null ? userFull.about : null;
boolean hasUsername = user != null && !TextUtils.isEmpty(user.username);
if (about != null) {
userSectionRow = rowCount++;
userInfoRow = rowCount++;
} else {
userSectionRow = -1;
userInfoRow = -1;
if (phoneRow != -1) {
userSectionRow = rowCount++;
}
if (hasUsername) {
userInfoRow = rowCount++;
} else {
userInfoDetailedRow = rowCount++;
}
}
if (hasUsername) {
usernameRow = rowCount++;
}
sectionRow = rowCount++;
if (user_id != UserConfig.getClientUserId()) {
@ -2706,6 +2708,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter.
break;
case 2:
TextDetailCell textDetailCell = (TextDetailCell) holder.itemView;
textDetailCell.setMultiline(false);
if (i == phoneRow) {
String text;
final TLRPC.User user = MessagesController.getInstance().getUser(user_id);
@ -2714,7 +2717,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter.
} else {
text = LocaleController.getString("NumberUnknown", R.string.NumberUnknown);
}
textDetailCell.setTextAndValueAndIcon(text, LocaleController.getString("PhoneMobile", R.string.PhoneMobile), R.drawable.profile_phone);
textDetailCell.setTextAndValueAndIcon(text, LocaleController.getString("PhoneMobile", R.string.PhoneMobile), R.drawable.profile_phone, 0);
} else if (i == usernameRow) {
String text;
final TLRPC.User user = MessagesController.getInstance().getUser(user_id);
@ -2723,15 +2726,24 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter.
} else {
text = "-";
}
textDetailCell.setTextAndValue(text, LocaleController.getString("Username", R.string.Username));
if (phoneRow == -1 && userInfoRow == -1 && userInfoDetailedRow == -1) {
textDetailCell.setTextAndValueAndIcon(text, LocaleController.getString("Username", R.string.Username), R.drawable.profile_info, 11);
} else {
textDetailCell.setTextAndValue(text, LocaleController.getString("Username", R.string.Username));
}
} else if (i == channelNameRow) {
String text;
if (currentChat != null && currentChat.username != null && currentChat.username.length() != 0) {
if (currentChat != null && !TextUtils.isEmpty(currentChat.username)) {
text = "@" + currentChat.username;
} else {
text = "-";
}
textDetailCell.setTextAndValue(text, MessagesController.getInstance().linkPrefix + "/" + currentChat.username);
} else if (i == userInfoDetailedRow) {
TLRPC.TL_userFull userFull = MessagesController.getInstance().getUserFull(user_id);
String about = userFull != null ? userFull.about : null;
textDetailCell.setMultiline(true);
textDetailCell.setTextAndValueAndIcon(about, LocaleController.getString("UserBio", R.string.UserBio), R.drawable.profile_info, 11);
}
break;
case 3:
@ -2892,13 +2904,13 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter.
if (i == userInfoRow) {
TLRPC.TL_userFull userFull = MessagesController.getInstance().getUserFull(user_id);
String about = userFull != null ? userFull.about : null;
aboutLinkCell.setTextAndIcon(about, R.drawable.profile_info);
aboutLinkCell.setTextAndIcon(about, R.drawable.profile_info, false);
} else if (i == channelInfoRow) {
String text = info.about;
while (text.contains("\n\n\n")) {
text = text.replace("\n\n\n", "\n\n");
}
aboutLinkCell.setTextAndIcon(text, R.drawable.profile_info);
aboutLinkCell.setTextAndIcon(text, R.drawable.profile_info, true);
}
break;
}
@ -2909,7 +2921,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter.
int i = holder.getAdapterPosition();
if (user_id != 0) {
return i == phoneRow || i == settingsTimerRow || i == settingsKeyRow || i == settingsNotificationsRow ||
i == sharedMediaRow || i == startSecretChatRow || i == usernameRow || i == userInfoRow || i == groupsInCommonRow;
i == sharedMediaRow || i == startSecretChatRow || i == usernameRow || i == userInfoRow || i == groupsInCommonRow || i == userInfoDetailedRow;
} else if (chat_id != 0) {
return i == convertRow || i == settingsNotificationsRow || i == sharedMediaRow || i > emptyRowChat2 && i < membersEndRow ||
i == addMemberRow || i == channelNameRow || i == leaveChannelRow || i == channelInfoRow || i == membersRow;
@ -2928,7 +2940,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter.
return 0;
} else if (i == sectionRow || i == userSectionRow) {
return 1;
} else if (i == phoneRow || i == usernameRow || i == channelNameRow) {
} else if (i == phoneRow || i == usernameRow || i == channelNameRow || i == userInfoDetailedRow) {
return 2;
} else if (i == leaveChannelRow || i == sharedMediaRow || i == settingsTimerRow || i == settingsNotificationsRow || i == startSecretChatRow || i == settingsKeyRow || i == convertRow || i == addMemberRow || i == groupsInCommonRow || i == membersRow) {
return 3;

View File

@ -114,7 +114,7 @@ public class ProxySettingsActivity extends BaseFragment implements NotificationC
@Override
public View createView(Context context) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
useProxySettings = preferences.getBoolean("proxy_enabled", false);
useProxyForCalls = preferences.getBoolean("proxy_enabled_calls", false);
@ -198,8 +198,10 @@ public class ProxySettingsActivity extends BaseFragment implements NotificationC
public void onClick(View v) {
useProxySettings = !useProxySettings;
checkCell1.setChecked(useProxySettings);
if(!useProxySettings)
if(!useProxySettings){
useForCallsCell.setChecked(false);
preferences.edit().putBoolean("proxy_enabled_calls", false).apply();
}
useForCallsCell.setEnabled(useProxySettings);
}
});

File diff suppressed because it is too large Load Diff

View File

@ -1,379 +0,0 @@
/*
* This is the source code of Telegram for Android v. 3.x.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-2017.
*/
package org.telegram.ui;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ImageLoader;
import org.telegram.messenger.ImageReceiver;
import org.telegram.messenger.MessageObject;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.R;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.Components.LayoutHelper;
import java.io.File;
import java.util.ArrayList;
public class SecretPhotoViewer implements NotificationCenter.NotificationCenterDelegate {
private class FrameLayoutDrawer extends FrameLayout {
public FrameLayoutDrawer(Context context) {
super(context);
setWillNotDraw(false);
}
@Override
protected void onDraw(Canvas canvas) {
getInstance().onDraw(canvas);
}
}
private class SecretDeleteTimer extends FrameLayout {
private String currentInfoString;
private int infoWidth;
private TextPaint infoPaint = null;
private StaticLayout infoLayout = null;
private Paint deleteProgressPaint;
private RectF deleteProgressRect = new RectF();
private Drawable drawable = null;
public SecretDeleteTimer(Context context) {
super(context);
setWillNotDraw(false);
infoPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
infoPaint.setTextSize(AndroidUtilities.dp(15));
infoPaint.setColor(0xffffffff);
deleteProgressPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
deleteProgressPaint.setColor(0xffe6e6e6);
drawable = getResources().getDrawable(R.drawable.circle1);
}
private void updateSecretTimeText() {
if (currentMessageObject == null) {
return;
}
String str = currentMessageObject.getSecretTimeString();
if (str == null) {
return;
}
if (currentInfoString == null || !currentInfoString.equals(str)) {
currentInfoString = str;
infoWidth = (int)Math.ceil(infoPaint.measureText(currentInfoString));
CharSequence str2 = TextUtils.ellipsize(currentInfoString, infoPaint, infoWidth, TextUtils.TruncateAt.END);
infoLayout = new StaticLayout(str2, infoPaint, infoWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
invalidate();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
deleteProgressRect.set(getMeasuredWidth() - AndroidUtilities.dp(30), AndroidUtilities.dp(2), getMeasuredWidth() - AndroidUtilities.dp(2), AndroidUtilities.dp(30));
}
@Override
protected void onDraw(Canvas canvas) {
if (currentMessageObject == null || currentMessageObject.messageOwner.destroyTime == 0) {
return;
}
if (drawable != null) {
drawable.setBounds(getMeasuredWidth() - AndroidUtilities.dp(32), 0, getMeasuredWidth(), AndroidUtilities.dp(32));
drawable.draw(canvas);
}
long msTime = System.currentTimeMillis() + ConnectionsManager.getInstance().getTimeDifference() * 1000;
float progress = Math.max(0, (long)currentMessageObject.messageOwner.destroyTime * 1000 - msTime) / (currentMessageObject.messageOwner.ttl * 1000.0f);
canvas.drawArc(deleteProgressRect, -90, -360 * progress, true, deleteProgressPaint);
if (progress != 0) {
int offset = AndroidUtilities.dp(2);
invalidate((int)deleteProgressRect.left - offset, (int)deleteProgressRect.top - offset, (int)deleteProgressRect.right + offset * 2, (int)deleteProgressRect.bottom + offset * 2);
}
updateSecretTimeText();
if (infoLayout != null) {
canvas.save();
canvas.translate(getMeasuredWidth() - AndroidUtilities.dp(38) - infoWidth, AndroidUtilities.dp(7));
infoLayout.draw(canvas);
canvas.restore();
}
}
}
private Activity parentActivity;
private WindowManager.LayoutParams windowLayoutParams;
private FrameLayout windowView;
private FrameLayoutDrawer containerView;
private ImageReceiver centerImage = new ImageReceiver();
private SecretDeleteTimer secretDeleteTimer;
private boolean isVisible = false;
private MessageObject currentMessageObject = null;
@SuppressLint("StaticFieldLeak")
private static volatile SecretPhotoViewer Instance = null;
public static SecretPhotoViewer getInstance() {
SecretPhotoViewer localInstance = Instance;
if (localInstance == null) {
synchronized (PhotoViewer.class) {
localInstance = Instance;
if (localInstance == null) {
Instance = localInstance = new SecretPhotoViewer();
}
}
}
return localInstance;
}
@SuppressWarnings("unchecked")
@Override
public void didReceivedNotification(int id, Object... args) {
if (id == NotificationCenter.messagesDeleted) {
if (currentMessageObject == null) {
return;
}
int channelId = (Integer) args[1];
if (channelId != 0) {
return;
}
ArrayList<Integer> markAsDeletedMessages = (ArrayList<Integer>)args[0];
if (markAsDeletedMessages.contains(currentMessageObject.getId())) {
closePhoto();
}
} else if (id == NotificationCenter.didCreatedNewDeleteTask) {
if (currentMessageObject == null || secretDeleteTimer == null) {
return;
}
SparseArray<ArrayList<Integer>> mids = (SparseArray<ArrayList<Integer>>)args[0];
for(int i = 0; i < mids.size(); i++) {
int key = mids.keyAt(i);
ArrayList<Integer> arr = mids.get(key);
for (Integer mid : arr) {
if (currentMessageObject.getId() == mid) {
currentMessageObject.messageOwner.destroyTime = key;
secretDeleteTimer.invalidate();
return;
}
}
}
}
}
public void setParentActivity(Activity activity) {
if (parentActivity == activity) {
return;
}
parentActivity = activity;
windowView = new FrameLayout(activity);
windowView.setBackgroundColor(0xff000000);
windowView.setFocusable(true);
windowView.setFocusableInTouchMode(true);
if (Build.VERSION.SDK_INT >= 23) {
windowView.setFitsSystemWindows(true);
}
containerView = new FrameLayoutDrawer(activity);
containerView.setFocusable(false);
windowView.addView(containerView);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams)containerView.getLayoutParams();
layoutParams.width = LayoutHelper.MATCH_PARENT;
layoutParams.height = LayoutHelper.MATCH_PARENT;
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
containerView.setLayoutParams(layoutParams);
containerView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_POINTER_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
closePhoto();
}
return true;
}
});
secretDeleteTimer = new SecretDeleteTimer(activity);
containerView.addView(secretDeleteTimer);
layoutParams = (FrameLayout.LayoutParams)secretDeleteTimer.getLayoutParams();
layoutParams.gravity = Gravity.TOP | Gravity.RIGHT;
layoutParams.width = AndroidUtilities.dp(100);
layoutParams.height = AndroidUtilities.dp(32);
layoutParams.rightMargin = AndroidUtilities.dp(19);
layoutParams.topMargin = AndroidUtilities.dp(19);
secretDeleteTimer.setLayoutParams(layoutParams);
windowLayoutParams = new WindowManager.LayoutParams();
windowLayoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
windowLayoutParams.format = PixelFormat.TRANSLUCENT;
windowLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
windowLayoutParams.gravity = Gravity.TOP;
windowLayoutParams.type = WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
windowLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
centerImage.setParentView(containerView);
}
public void openPhoto(MessageObject messageObject) {
if (parentActivity == null || messageObject == null || messageObject.messageOwner.media == null || messageObject.messageOwner.media.photo == null) {
return;
}
NotificationCenter.getInstance().addObserver(this, NotificationCenter.messagesDeleted);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.didCreatedNewDeleteTask);
TLRPC.PhotoSize sizeFull = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, AndroidUtilities.getPhotoSize());
int size = sizeFull.size;
if (size == 0) {
size = -1;
}
BitmapDrawable drawable = ImageLoader.getInstance().getImageFromMemory(sizeFull.location, null, null);
if (drawable == null) {
File file = FileLoader.getPathToAttach(sizeFull);
Bitmap bitmap = null;
BitmapFactory.Options options = null;
if (Build.VERSION.SDK_INT < 21) {
options = new BitmapFactory.Options();
options.inDither = true;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inPurgeable = true;
options.inSampleSize = 1;
options.inMutable = true;
}
try {
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
} catch (Throwable e) {
FileLog.e(e);
}
if (bitmap != null) {
drawable = new BitmapDrawable(bitmap);
ImageLoader.getInstance().putImageToCache(drawable, sizeFull.location.volume_id + "_" + sizeFull.location.local_id);
}
}
if (drawable != null) {
centerImage.setImageBitmap(drawable);
} else {
centerImage.setImage(sizeFull.location, null, null, size, null, false);
}
currentMessageObject = messageObject;
AndroidUtilities.lockOrientation(parentActivity);
try {
if (windowView.getParent() != null) {
WindowManager wm = (WindowManager) parentActivity.getSystemService(Context.WINDOW_SERVICE);
wm.removeView(windowView);
}
} catch (Exception e) {
FileLog.e(e);
}
WindowManager wm = (WindowManager) parentActivity.getSystemService(Context.WINDOW_SERVICE);
wm.addView(windowView, windowLayoutParams);
secretDeleteTimer.invalidate();
isVisible = true;
}
public boolean isVisible() {
return isVisible;
}
public void closePhoto() {
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.messagesDeleted);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didCreatedNewDeleteTask);
if (parentActivity == null) {
return;
}
currentMessageObject = null;
isVisible = false;
AndroidUtilities.unlockOrientation(parentActivity);
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
centerImage.setImageBitmap((Bitmap)null);
}
});
try {
if (windowView.getParent() != null) {
WindowManager wm = (WindowManager) parentActivity.getSystemService(Context.WINDOW_SERVICE);
wm.removeView(windowView);
}
} catch (Exception e) {
FileLog.e(e);
}
}
public void destroyPhotoViewer() {
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.messagesDeleted);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didCreatedNewDeleteTask);
isVisible = false;
currentMessageObject = null;
if (parentActivity == null || windowView == null) {
return;
}
try {
if (windowView.getParent() != null) {
WindowManager wm = (WindowManager) parentActivity.getSystemService(Context.WINDOW_SERVICE);
wm.removeViewImmediate(windowView);
}
windowView = null;
} catch (Exception e) {
FileLog.e(e);
}
Instance = null;
}
private void onDraw(Canvas canvas) {
canvas.save();
canvas.translate(containerView.getWidth() / 2, containerView.getHeight() / 2);
Bitmap bitmap = centerImage.getBitmap();
if (bitmap != null) {
int bitmapWidth = bitmap.getWidth();
int bitmapHeight = bitmap.getHeight();
float scaleX = (float) containerView.getWidth() / (float) bitmapWidth;
float scaleY = (float) containerView.getHeight() / (float) bitmapHeight;
float scale = scaleX > scaleY ? scaleY : scaleX;
int width = (int) (bitmapWidth * scale);
int height = (int) (bitmapHeight * scale);
centerImage.setImageCoords(-width / 2, -height / 2, width, height);
centerImage.draw(canvas);
}
canvas.restore();
}
}

View File

@ -130,6 +130,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
private int numberSectionRow;
private int numberRow;
private int usernameRow;
private int bioRow;
private int settingsSectionRow;
private int settingsSectionRow2;
private int enableAnimationsRow;
@ -236,6 +237,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
};
NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.featuredStickersDidLoaded);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.userInfoDidLoaded);
rowCount = 0;
overscrollRow = rowCount++;
@ -243,6 +245,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
numberSectionRow = rowCount++;
numberRow = rowCount++;
usernameRow = rowCount++;
bioRow = rowCount++;
settingsSectionRow = rowCount++;
settingsSectionRow2 = rowCount++;
notificationRow = rowCount++;
@ -296,6 +299,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
MessagesController.getInstance().cancelLoadFullUser(UserConfig.getClientUserId());
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.featuredStickersDidLoaded);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.userInfoDidLoaded);
avatarUpdater.clear();
}
@ -375,10 +379,17 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
listView = new RecyclerListView(context);
listView.setVerticalScrollBarEnabled(false);
listView.setLayoutManager(layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
listView.setLayoutManager(layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) {
@Override
public boolean supportsPredictiveItemAnimations() {
return false;
}
});
listView.setGlowColor(Theme.getColor(Theme.key_avatar_backgroundActionBarBlue));
frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
listView.setAdapter(listAdapter);
listView.setItemAnimator(null);
listView.setLayoutAnimation(null);
listView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
@Override
public void onItemClick(View view, final int position) {
@ -547,6 +558,11 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
showDialog(builder.create());
} else if (position == usernameRow) {
presentFragment(new ChangeUsernameActivity());
} else if (position == bioRow) {
TLRPC.TL_userFull userFull = MessagesController.getInstance().getUserFull(UserConfig.getClientUserId());
if (userFull != null) {
presentFragment(new ChangeBioActivity());
}
} else if (position == numberRow) {
presentFragment(new ChangePhoneHelpActivity());
} else if (position == stickersRow) {
@ -1003,6 +1019,11 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
if (listAdapter != null) {
listAdapter.notifyItemChanged(stickersRow);
}
} else if (id == NotificationCenter.userInfoDidLoaded) {
Integer uid = (Integer) args[0];
if (uid == UserConfig.getClientUserId()) {
listAdapter.notifyItemChanged(bioRow);
}
}
}
@ -1286,12 +1307,23 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
} else if (position == usernameRow) {
TLRPC.User user = UserConfig.getCurrentUser();
String value;
if (user != null && user.username != null && user.username.length() != 0) {
if (user != null && !TextUtils.isEmpty(user.username)) {
value = "@" + user.username;
} else {
value = LocaleController.getString("UsernameEmpty", R.string.UsernameEmpty);
}
textCell.setTextAndValue(value, LocaleController.getString("Username", R.string.Username), false);
textCell.setTextAndValue(value, LocaleController.getString("Username", R.string.Username), true);
} else if (position == bioRow) {
TLRPC.TL_userFull userFull = MessagesController.getInstance().getUserFull(UserConfig.getClientUserId());
String value;
if (userFull == null) {
value = LocaleController.getString("Loading", R.string.Loading);
} else if (userFull != null && !TextUtils.isEmpty(userFull.about)) {
value = userFull.about;
} else {
value = LocaleController.getString("UserBioEmpty", R.string.UserBioEmpty);
}
textCell.setTextAndValue(value, LocaleController.getString("UserBio", R.string.UserBio), false);
}
break;
}
@ -1303,7 +1335,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
int position = holder.getAdapterPosition();
return position == textSizeRow || position == enableAnimationsRow || position == notificationRow || position == backgroundRow || position == numberRow ||
position == askQuestionRow || position == sendLogsRow || position == sendByEnterRow || position == autoplayGifsRow || position == privacyRow ||
position == clearLogsRow || position == languageRow || position == usernameRow ||
position == clearLogsRow || position == languageRow || position == usernameRow || position == bioRow ||
position == switchBackendButtonRow || position == telegramFaqRow || position == contactsSortRow || position == contactsReimportRow || position == saveToGalleryRow ||
position == stickersRow || position == raiseToSpeakRow || position == privacyPolicyRow || position == customTabsRow || position == directShareRow || position == versionRow ||
position == emojiRow || position == dataRow || position == themeRow || position == dumpCallStatsRow;
@ -1382,7 +1414,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
return 2;
} else if (position == versionRow) {
return 5;
} else if (position == numberRow || position == usernameRow) {
} else if (position == numberRow || position == usernameRow || position == bioRow) {
return 6;
} else if (position == settingsSectionRow2 || position == messagesSectionRow2 || position == supportSectionRow2 || position == numberSectionRow) {
return 4;

View File

@ -55,7 +55,7 @@ public class StickerPreviewViewer {
@Override
protected void onDraw(Canvas canvas) {
getInstance().onDraw(canvas);
StickerPreviewViewer.this.onDraw(canvas);
}
}
@ -423,7 +423,7 @@ public class StickerPreviewViewer {
}
}
currentSet = newSet;
centerImage.setImage(sticker, null, sticker.thumb.location, null, "webp", true);
centerImage.setImage(sticker, null, sticker.thumb.location, null, "webp", 1);
stickerEmojiLayout = null;
for (int a = 0; a < sticker.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = sticker.attributes.get(a);
@ -522,7 +522,7 @@ public class StickerPreviewViewer {
canvas.save();
int size = (int) (Math.min(containerView.getWidth(), containerView.getHeight()) / 1.8f);
canvas.translate(containerView.getWidth() / 2, Math.max(size / 2 + AndroidUtilities.statusBarHeight, (containerView.getHeight() - keyboardHeight) / 2));
canvas.translate(containerView.getWidth() / 2, Math.max(size / 2 + AndroidUtilities.statusBarHeight + (stickerEmojiLayout!=null ? AndroidUtilities.dp(40) : 0), (containerView.getHeight() - keyboardHeight) / 2));
Bitmap bitmap = centerImage.getBitmap();
if (bitmap != null) {
float scale = 0.8f * showProgress / 0.8f;

View File

@ -617,6 +617,7 @@ public class ThemePreviewActivity extends BaseFragment implements NotificationCe
message.from_id = 0;
message.id = 5;
message.media = new TLRPC.TL_messageMediaDocument();
message.media.flags |= 3;
message.media.document = new TLRPC.TL_document();
message.media.document.mime_type = "audio/mp4";
message.media.document.thumb = new TLRPC.TL_photoSizeEmpty();
@ -655,6 +656,7 @@ public class ThemePreviewActivity extends BaseFragment implements NotificationCe
message.from_id = UserConfig.getClientUserId();
message.id = 1;
message.media = new TLRPC.TL_messageMediaDocument();
message.media.flags |= 3;
message.media.document = new TLRPC.TL_document();
message.media.document.mime_type = "audio/ogg";
message.media.document.thumb = new TLRPC.TL_photoSizeEmpty();
@ -685,6 +687,7 @@ public class ThemePreviewActivity extends BaseFragment implements NotificationCe
message.from_id = 0;
message.id = 1;
message.media = new TLRPC.TL_messageMediaPhoto();
message.media.flags |= 3;
message.media.photo = new TLRPC.TL_photo();
message.media.photo.has_stickers = false;
message.media.photo.id = 1;

View File

@ -302,7 +302,7 @@ public class WallpapersActivity extends BaseFragment implements NotificationCent
progressView.setVisibility(View.VISIBLE);
loadingSize = size;
selectedColor = 0;
FileLoader.getInstance().loadFile(size, null, true);
FileLoader.getInstance().loadFile(size, null, 1);
backgroundImage.setBackgroundColor(0);
} else {
if (loadingFile != null) {

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="0.0"
android:toAlpha="1.0"
android:duration="200"
android:interpolator="@android:anim/accelerate_decelerate_interpolator"/>
</set>

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