diff --git a/TMessagesProj/build.gradle b/TMessagesProj/build.gradle index 9242c3d0c..665d9d496 100644 --- a/TMessagesProj/build.gradle +++ b/TMessagesProj/build.gradle @@ -3,7 +3,7 @@ buildscript { mavenCentral() } dependencies { - classpath 'com.android.tools.build:gradle:0.10.+' + classpath 'com.android.tools.build:gradle:0.11.+' } } apply plugin: 'android' @@ -18,7 +18,6 @@ tasks.withType(JavaCompile) { dependencies { compile 'com.android.support:support-v4:19.0.+' - compile 'com.android.support:appcompat-v7:19.0.+' compile 'com.google.android.gms:play-services:4.1.+' compile 'net.hockeyapp.android:HockeySDK:3.0.1' } @@ -82,7 +81,7 @@ android { defaultConfig { minSdkVersion 8 targetSdkVersion 19 - versionCode 240 + versionCode 243 versionName "1.4.15" } } diff --git a/TMessagesProj/src/main/AndroidManifest.xml b/TMessagesProj/src/main/AndroidManifest.xml index 158676b00..71e7bb9cc 100644 --- a/TMessagesProj/src/main/AndroidManifest.xml +++ b/TMessagesProj/src/main/AndroidManifest.xml @@ -100,11 +100,6 @@ android:configChanges="keyboard|keyboardHidden|orientation|screenSize" android:screenOrientation="portrait"> - - diff --git a/TMessagesProj/src/main/assets/emoji/emoji2.0x.jpg b/TMessagesProj/src/main/assets/emoji/emoji2.0x.jpg deleted file mode 100644 index 204ad9fea..000000000 Binary files a/TMessagesProj/src/main/assets/emoji/emoji2.0x.jpg and /dev/null differ diff --git a/TMessagesProj/src/main/assets/emoji/emoji2.0x_0.jpg b/TMessagesProj/src/main/assets/emoji/emoji2.0x_0.jpg new file mode 100644 index 000000000..1cf58511e Binary files /dev/null and b/TMessagesProj/src/main/assets/emoji/emoji2.0x_0.jpg differ diff --git a/TMessagesProj/src/main/assets/emoji/emoji2.0x_1.jpg b/TMessagesProj/src/main/assets/emoji/emoji2.0x_1.jpg new file mode 100644 index 000000000..f5a3bd8a3 Binary files /dev/null and b/TMessagesProj/src/main/assets/emoji/emoji2.0x_1.jpg differ diff --git a/TMessagesProj/src/main/assets/emoji/emoji2.0x_2.jpg b/TMessagesProj/src/main/assets/emoji/emoji2.0x_2.jpg new file mode 100644 index 000000000..d0db3e171 Binary files /dev/null and b/TMessagesProj/src/main/assets/emoji/emoji2.0x_2.jpg differ diff --git a/TMessagesProj/src/main/assets/emoji/emoji2.0x_3.jpg b/TMessagesProj/src/main/assets/emoji/emoji2.0x_3.jpg new file mode 100644 index 000000000..225f2b8c5 Binary files /dev/null and b/TMessagesProj/src/main/assets/emoji/emoji2.0x_3.jpg differ diff --git a/TMessagesProj/src/main/assets/emoji/emoji2.0x_4.jpg b/TMessagesProj/src/main/assets/emoji/emoji2.0x_4.jpg new file mode 100644 index 000000000..453875c0d Binary files /dev/null and b/TMessagesProj/src/main/assets/emoji/emoji2.0x_4.jpg differ diff --git a/TMessagesProj/src/main/assets/emoji/emoji2.0x_a.jpg b/TMessagesProj/src/main/assets/emoji/emoji2.0x_a.jpg deleted file mode 100644 index a0203fe2f..000000000 Binary files a/TMessagesProj/src/main/assets/emoji/emoji2.0x_a.jpg and /dev/null differ diff --git a/TMessagesProj/src/main/assets/emoji/emoji2.0x_a_0.jpg b/TMessagesProj/src/main/assets/emoji/emoji2.0x_a_0.jpg new file mode 100644 index 000000000..53416f240 Binary files /dev/null and b/TMessagesProj/src/main/assets/emoji/emoji2.0x_a_0.jpg differ diff --git a/TMessagesProj/src/main/assets/emoji/emoji2.0x_a_1.jpg b/TMessagesProj/src/main/assets/emoji/emoji2.0x_a_1.jpg new file mode 100644 index 000000000..8b7a562ea Binary files /dev/null and b/TMessagesProj/src/main/assets/emoji/emoji2.0x_a_1.jpg differ diff --git a/TMessagesProj/src/main/assets/emoji/emoji2.0x_a_2.jpg b/TMessagesProj/src/main/assets/emoji/emoji2.0x_a_2.jpg new file mode 100644 index 000000000..48424203e Binary files /dev/null and b/TMessagesProj/src/main/assets/emoji/emoji2.0x_a_2.jpg differ diff --git a/TMessagesProj/src/main/assets/emoji/emoji2.0x_a_3.jpg b/TMessagesProj/src/main/assets/emoji/emoji2.0x_a_3.jpg new file mode 100644 index 000000000..98cef882c Binary files /dev/null and b/TMessagesProj/src/main/assets/emoji/emoji2.0x_a_3.jpg differ diff --git a/TMessagesProj/src/main/assets/emoji/emoji2.0x_a_4.jpg b/TMessagesProj/src/main/assets/emoji/emoji2.0x_a_4.jpg new file mode 100644 index 000000000..0f8980a81 Binary files /dev/null and b/TMessagesProj/src/main/assets/emoji/emoji2.0x_a_4.jpg differ diff --git a/TMessagesProj/src/main/assets/emoji/emoji3.0x.jpg b/TMessagesProj/src/main/assets/emoji/emoji3.0x.jpg deleted file mode 100644 index e5a20b173..000000000 Binary files a/TMessagesProj/src/main/assets/emoji/emoji3.0x.jpg and /dev/null differ diff --git a/TMessagesProj/src/main/assets/emoji/emoji3.0x_0.jpg b/TMessagesProj/src/main/assets/emoji/emoji3.0x_0.jpg new file mode 100644 index 000000000..e09c30c59 Binary files /dev/null and b/TMessagesProj/src/main/assets/emoji/emoji3.0x_0.jpg differ diff --git a/TMessagesProj/src/main/assets/emoji/emoji3.0x_1.jpg b/TMessagesProj/src/main/assets/emoji/emoji3.0x_1.jpg new file mode 100644 index 000000000..e0b0752ed Binary files /dev/null and b/TMessagesProj/src/main/assets/emoji/emoji3.0x_1.jpg differ diff --git a/TMessagesProj/src/main/assets/emoji/emoji3.0x_2.jpg b/TMessagesProj/src/main/assets/emoji/emoji3.0x_2.jpg new file mode 100644 index 000000000..ffd3c8480 Binary files /dev/null and b/TMessagesProj/src/main/assets/emoji/emoji3.0x_2.jpg differ diff --git a/TMessagesProj/src/main/assets/emoji/emoji3.0x_3.jpg b/TMessagesProj/src/main/assets/emoji/emoji3.0x_3.jpg new file mode 100644 index 000000000..dd229d2a5 Binary files /dev/null and b/TMessagesProj/src/main/assets/emoji/emoji3.0x_3.jpg differ diff --git a/TMessagesProj/src/main/assets/emoji/emoji3.0x_4.jpg b/TMessagesProj/src/main/assets/emoji/emoji3.0x_4.jpg new file mode 100644 index 000000000..9127912ff Binary files /dev/null and b/TMessagesProj/src/main/assets/emoji/emoji3.0x_4.jpg differ diff --git a/TMessagesProj/src/main/assets/emoji/emoji3.0x_a.jpg b/TMessagesProj/src/main/assets/emoji/emoji3.0x_a.jpg deleted file mode 100644 index 12d55cdbc..000000000 Binary files a/TMessagesProj/src/main/assets/emoji/emoji3.0x_a.jpg and /dev/null differ diff --git a/TMessagesProj/src/main/assets/emoji/emoji3.0x_a_0.jpg b/TMessagesProj/src/main/assets/emoji/emoji3.0x_a_0.jpg new file mode 100644 index 000000000..e0e9339ec Binary files /dev/null and b/TMessagesProj/src/main/assets/emoji/emoji3.0x_a_0.jpg differ diff --git a/TMessagesProj/src/main/assets/emoji/emoji3.0x_a_1.jpg b/TMessagesProj/src/main/assets/emoji/emoji3.0x_a_1.jpg new file mode 100644 index 000000000..f5e831aec Binary files /dev/null and b/TMessagesProj/src/main/assets/emoji/emoji3.0x_a_1.jpg differ diff --git a/TMessagesProj/src/main/assets/emoji/emoji3.0x_a_2.jpg b/TMessagesProj/src/main/assets/emoji/emoji3.0x_a_2.jpg new file mode 100644 index 000000000..d04659d6a Binary files /dev/null and b/TMessagesProj/src/main/assets/emoji/emoji3.0x_a_2.jpg differ diff --git a/TMessagesProj/src/main/assets/emoji/emoji3.0x_a_3.jpg b/TMessagesProj/src/main/assets/emoji/emoji3.0x_a_3.jpg new file mode 100644 index 000000000..1a3372391 Binary files /dev/null and b/TMessagesProj/src/main/assets/emoji/emoji3.0x_a_3.jpg differ diff --git a/TMessagesProj/src/main/assets/emoji/emoji3.0x_a_4.jpg b/TMessagesProj/src/main/assets/emoji/emoji3.0x_a_4.jpg new file mode 100644 index 000000000..7ce611f72 Binary files /dev/null and b/TMessagesProj/src/main/assets/emoji/emoji3.0x_a_4.jpg differ diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/ConnectionsManager.java b/TMessagesProj/src/main/java/org/telegram/messenger/ConnectionsManager.java index 54ee368f9..88454987c 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/ConnectionsManager.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/ConnectionsManager.java @@ -184,10 +184,10 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection. if (paused) { ApplicationLoader.lastPauseTime = System.currentTimeMillis(); nextSleepTimeout = 30000; - FileLog.e("tmessages", "wakeup network in background by recieved push"); + FileLog.e("tmessages", "wakeup network in background by received push"); } else if (ApplicationLoader.lastPauseTime != 0) { ApplicationLoader.lastPauseTime = System.currentTimeMillis(); - FileLog.e("tmessages", "reset sleep timeout by recieved push"); + FileLog.e("tmessages", "reset sleep timeout by received push"); } } }); @@ -849,7 +849,16 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection. public static boolean isNetworkOnline() { try { ConnectivityManager cm = (ConnectivityManager)ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE); - NetworkInfo netInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); + NetworkInfo netInfo = cm.getActiveNetworkInfo(); + if (netInfo != null && netInfo.isConnected()) { + return true; + } + + netInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); + if (netInfo.isConnected()) { + return true; + } + if (netInfo != null && netInfo.getState() == NetworkInfo.State.CONNECTED) { return true; } else { diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/Emoji.java b/TMessagesProj/src/main/java/org/telegram/messenger/Emoji.java index d27606f4f..45c5586e6 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/Emoji.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/Emoji.java @@ -34,8 +34,12 @@ public class Emoji { private static int drawImgSize, bigImgSize; private static boolean inited = false; private static Paint placeholderPaint; - private static Bitmap emojiBmp = null; - private static boolean loadingEmoji = false; + private static Bitmap emojiBmp[] = new Bitmap[5]; + private static boolean loadingEmoji[] = new boolean[5]; + + private static final int[] cols = { + 13, 10, 15, 10, 14 + }; private static final char[] emojiChars = { 0x00A9, 0x00AE, 0x203C, 0x2049, 0x2122, 0x2139, 0x2194, 0x2195, 0x2196, 0x2197, @@ -199,19 +203,17 @@ public class Emoji { drawImgSize = Utilities.dp(20); bigImgSize = Utilities.dp(30); - int num = 0; for (int j = 1; j < data.length; j++) { for (int i = 0; i < data[j].length; i++) { - Rect rect = new Rect((num % 29) * imgSize, (num / 29) * imgSize, (num % 29 + 1) * imgSize, (num / 29 + 1) * imgSize); - rects.put(data[j][i], new DrawableInfo(rect)); - num++; + Rect rect = new Rect((i % cols[j - 1]) * imgSize, (i / cols[j - 1]) * imgSize, (i % cols[j - 1] + 1) * imgSize, (i / cols[j - 1] + 1) * imgSize); + rects.put(data[j][i], new DrawableInfo(rect, (byte)(j - 1))); } } placeholderPaint = new Paint(); - placeholderPaint.setColor(0x55000000); + placeholderPaint.setColor(0x00000000); } - private static Bitmap loadEmoji() { + private static Bitmap loadEmoji(final int page) { try { float scale = 1.0f; int imageResize = 1; @@ -227,7 +229,7 @@ public class Emoji { scale = 3.0f; } - String imageName = String.format(Locale.US, "emoji%.01fx.jpg", scale); + String imageName = String.format(Locale.US, "emoji%.01fx_%d.jpg", scale, page); File imageFile = ApplicationLoader.applicationContext.getFileStreamPath(imageName); if (!imageFile.exists()) { InputStream is = ApplicationLoader.applicationContext.getAssets().open("emoji/" + imageName); @@ -242,7 +244,7 @@ public class Emoji { final Bitmap colorsBitmap = Bitmap.createBitmap(opts.outWidth / imageResize, opts.outHeight / imageResize, Bitmap.Config.ARGB_8888); Utilities.loadBitmap(imageFile.getAbsolutePath(), colorsBitmap, imageResize); - imageName = String.format(Locale.US, "emoji%.01fx_a.jpg", scale); + imageName = String.format(Locale.US, "emoji%.01fx_a_%d.jpg", scale, page); imageFile = ApplicationLoader.applicationContext.getFileStreamPath(imageName); if (!imageFile.exists()) { InputStream is = ApplicationLoader.applicationContext.getAssets().open("emoji/" + imageName); @@ -255,7 +257,7 @@ public class Emoji { Utilities.RunOnUIThread(new Runnable() { @Override public void run() { - emojiBmp = colorsBitmap; + emojiBmp[page] = colorsBitmap; NotificationCenter.getInstance().postNotificationName(999); } }); @@ -267,15 +269,15 @@ public class Emoji { return null; } - private static void loadEmojiAsync() { - if (loadingEmoji) { + private static void loadEmojiAsync(final int page) { + if (loadingEmoji[page]) { return; } - loadingEmoji = true; + loadingEmoji[page] = true; new Thread(new Runnable() { public void run() { - loadEmoji(); - loadingEmoji = false; + loadEmoji(page); + loadingEmoji[page] = false; } }).start(); } @@ -313,7 +315,7 @@ public class Emoji { } public static class EmojiDrawable extends Drawable { - Rect rect; + private DrawableInfo info; boolean fullSize = false; private static Paint paint; @@ -322,14 +324,14 @@ public class Emoji { paint.setFlags(Paint.FILTER_BITMAP_FLAG | Paint.ANTI_ALIAS_FLAG); } - public EmojiDrawable(DrawableInfo info) { - rect = info.rect; + public EmojiDrawable(DrawableInfo i) { + info = i; } @Override public void draw(Canvas canvas) { - if (emojiBmp == null) { - loadEmojiAsync(); + if (emojiBmp[info.page] == null) { + loadEmojiAsync(info.page); canvas.drawRect(getBounds(), placeholderPaint); return; } @@ -340,7 +342,7 @@ public class Emoji { b.top = cY - (fullSize ? bigImgSize : drawImgSize) / 2; b.bottom = cY + (fullSize ? bigImgSize : drawImgSize) / 2; if (!canvas.quickReject(b.left, b.top, b.right, b.bottom, Canvas.EdgeType.AA)) { - canvas.drawBitmap(emojiBmp, rect, b, paint); + canvas.drawBitmap(emojiBmp[info.page], info.rect, b, paint); } } @@ -361,9 +363,12 @@ public class Emoji { } private static class DrawableInfo { - Rect rect; - public DrawableInfo(Rect rect) { - this.rect = rect; + public Rect rect; + public byte page; + + public DrawableInfo(Rect r, byte p) { + rect = r; + page = p; } } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/FileLoadOperation.java b/TMessagesProj/src/main/java/org/telegram/messenger/FileLoadOperation.java index 0c87667d5..1a2b32b63 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/FileLoadOperation.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/FileLoadOperation.java @@ -93,12 +93,7 @@ public class FileLoadOperation { } public FileLoadOperation(TLRPC.Audio audioLocation) { - if (audioLocation instanceof TLRPC.TL_audio) { - location = new TLRPC.TL_inputAudioFileLocation(); - datacenter_id = audioLocation.dc_id; - location.id = audioLocation.id; - location.access_hash = audioLocation.access_hash; - } else if (audioLocation instanceof TLRPC.TL_audioEncrypted) { + if (audioLocation instanceof TLRPC.TL_audioEncrypted) { location = new TLRPC.TL_inputEncryptedFileLocation(); location.id = audioLocation.id; location.access_hash = audioLocation.access_hash; @@ -106,6 +101,11 @@ public class FileLoadOperation { iv = new byte[32]; System.arraycopy(audioLocation.iv, 0, iv, 0, iv.length); key = audioLocation.key; + } else if (audioLocation instanceof TLRPC.TL_audio) { + location = new TLRPC.TL_inputAudioFileLocation(); + datacenter_id = audioLocation.dc_id; + location.id = audioLocation.id; + location.access_hash = audioLocation.access_hash; } ext = ".m4a"; } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/FileLoader.java b/TMessagesProj/src/main/java/org/telegram/messenger/FileLoader.java index afb2cad56..97a0289e7 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/FileLoader.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/FileLoader.java @@ -20,7 +20,6 @@ import android.os.ParcelFileDescriptor; import org.telegram.objects.MessageObject; import org.telegram.ui.ApplicationLoader; -import org.telegram.ui.Views.BackupImageView; import org.telegram.ui.Views.ImageReceiver; import java.io.ByteArrayOutputStream; @@ -34,6 +33,7 @@ import java.util.HashMap; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Semaphore; public class FileLoader { public LruCache memCache; @@ -132,10 +132,10 @@ public class FileLoader { private class CacheImage { public String key; - final public ArrayList imageViewArray = new ArrayList(); + final public ArrayList imageViewArray = new ArrayList(); public FileLoadOperation loadOperation; - public void addImageView(Object imageView) { + public void addImageView(ImageReceiver imageView) { synchronized (imageViewArray) { boolean exist = false; for (Object v : imageViewArray) { @@ -166,9 +166,7 @@ public class FileLoader { synchronized (imageViewArray) { if (image != null) { for (Object imgView : imageViewArray) { - if (imgView instanceof BackupImageView) { - ((BackupImageView)imgView).setImageBitmap(image, key); - } else if (imgView instanceof ImageReceiver) { + if (imgView instanceof ImageReceiver) { ((ImageReceiver)imgView).setImageBitmap(image, key); } } @@ -481,8 +479,22 @@ public class FileLoader { }); } - public boolean isLoadingFile(String fileName) { - return loadOperationPaths.containsKey(fileName); + public boolean isLoadingFile(final String fileName) { + final Semaphore semaphore = new Semaphore(0); + final Boolean[] result = new Boolean[1]; + fileLoaderQueue.postRunnable(new Runnable() { + @Override + public void run() { + result[0] = loadOperationPaths.containsKey(fileName); + semaphore.release(); + } + }); + try { + semaphore.acquire(); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + return result[0]; } public void loadFile(final TLRPC.Video video, final TLRPC.PhotoSize photo, final TLRPC.Document document, final TLRPC.Audio audio) { @@ -676,34 +688,16 @@ public class FileLoader { memCache.evictAll(); } - private Integer getTag(Object obj) { - if (obj instanceof BackupImageView) { - return (Integer)((BackupImageView)obj).getTag(R.string.CacheTag); - } else if (obj instanceof ImageReceiver) { - return ((ImageReceiver)obj).TAG; - } - return 0; - } - - private void setTag(Object obj, Integer tag) { - if (obj instanceof BackupImageView) { - ((BackupImageView)obj).setTag(R.string.CacheTag, tag); - } else if (obj instanceof ImageReceiver) { - ((ImageReceiver)obj).TAG = tag; - } - } - - public void cancelLoadingForImageView(final Object imageView) { + public void cancelLoadingForImageView(final ImageReceiver imageView) { if (imageView == null) { return; } fileLoaderQueue.postRunnable(new Runnable() { @Override public void run() { - Integer TAG = getTag(imageView); + Integer TAG = imageView.TAG; if (TAG == null) { - TAG = lastImageNum; - setTag(imageView, TAG); + imageView.TAG = TAG = lastImageNum; lastImageNum++; if (lastImageNum == Integer.MAX_VALUE) { lastImageNum = 0; @@ -723,15 +717,15 @@ public class FileLoader { }); } - public Bitmap getImageFromMemory(TLRPC.FileLocation url, Object imageView, String filter, boolean cancel) { + public Bitmap getImageFromMemory(TLRPC.FileLocation url, ImageReceiver imageView, String filter, boolean cancel) { return getImageFromMemory(url, null, imageView, filter, cancel); } - public Bitmap getImageFromMemory(String url, Object imageView, String filter, boolean cancel) { + public Bitmap getImageFromMemory(String url, ImageReceiver imageView, String filter, boolean cancel) { return getImageFromMemory(null, url, imageView, filter, cancel); } - public Bitmap getImageFromMemory(TLRPC.FileLocation url, String httpUrl, Object imageView, String filter, boolean cancel) { + public Bitmap getImageFromMemory(TLRPC.FileLocation url, String httpUrl, ImageReceiver imageView, String filter, boolean cancel) { if (url == null && httpUrl == null) { return null; } @@ -783,19 +777,19 @@ public class FileLoader { }); } - public void loadImage(final String url, final Object imageView, final String filter, final boolean cancel) { + public void loadImage(final String url, final ImageReceiver imageView, final String filter, final boolean cancel) { loadImage(null, url, imageView, filter, cancel, 0); } - public void loadImage(final TLRPC.FileLocation url, final Object imageView, final String filter, final boolean cancel) { + public void loadImage(final TLRPC.FileLocation url, final ImageReceiver imageView, final String filter, final boolean cancel) { loadImage(url, null, imageView, filter, cancel, 0); } - public void loadImage(final TLRPC.FileLocation url, final Object imageView, final String filter, final boolean cancel, final int size) { + public void loadImage(final TLRPC.FileLocation url, final ImageReceiver imageView, final String filter, final boolean cancel, final int size) { loadImage(url, null, imageView, filter, cancel, size); } - public void loadImage(final TLRPC.FileLocation url, final String httpUrl, final Object imageView, final String filter, final boolean cancel, final int size) { + public void loadImage(final TLRPC.FileLocation url, final String httpUrl, final ImageReceiver imageView, final String filter, final boolean cancel, final int size) { if ((url == null && httpUrl == null) || imageView == null || (url != null && !(url instanceof TLRPC.TL_fileLocation) && !(url instanceof TLRPC.TL_fileEncryptedLocation))) { return; } @@ -814,10 +808,9 @@ public class FileLoader { key += "@" + filter; } - Integer TAG = getTag(imageView); + Integer TAG = imageView.TAG; if (TAG == null) { - TAG = lastImageNum; - setTag(imageView, TAG); + TAG = imageView.TAG = lastImageNum; lastImageNum++; if (lastImageNum == Integer.MAX_VALUE) lastImageNum = 0; @@ -878,8 +871,8 @@ public class FileLoader { if (arg3 != null) { loadOperationPaths.remove(arg3); } - for (Object v : img.imageViewArray) { - imageLoadingByKeys.remove(getTag(v)); + for (ImageReceiver v : img.imageViewArray) { + imageLoadingByKeys.remove(v.TAG); } checkOperationsAndClear(img.loadOperation); imageLoading.remove(arg2); @@ -906,8 +899,8 @@ public class FileLoader { if (arg3 != null) { loadOperationPaths.remove(arg3); } - for (Object view : img.imageViewArray) { - imageLoadingByKeys.remove(getTag(view)); + for (ImageReceiver view : img.imageViewArray) { + imageLoadingByKeys.remove(view.TAG); imageLoading.remove(arg2); checkOperationsAndClear(operation); } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/MessagesController.java b/TMessagesProj/src/main/java/org/telegram/messenger/MessagesController.java index e6ffa09bc..0c472b085 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/MessagesController.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/MessagesController.java @@ -852,7 +852,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ArrayList keys = new ArrayList(printingUsers.keySet()); for (Long key : keys) { - if (key > 0) { + if (key > 0 || key.intValue() == 0) { newPrintingStrings.put(key, LocaleController.getString("Typing", R.string.Typing)); } else { ArrayList arr = printingUsers.get(key); @@ -3937,26 +3937,30 @@ public class MessagesController implements NotificationCenter.NotificationCenter } } } else if (update instanceof TLRPC.TL_updateEncryptedChatTyping) { - long uid = ((long)update.chat_id) << 32; - ArrayList arr = printingUsers.get(uid); - if (arr == null) { - arr = new ArrayList(); - printingUsers.put(uid, arr); - } - boolean exist = false; - for (PrintingUser u : arr) { - if (u.userId == update.user_id) { - exist = true; - u.lastTime = currentTime; - break; + TLRPC.EncryptedChat encryptedChat = getEncryptedChat(update.chat_id); + if (encryptedChat != null) { + update.user_id = encryptedChat.user_id; + long uid = ((long) update.chat_id) << 32; + ArrayList arr = printingUsers.get(uid); + if (arr == null) { + arr = new ArrayList(); + printingUsers.put(uid, arr); + } + boolean exist = false; + for (PrintingUser u : arr) { + if (u.userId == update.user_id) { + exist = true; + u.lastTime = currentTime; + break; + } + } + if (!exist) { + PrintingUser newUser = new PrintingUser(); + newUser.userId = update.user_id; + newUser.lastTime = currentTime; + arr.add(newUser); + printChanged = true; } - } - if (!exist) { - PrintingUser newUser = new PrintingUser(); - newUser.userId = update.user_id; - newUser.lastTime = currentTime; - arr.add(newUser); - printChanged = true; } } else if (update instanceof TLRPC.TL_updateEncryptedMessagesRead) { markAsReadEncrypted.put(update.chat_id, Math.max(update.max_date, update.date)); @@ -3970,22 +3974,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter } else if (update instanceof TLRPC.TL_updateEncryption) { final TLRPC.EncryptedChat newChat = update.chat; long dialog_id = ((long)newChat.id) << 32; - TLRPC.EncryptedChat existingChat = encryptedChats.get(newChat.id); - if (existingChat == null) { - Semaphore semaphore = new Semaphore(0); - ArrayList result = new ArrayList(); - MessagesStorage.getInstance().getEncryptedChat(newChat.id, semaphore, result); - try { - semaphore.acquire(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - if (result.size() == 2) { - existingChat = (TLRPC.EncryptedChat)result.get(0); - TLRPC.User user = (TLRPC.User)result.get(1); - users.putIfAbsent(user.id, user); - } - } + TLRPC.EncryptedChat existingChat = getEncryptedChat(newChat.id); if (newChat instanceof TLRPC.TL_encryptedChatRequested && existingChat == null) { int user_id = newChat.participant_id; @@ -4289,7 +4278,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter } if (ApplicationLoader.lastPauseTime != 0) { ApplicationLoader.lastPauseTime = System.currentTimeMillis(); - FileLog.e("tmessages", "reset sleep timeout by recieved message"); + FileLog.e("tmessages", "reset sleep timeout by received message"); } if (messageObject == null) { return; @@ -4654,12 +4643,12 @@ public class MessagesController implements NotificationCenter.NotificationCenter } } - public TLRPC.Message decryptMessage(TLRPC.EncryptedMessage message) { - TLRPC.EncryptedChat chat = encryptedChats.get(message.chat_id); + public TLRPC.EncryptedChat getEncryptedChat(int chat_id) { + TLRPC.EncryptedChat chat = encryptedChats.get(chat_id); if (chat == null) { Semaphore semaphore = new Semaphore(0); ArrayList result = new ArrayList(); - MessagesStorage.getInstance().getEncryptedChat(message.chat_id, semaphore, result); + MessagesStorage.getInstance().getEncryptedChat(chat_id, semaphore, result); try { semaphore.acquire(); } catch (Exception e) { @@ -4672,6 +4661,11 @@ public class MessagesController implements NotificationCenter.NotificationCenter users.putIfAbsent(user.id, user); } } + return chat; + } + + public TLRPC.Message decryptMessage(TLRPC.EncryptedMessage message) { + TLRPC.EncryptedChat chat = getEncryptedChat(message.chat_id); if (chat == null) { return null; } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/NotificationCenter.java b/TMessagesProj/src/main/java/org/telegram/messenger/NotificationCenter.java index 6a78befbb..f71ed384c 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/NotificationCenter.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/NotificationCenter.java @@ -15,8 +15,6 @@ public class NotificationCenter { final private HashMap> observers = new HashMap>(); - final private HashMap memCache = new HashMap(); - final private HashMap removeAfterBroadcast = new HashMap(); final private HashMap addAfterBroadcast = new HashMap(); @@ -40,27 +38,6 @@ public class NotificationCenter { public abstract void didReceivedNotification(int id, Object... args); } - public void addToMemCache(int id, Object object) { - addToMemCache(String.valueOf(id), object); - } - - public void addToMemCache(String id, Object object) { - memCache.put(id, object); - } - - public Object getFromMemCache(int id) { - return getFromMemCache(String.valueOf(id), null); - } - - public Object getFromMemCache(String id, Object defaultValue) { - Object obj = memCache.get(id); - if (obj != null) { - memCache.remove(id); - return obj; - } - return defaultValue; - } - public void postNotificationName(int id, Object... args) { synchronized (observers) { broadcasting = true; diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/TcpConnection.java b/TMessagesProj/src/main/java/org/telegram/messenger/TcpConnection.java index 46df1d71d..660354c77 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/TcpConnection.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/TcpConnection.java @@ -59,7 +59,6 @@ public class TcpConnection extends ConnectionContext { private boolean firstPacket; private Timer reconnectTimer; - private boolean tryWithNoNetworkAnyway = false; public TcpConnection(int did) { if (selector == null) { @@ -81,6 +80,43 @@ public class TcpConnection extends ConnectionContext { } public void connect() { + if (!ConnectionsManager.isNetworkOnline()) { + synchronized (timerSync) { + reconnectTimer = new Timer(); + reconnectTimer.schedule(new TimerTask() { + @Override + public void run() { + selector.scheduleTask(new Runnable() { + @Override + public void run() { + try { + synchronized (timerSync) { + if (reconnectTimer != null) { + reconnectTimer.cancel(); + reconnectTimer = null; + } + } + } catch (Exception e2) { + FileLog.e("tmessages", e2); + } + connect(); + } + }); + } + }, 500); + } + if (delegate != null) { + final TcpConnectionDelegate finalDelegate = delegate; + Utilities.stageQueue.postRunnable(new Runnable() { + @Override + public void run() { + finalDelegate.tcpConnectionClosed(TcpConnection.this); + } + }); + } + return; + } + selector.scheduleTask(new Runnable() { @Override public void run() { @@ -94,14 +130,6 @@ public class TcpConnection extends ConnectionContext { hostAddress = datacenter.getCurrentAddress(); hostPort = datacenter.getCurrentPort(); - if(android.os.Build.VERSION.SDK_INT < 11) { - if (!ConnectionsManager.isNetworkOnline() && !tryWithNoNetworkAnyway) { - handleConnectionError(null); - tryWithNoNetworkAnyway = true; - return; - } - tryWithNoNetworkAnyway = false; - } try { synchronized (timerSync) { if (reconnectTimer != null) { @@ -637,28 +665,30 @@ public class TcpConnection extends ConnectionContext { } FileLog.d("tmessages", "Reconnect " + hostAddress + ":" + hostPort + " " + TcpConnection.this); try { - reconnectTimer = new Timer(); - reconnectTimer.schedule(new TimerTask() { - @Override - public void run() { - selector.scheduleTask(new Runnable() { - @Override - public void run() { - try { - synchronized (timerSync) { - if (reconnectTimer != null) { - reconnectTimer.cancel(); - reconnectTimer = null; + synchronized (timerSync) { + reconnectTimer = new Timer(); + reconnectTimer.schedule(new TimerTask() { + @Override + public void run() { + selector.scheduleTask(new Runnable() { + @Override + public void run() { + try { + synchronized (timerSync) { + if (reconnectTimer != null) { + reconnectTimer.cancel(); + reconnectTimer = null; + } } + } catch (Exception e2) { + FileLog.e("tmessages", e2); } - } catch (Exception e2) { - FileLog.e("tmessages", e2); + connect(); } - connect(); - } - }); - } - }, failedConnectionCount > 3 ? 500 : 300, failedConnectionCount > 3 ? 500 : 300); + }); + } + }, failedConnectionCount > 3 ? 500 : 300, failedConnectionCount > 3 ? 500 : 300); + } } catch (Exception e3) { FileLog.e("tmessages", e3); } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java b/TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java index ee2220e2e..ea76ec3f1 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java @@ -14,6 +14,7 @@ import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; +import android.content.pm.ActivityInfo; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Point; @@ -27,6 +28,7 @@ import android.text.Html; import android.text.SpannableStringBuilder; import android.util.Base64; import android.view.Display; +import android.view.Surface; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; @@ -72,6 +74,7 @@ public class Utilities { public static Pattern pattern = Pattern.compile("[0-9]+"); public static SecureRandom random = new SecureRandom(); private final static Integer lock = 1; + private static int prevOrientation = -10; private static boolean waitingForSms = false; private static final Integer smsLock = 2; @@ -152,6 +155,47 @@ public class Utilities { public native static void aesIgeEncryption2(ByteBuffer _what, byte[] _key, byte[] _iv, boolean encrypt, boolean changeIv, int len); public native static void loadBitmap(String path, Bitmap bitmap, int scale); + public static void lockOrientation(Activity activity) { + if (prevOrientation != -10) { + return; + } + try { + prevOrientation = activity.getRequestedOrientation(); + WindowManager manager = (WindowManager)activity.getSystemService(Activity.WINDOW_SERVICE); + if (manager != null && manager.getDefaultDisplay() != null) { + int rotation = manager.getDefaultDisplay().getRotation(); + if (rotation == Surface.ROTATION_270) { + if (Build.VERSION.SDK_INT >= 9) { + activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE); + } else { + activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); + } + } else if (rotation == Surface.ROTATION_90) { + activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); + } else if (rotation == Surface.ROTATION_0) { + activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); + } else { + if (Build.VERSION.SDK_INT >= 9) { + activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT); + } + } + } + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + + public static void unlockOrientation(Activity activity) { + try { + if (prevOrientation != -10) { + activity.setRequestedOrientation(prevOrientation); + prevOrientation = -10; + } + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + public static boolean isWaitingForSms() { boolean value = false; synchronized (smsLock) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ApplicationLoader.java b/TMessagesProj/src/main/java/org/telegram/ui/ApplicationLoader.java index 98c7bcff1..42ddb9889 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ApplicationLoader.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ApplicationLoader.java @@ -152,10 +152,12 @@ public class ApplicationLoader extends Application { if (preferences.getBoolean("pushService", true)) { applicationContext.startService(new Intent(applicationContext, NotificationsService.class)); - Calendar cal = Calendar.getInstance(); - PendingIntent pintent = PendingIntent.getService(applicationContext, 0, new Intent(applicationContext, NotificationsService.class), 0); - AlarmManager alarm = (AlarmManager) applicationContext.getSystemService(Context.ALARM_SERVICE); - alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30000, pintent); + if (android.os.Build.VERSION.SDK_INT >= 19) { + Calendar cal = Calendar.getInstance(); + PendingIntent pintent = PendingIntent.getService(applicationContext, 0, new Intent(applicationContext, NotificationsService.class), 0); + AlarmManager alarm = (AlarmManager) applicationContext.getSystemService(Context.ALARM_SERVICE); + alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30000, pintent); + } } else { stopPushService(); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMediaCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMediaCell.java index c146da6b4..b6cb0f4f8 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMediaCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMediaCell.java @@ -28,6 +28,7 @@ import org.telegram.messenger.R; import org.telegram.messenger.Utilities; import org.telegram.objects.MessageObject; import org.telegram.objects.PhotoObject; +import org.telegram.ui.PhotoViewer; import org.telegram.ui.Views.GifDrawable; import org.telegram.ui.Views.ImageReceiver; import org.telegram.ui.Views.ProgressView; @@ -39,7 +40,7 @@ import java.util.Locale; public class ChatMediaCell extends ChatBaseCell implements MediaController.FileDownloadProgressListener { public static interface ChatMediaCellDelegate { - public abstract void didPressedImage(ChatMediaCell cell, ImageReceiver imageReceiver); + public abstract void didPressedImage(ChatMediaCell cell); } private static Drawable placeholderInDrawable; @@ -196,7 +197,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD if (currentMessageObject.type == 1) { if (buttonState == -1) { if (mediaDelegate != null) { - mediaDelegate.didPressedImage(this, photoImage); + mediaDelegate.didPressedImage(this); } } else if (buttonState == 0) { didPressedButton(); @@ -217,7 +218,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD } } else if (currentMessageObject.type == 4) { if (mediaDelegate != null) { - mediaDelegate.didPressedImage(this, photoImage); + mediaDelegate.didPressedImage(this); } } } @@ -271,7 +272,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD } } else if (buttonState == 3) { if (mediaDelegate != null) { - mediaDelegate.didPressedImage(this, photoImage); + mediaDelegate.didPressedImage(this); } } } @@ -421,6 +422,10 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD updateButtonState(); } + public ImageReceiver getPhotoImage() { + return photoImage; + } + public void updateButtonState() { String fileName = null; File cacheFile = null; @@ -544,6 +549,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD gifDrawable.draw(canvas); canvas.restore(); } else { + photoImage.setVisible(!PhotoViewer.getInstance().isShowingImage(currentMessageObject), false); photoImage.draw(canvas, photoImage.imageX, photoImage.imageY, photoWidth, photoHeight); drawTime = photoImage.getVisible(); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java index 22020d524..8f4da2f30 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java @@ -15,7 +15,6 @@ import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; -import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.res.Configuration; @@ -26,7 +25,6 @@ import android.graphics.drawable.BitmapDrawable; import android.media.MediaPlayer; import android.media.ThumbnailUtils; import android.net.Uri; -import android.os.Build; import android.os.Bundle; import android.os.PowerManager; import android.provider.MediaStore; @@ -103,7 +101,7 @@ import java.util.Comparator; import java.util.HashMap; import java.util.concurrent.Semaphore; -public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLayout.SizeNotifierRelativeLayoutDelegate, NotificationCenter.NotificationCenterDelegate, MessagesActivity.MessagesActivityDelegate, DocumentSelectActivity.DocumentSelectActivityDelegate { +public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLayout.SizeNotifierRelativeLayoutDelegate, NotificationCenter.NotificationCenterDelegate, MessagesActivity.MessagesActivityDelegate, DocumentSelectActivity.DocumentSelectActivityDelegate, PhotoViewer.PhotoViewerProvider { private View timeItem; private View menuItem; @@ -180,7 +178,6 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa private float startedDraggingX = -1; private float distCanMove = Utilities.dp(80); private PowerManager.WakeLock mWakeLock = null; - private int prevOrientation = -10; private String currentPicturePath; @@ -411,14 +408,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa FileLog.e("tmessages", e); } } - try { - if (prevOrientation != -10) { - getParentActivity().setRequestedOrientation(prevOrientation); - prevOrientation = -10; - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } + Utilities.unlockOrientation(getParentActivity()); MediaController.getInstance().stopAudio(); } @@ -496,18 +486,17 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa } presentFragment(new UserProfileActivity(args)); } else if (currentChat != null) { - if (info != null) { - if (info instanceof TLRPC.TL_chatParticipantsForbidden) { - return; - } - NotificationCenter.getInstance().addToMemCache(5, info); + if (info != null && info instanceof TLRPC.TL_chatParticipantsForbidden) { + return; } if (currentChat.participants_count == 0 || currentChat.left || currentChat instanceof TLRPC.TL_chatForbidden) { return; } Bundle args = new Bundle(); args.putInt("chat_id", currentChat.id); - presentFragment(new ChatProfileActivity(args)); + ChatProfileActivity fragment = new ChatProfileActivity(args); + fragment.setChatInfo(info); + presentFragment(fragment); } } else if (id == copy) { String str = ""; @@ -1066,30 +1055,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa } catch (Exception e) { FileLog.e("tmessages", e); } - try { - prevOrientation = getParentActivity().getRequestedOrientation(); - WindowManager manager = (WindowManager)ApplicationLoader.applicationContext.getSystemService(Activity.WINDOW_SERVICE); - if (manager != null && manager.getDefaultDisplay() != null) { - int rotation = manager.getDefaultDisplay().getRotation(); - if (rotation == Surface.ROTATION_270) { - if (Build.VERSION.SDK_INT >= 9) { - getParentActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE); - } else { - getParentActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); - } - } else if (rotation == Surface.ROTATION_90) { - getParentActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); - } else if (rotation == Surface.ROTATION_0) { - getParentActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); - } else { - if (Build.VERSION.SDK_INT >= 9) { - getParentActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT); - } - } - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } + Utilities.lockOrientation(getParentActivity()); recordPanel.setVisibility(View.VISIBLE); recordTimeText.setText("00:00"); @@ -1128,14 +1094,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa FileLog.e("tmessages", e); } } - try { - if (prevOrientation != -10) { - getParentActivity().setRequestedOrientation(prevOrientation); - prevOrientation = -10; - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } + Utilities.unlockOrientation(getParentActivity()); if(android.os.Build.VERSION.SDK_INT > 13) { recordPanel.animate().setInterpolator(new AccelerateDecelerateInterpolator()).setListener(new Animator.AnimatorListener() { @Override @@ -3367,6 +3326,51 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa showAlertDialog(builder); } + @Override + public PhotoViewer.PlaceProviderObject getPlaceForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation) { + if (messageObject == null) { + return null; + } + int count = chatListView.getChildCount(); + + for (int a = 0; a < count; a++) { + MessageObject messageToOpen = null; + ImageReceiver imageReceiver = null; + View view = chatListView.getChildAt(a); + if (view instanceof ChatMediaCell) { + ChatMediaCell cell = (ChatMediaCell)view; + MessageObject message = cell.getMessageObject(); + if (message != null && message.messageOwner.id == messageObject.messageOwner.id) { + messageToOpen = message; + imageReceiver = cell.getPhotoImage(); + } + } else if (view.getTag() != null) { + Object tag = view.getTag(); + if (tag instanceof ChatListRowHolderEx) { + ChatListRowHolderEx holder = (ChatListRowHolderEx)tag; + if (holder.message != null && holder.message.messageOwner.id == messageObject.messageOwner.id) { + messageToOpen = holder.message; + imageReceiver = holder.photoImage.imageReceiver; + view = holder.photoImage; + } + } + } + + if (messageToOpen != null) { + int coords[] = new int[2]; + view.getLocationInWindow(coords); + PhotoViewer.PlaceProviderObject object = new PhotoViewer.PlaceProviderObject(); + object.viewX = coords[0]; + object.viewY = coords[1] - Utilities.statusBarHeight; + object.parentView = chatListView; + object.imageReceiver = imageReceiver; + object.thumb = object.imageReceiver.getBitmap(); + return object; + } + } + return null; + } + private class ChatAdapter extends BaseAdapter { private Context mContext; @@ -3517,7 +3521,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa if (view instanceof ChatMediaCell) { ((ChatMediaCell)view).mediaDelegate = new ChatMediaCell.ChatMediaCellDelegate() { @Override - public void didPressedImage(ChatMediaCell cell, ImageReceiver imageReceiver) { + public void didPressedImage(ChatMediaCell cell) { MessageObject message = cell.getMessageObject(); if (message.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SEND_ERROR) { createMenu(cell, false); @@ -3526,12 +3530,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa return; } if (message.type == 1) { -// int coords[] = new int[2]; -// cell.getLocationInWindow(coords); -// PhotoViewer.getInstance().openPhoto(imageReceiver, coords[0], coords[1] - Utilities.statusBarHeight, chatListView); - NotificationCenter.getInstance().addToMemCache(51, message); - Intent intent = new Intent(getParentActivity(), GalleryImageViewer.class); - getParentActivity().startActivity(intent); + PhotoViewer.getInstance().openPhoto(message, ChatActivity.this); } else if (message.type == 3) { try { File f = null; @@ -3551,8 +3550,9 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa if (!isGoogleMapsInstalled()) { return; } - NotificationCenter.getInstance().addToMemCache(0, message); - presentFragment(new LocationActivity()); + LocationActivity fragment = new LocationActivity(); + fragment.setMessageObject(message); + presentFragment(fragment); } } }; @@ -3641,7 +3641,6 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa private PhotoObject photoObjectToSet = null; private File photoFile = null; - private String photoFileName = null; private String photoFilter = null; public void update() { @@ -3683,6 +3682,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa photoImage.setImage(photo.photoOwner.location, "50_50", Utilities.getGroupAvatarForId(currentChat.id)); } } + photoImage.imageReceiver.setVisible(!PhotoViewer.getInstance().isShowingImage(message), false); } } else if (type == 12 || type == 13) { TLRPC.User contactUser = MessagesController.getInstance().users.get(message.messageOwner.media.user_id); @@ -3753,9 +3753,9 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa phoneTextView.setText(String.format("%.1f MB %s", document.size / 1024.0f / 1024.0f, ext)); } if (document.thumb instanceof TLRPC.TL_photoSize) { - + contactAvatar.setImage(document.thumb.location, "50_50", type == 8 ? R.drawable.doc_green : R.drawable.doc_blue); } else if (document.thumb instanceof TLRPC.TL_photoCachedSize) { - + contactAvatar.setImage(document.thumb.location, "50_50", type == 8 ? R.drawable.doc_green : R.drawable.doc_blue); } else { if (type == 8) { contactAvatar.setImageResource(R.drawable.doc_green); @@ -3843,12 +3843,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa if (file != null) { progressBarMap.remove(file); } - String fileName = null; - if (photoFileName != null) { - fileName = photoFileName; - } else { - fileName = message.getFileName(); - } + String fileName = message.getFileName(); boolean load = false; if (message.type != 2 && message.type != 3 && message.messageOwner.attachPath != null && message.messageOwner.attachPath.length() != 0) { File f = new File(message.messageOwner.attachPath); @@ -3895,9 +3890,6 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa addToLoadingFile(fileName, actionProgress); if (actionView != null) { actionView.setVisibility(View.VISIBLE); - if (photoFileName != null) { - actionCancelButton.setImageResource(R.drawable.photo_download_cancel_states); - } } if (actionAttachButton != null) { actionAttachButton.setVisibility(View.GONE); @@ -4160,9 +4152,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa } if (message != null) { if (message.type == 11) { - NotificationCenter.getInstance().addToMemCache(51, message); - Intent intent = new Intent(getParentActivity(), GalleryImageViewer.class); - getParentActivity().startActivity(intent); + PhotoViewer.getInstance().openPhoto(message, ChatActivity.this); } else if (message.type == 8 || message.type == 9) { File f = null; String fileName = message.getFileName(); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChatProfileActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChatProfileActivity.java index 39ca78c03..cb42c1aa0 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChatProfileActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChatProfileActivity.java @@ -39,6 +39,7 @@ import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; +import org.telegram.objects.MessageObject; import org.telegram.ui.Cells.ChatOrUserCell; import org.telegram.ui.Views.ActionBar.ActionBarLayer; import org.telegram.ui.Views.ActionBar.ActionBarMenu; @@ -51,7 +52,7 @@ import java.util.Collections; import java.util.Comparator; import java.util.HashMap; -public class ChatProfileActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, ContactsActivity.ContactsActivityDelegate { +public class ChatProfileActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, ContactsActivity.ContactsActivityDelegate, PhotoViewer.PhotoViewerProvider { private ListView listView; private ListAdapter listViewAdapter; private int chat_id; @@ -90,7 +91,6 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen NotificationCenter.getInstance().addObserver(this, MessagesController.closeChats); chat_id = getArguments().getInt("chat_id", 0); - info = (TLRPC.ChatParticipants)NotificationCenter.getInstance().getFromMemCache(5); updateOnlineCount(); MessagesController.getInstance().getMediaCount(-chat_id, classGuid, true); avatarUpdater.delegate = new AvatarUpdater.AvatarUpdaterDelegate() { @@ -336,6 +336,37 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen } } + @Override + public PhotoViewer.PlaceProviderObject getPlaceForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation) { + if (fileLocation == null) { + return null; + } + TLRPC.Chat chat = MessagesController.getInstance().chats.get(chat_id); + if (chat != null && chat.photo != null && chat.photo.photo_big != null) { + TLRPC.FileLocation photoBig = chat.photo.photo_big; + if (photoBig.local_id == fileLocation.local_id && photoBig.volume_id == fileLocation.volume_id && photoBig.dc_id == fileLocation.dc_id) { + int count = listView.getChildCount(); + for (int a = 0; a < count; a++) { + View view = listView.getChildAt(a); + BackupImageView avatarImage = (BackupImageView)view.findViewById(R.id.settings_avatar_image); + if (avatarImage != null) { + int coords[] = new int[2]; + avatarImage.getLocationInWindow(coords); + PhotoViewer.PlaceProviderObject object = new PhotoViewer.PlaceProviderObject(); + object.viewX = coords[0]; + object.viewY = coords[1] - Utilities.statusBarHeight; + object.parentView = listView; + object.imageReceiver = avatarImage.imageReceiver; + object.thumb = object.imageReceiver.getBitmap(); + object.size = -1; + return object; + } + } + } + } + return null; + } + public void didReceivedNotification(int id, Object... args) { if (id == MessagesController.updateInterfaces) { int mask = (Integer)args[0]; @@ -377,6 +408,10 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen } } + public void setChatInfo(TLRPC.ChatParticipants chatParticipants) { + info = chatParticipants; + } + private void updateVisibleRows(int mask) { if (listView == null) { return; @@ -441,9 +476,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen if (action == 0) { TLRPC.Chat chat = MessagesController.getInstance().chats.get(chat_id); if (chat.photo != null && chat.photo.photo_big != null) { - NotificationCenter.getInstance().addToMemCache(53, chat.photo.photo_big); - Intent intent = new Intent(getParentActivity(), GalleryImageViewer.class); - getParentActivity().startActivity(intent); + PhotoViewer.getInstance().openPhoto(chat.photo.photo_big, this); } } else if (action == 1) { avatarUpdater.openCamera(); @@ -606,10 +639,13 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen } TLRPC.FileLocation photo = null; + TLRPC.FileLocation photoBig = null; if (chat.photo != null) { photo = chat.photo.photo_small; + photoBig = chat.photo.photo_big; } avatarImage.setImage(photo, "50_50", Utilities.getGroupAvatarForId(chat.id)); + avatarImage.imageReceiver.setVisible(!PhotoViewer.getInstance().isShowingImage(photoBig), false); return view; } else if (type == 1) { if (view == null) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/DocumentSelectActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/DocumentSelectActivity.java index fabf713f3..4c7c0edb2 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/DocumentSelectActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/DocumentSelectActivity.java @@ -21,7 +21,6 @@ import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; -import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; @@ -423,12 +422,10 @@ public class DocumentSelectActivity extends BaseFragment { imageView.setImageBitmap(null); typeTextView.setText(item.ext.toUpperCase().substring(0, Math.min(item.ext.length(), 4))); imageView.setImage(item.thumb, "55_42", 0); - imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setVisibility(View.VISIBLE); typeTextView.setVisibility(View.VISIBLE); } else if (item.icon != 0) { imageView.setImageResource(item.icon); - imageView.setScaleType(ImageView.ScaleType.CENTER); imageView.setVisibility(View.VISIBLE); typeTextView.setVisibility(View.GONE); } else { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/GalleryImageViewer.java b/TMessagesProj/src/main/java/org/telegram/ui/GalleryImageViewer.java deleted file mode 100644 index 0c865c868..000000000 --- a/TMessagesProj/src/main/java/org/telegram/ui/GalleryImageViewer.java +++ /dev/null @@ -1,1084 +0,0 @@ -/* - * This is the source code of Telegram for Android v. 1.3.2. - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2013. - */ - -package org.telegram.ui; - -import android.content.Intent; -import android.graphics.Point; -import android.net.Uri; -import android.os.Bundle; -import android.os.Parcelable; -import android.support.v4.view.PagerAdapter; -import android.support.v4.view.ViewPager; -import android.support.v7.app.ActionBar; -import android.view.Display; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; -import android.view.ViewTreeObserver; -import android.view.animation.Animation; -import android.view.animation.TranslateAnimation; -import android.widget.ImageView; -import android.widget.ProgressBar; -import android.widget.TextView; - -import org.telegram.messenger.ConnectionsManager; -import org.telegram.messenger.FileLog; -import org.telegram.messenger.LocaleController; -import org.telegram.messenger.MediaController; -import org.telegram.objects.PhotoObject; -import org.telegram.ui.Views.AbstractGalleryActivity; -import org.telegram.ui.Views.GalleryViewPager; -import org.telegram.ui.Views.PZSImageView; -import org.telegram.messenger.TLRPC; -import org.telegram.objects.MessageObject; -import org.telegram.messenger.FileLoader; -import org.telegram.messenger.MessagesController; -import org.telegram.messenger.NotificationCenter; -import org.telegram.messenger.R; -import org.telegram.messenger.UserConfig; -import org.telegram.messenger.Utilities; - -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; - -public class GalleryImageViewer extends AbstractGalleryActivity implements NotificationCenter.NotificationCenterDelegate { - private TextView nameTextView; - private TextView timeTextView; - private View bottomView; - private TextView fakeTitleView; - private LocalPagerAdapter localPagerAdapter; - private GalleryViewPager mViewPager; - private boolean withoutBottom = false; - private boolean fromAll = false; - private boolean isVideo = false; - private boolean needSearchMessage = false; - private boolean loadingMore = false; - private TextView title; - private boolean ignoreSet = false; - private ProgressBar loadingProgress; - private String currentFileName; - private int user_id = 0; - private Point displaySize = new Point(); - private boolean cancelRunning = false; - - private ArrayList imagesArrTemp = new ArrayList(); - private HashMap imagesByIdsTemp = new HashMap(); - - private long currentDialog = 0; - private int totalCount = 0; - private int classGuid; - private boolean firstLoad = true; - private boolean cacheEndReached = false; - - public static int needShowAllMedia = 2000; - - private final static int gallery_menu_save = 1; - private final static int gallery_menu_showall = 2; - - @SuppressWarnings("unchecked") - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - Display display = getWindowManager().getDefaultDisplay(); - if(android.os.Build.VERSION.SDK_INT < 13) { - displaySize.set(display.getWidth(), display.getHeight()); - } else { - display.getSize(displaySize); - } - - classGuid = ConnectionsManager.getInstance().generateClassGuid(); - setContentView(R.layout.gallery_layout); - - ActionBar actionBar = getSupportActionBar(); - actionBar.setDisplayShowTitleEnabled(true); - actionBar.setDisplayShowHomeEnabled(false); - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setDisplayUseLogoEnabled(false); - actionBar.setTitle(getString(R.string.Gallery)); - actionBar.show(); - - mViewPager = (GalleryViewPager)findViewById(R.id.gallery_view_pager); - ImageView shareButton = (ImageView)findViewById(R.id.gallery_view_share_button); - ImageView deleteButton = (ImageView) findViewById(R.id.gallery_view_delete_button); - nameTextView = (TextView)findViewById(R.id.gallery_view_name_text); - timeTextView = (TextView)findViewById(R.id.gallery_view_time_text); - bottomView = findViewById(R.id.gallery_view_bottom_view); - fakeTitleView = (TextView)findViewById(R.id.fake_title_view); - loadingProgress = (ProgressBar)findViewById(R.id.action_progress); - - title = (TextView)findViewById(R.id.action_bar_title); - if (title == null) { - final int titleId = getResources().getIdentifier("action_bar_title", "id", "android"); - title = (TextView)findViewById(titleId); - } - - NotificationCenter.getInstance().addObserver(this, FileLoader.FileDidFailedLoad); - NotificationCenter.getInstance().addObserver(this, FileLoader.FileDidLoaded); - NotificationCenter.getInstance().addObserver(this, FileLoader.FileLoadProgressChanged); - NotificationCenter.getInstance().addObserver(this, MessagesController.mediaCountDidLoaded); - NotificationCenter.getInstance().addObserver(this, MessagesController.mediaDidLoaded); - NotificationCenter.getInstance().addObserver(this, MessagesController.userPhotosLoaded); - NotificationCenter.getInstance().addObserver(this, 658); - - Integer index = null; - if (localPagerAdapter == null) { - final MessageObject file = (MessageObject)NotificationCenter.getInstance().getFromMemCache(51); - final TLRPC.FileLocation fileLocation = (TLRPC.FileLocation)NotificationCenter.getInstance().getFromMemCache(53); - final ArrayList messagesArr = (ArrayList)NotificationCenter.getInstance().getFromMemCache(54); - index = (Integer)NotificationCenter.getInstance().getFromMemCache(55); - Integer uid = (Integer)NotificationCenter.getInstance().getFromMemCache(56); - if (uid != null) { - user_id = uid; - } - - if (file != null) { - ArrayList imagesArr = new ArrayList(); - HashMap imagesByIds = new HashMap(); - imagesArr.add(file); - if (file.messageOwner.action == null || file.messageOwner.action instanceof TLRPC.TL_messageActionEmpty) { - needSearchMessage = true; - imagesByIds.put(file.messageOwner.id, file); - if (file.messageOwner.dialog_id != 0) { - currentDialog = file.messageOwner.dialog_id; - } else { - if (file.messageOwner.to_id.chat_id != 0) { - currentDialog = -file.messageOwner.to_id.chat_id; - } else { - if (file.messageOwner.to_id.user_id == UserConfig.clientUserId) { - currentDialog = file.messageOwner.from_id; - } else { - currentDialog = file.messageOwner.to_id.user_id; - } - } - } - } - localPagerAdapter = new LocalPagerAdapter(imagesArr, imagesByIds); - } else if (fileLocation != null) { - ArrayList arr = new ArrayList(); - arr.add(fileLocation); - withoutBottom = true; - deleteButton.setVisibility(View.INVISIBLE); - nameTextView.setVisibility(View.INVISIBLE); - timeTextView.setVisibility(View.INVISIBLE); - localPagerAdapter = new LocalPagerAdapter(arr); - } else if (messagesArr != null) { - MessageObject object = null; - for (MessageObject messageObject : messagesArr) { - if (messageObject.messageOwner.dialog_id != 0 || messageObject.messageOwner.to_id != null) { - object = messageObject; - break; - } - } - - ArrayList imagesArr = new ArrayList(); - HashMap imagesByIds = new HashMap(); - imagesArr.addAll(messagesArr); - Collections.reverse(imagesArr); - for (MessageObject message : imagesArr) { - imagesByIds.put(message.messageOwner.id, message); - } - index = imagesArr.size() - index - 1; - - - if (object.messageOwner.dialog_id != 0) { - currentDialog = object.messageOwner.dialog_id; - } else { - if (object.messageOwner.to_id == null) { - finish(); - } - if (object.messageOwner.to_id.chat_id != 0) { - currentDialog = -object.messageOwner.to_id.chat_id; - } else { - if (object.messageOwner.to_id.user_id == UserConfig.clientUserId) { - currentDialog = object.messageOwner.from_id; - } else { - currentDialog = object.messageOwner.to_id.user_id; - } - } - } - localPagerAdapter = new LocalPagerAdapter(imagesArr, imagesByIds); - } - } - - mViewPager.setPageMargin(Utilities.dp(20)); - mViewPager.setOffscreenPageLimit(1); - mViewPager.setAdapter(localPagerAdapter); - - if (index != null) { - fromAll = true; - mViewPager.setCurrentItem(index); - } - - shareButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - try { - TLRPC.InputFileLocation file = getCurrentFile(); - File f = new File(Utilities.getCacheDir(), currentFileName); - if (f.exists()) { - Intent intent = new Intent(Intent.ACTION_SEND); - if (file instanceof TLRPC.TL_inputVideoFileLocation) { - intent.setType("video/mp4"); - } else { - intent.setType("image/jpeg"); - } - intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f)); - startActivity(intent); - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - }); - - deleteButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (mViewPager == null || localPagerAdapter == null || localPagerAdapter.imagesArr == null) { - return; - } - int item = mViewPager.getCurrentItem(); - MessageObject obj = localPagerAdapter.imagesArr.get(item); - if (obj.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENT) { - ArrayList arr = new ArrayList(); - arr.add(obj.messageOwner.id); - MessagesController.getInstance().deleteMessages(arr, null, null); - finish(); - } - } - }); - - if (currentDialog != 0 && totalCount == 0) { - MessagesController.getInstance().getMediaCount(currentDialog, classGuid, true); - } - if (user_id != 0) { - MessagesController.getInstance().loadUserPhotos(user_id, 0, 30, 0, true, classGuid); - } - checkCurrentFile(); - } - - @Override - protected void onDestroy() { - super.onDestroy(); - NotificationCenter.getInstance().removeObserver(this, FileLoader.FileDidFailedLoad); - NotificationCenter.getInstance().removeObserver(this, FileLoader.FileDidLoaded); - NotificationCenter.getInstance().removeObserver(this, FileLoader.FileLoadProgressChanged); - NotificationCenter.getInstance().removeObserver(this, MessagesController.mediaCountDidLoaded); - NotificationCenter.getInstance().removeObserver(this, MessagesController.mediaDidLoaded); - NotificationCenter.getInstance().removeObserver(this, MessagesController.userPhotosLoaded); - NotificationCenter.getInstance().removeObserver(this, 658); - ConnectionsManager.getInstance().cancelRpcsForClassGuid(classGuid); - } - - @SuppressWarnings("unchecked") - @Override - public void didReceivedNotification(int id, final Object... args) { - if (id == FileLoader.FileDidFailedLoad) { - String location = (String)args[0]; - if (currentFileName != null && currentFileName.equals(location)) { - if (loadingProgress != null) { - loadingProgress.setVisibility(View.GONE); - } - if (localPagerAdapter != null) { - localPagerAdapter.updateViews(); - } - } - } else if (id == FileLoader.FileDidLoaded) { - String location = (String)args[0]; - if (currentFileName != null && currentFileName.equals(location)) { - if (loadingProgress != null) { - loadingProgress.setVisibility(View.GONE); - } - if (localPagerAdapter != null) { - localPagerAdapter.updateViews(); - } - } - } else if (id == FileLoader.FileLoadProgressChanged) { - String location = (String)args[0]; - if (currentFileName != null && currentFileName.equals(location)) { - Float progress = (Float)args[1]; - if (loadingProgress != null) { - loadingProgress.setVisibility(View.VISIBLE); - loadingProgress.setProgress((int)(progress * 100)); - } - if (localPagerAdapter != null) { - localPagerAdapter.updateViews(); - } - } - } else if (id == MessagesController.userPhotosLoaded) { - int guid = (Integer)args[4]; - int uid = (Integer)args[0]; - if (user_id == uid && classGuid == guid) { - boolean fromCache = (Boolean)args[3]; - TLRPC.FileLocation currentLocation = null; - int setToImage = -1; - if (localPagerAdapter != null && mViewPager != null) { - int idx = mViewPager.getCurrentItem(); - if (localPagerAdapter.imagesArrLocations.size() > idx) { - currentLocation = localPagerAdapter.imagesArrLocations.get(idx); - } - } - ArrayList photos = (ArrayList)args[5]; - if (photos.isEmpty()) { - return; - } - ArrayList arr = new ArrayList(); - for (TLRPC.Photo photo : photos) { - if (photo instanceof TLRPC.TL_photoEmpty) { - continue; - - } - TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(photo.sizes, 800, 800); - if (sizeFull != null) { - if (currentLocation != null && sizeFull.location.local_id == currentLocation.local_id && sizeFull.location.volume_id == currentLocation.volume_id) { - setToImage = arr.size(); - } - arr.add(sizeFull.location); - } - } - mViewPager.setAdapter(null); - int count = mViewPager.getChildCount(); - for (int a = 0; a < count; a++) { - View child = mViewPager.getChildAt(0); - mViewPager.removeView(child); - } - mViewPager.mCurrentView = null; - needSearchMessage = false; - ignoreSet = true; - mViewPager.setAdapter(localPagerAdapter = new LocalPagerAdapter(arr)); - mViewPager.invalidate(); - ignoreSet = false; - if (setToImage != -1) { - mViewPager.setCurrentItem(setToImage); - } else { - mViewPager.setCurrentItem(0); - } - if (fromCache) { - MessagesController.getInstance().loadUserPhotos(user_id, 0, 30, 0, false, classGuid); - } - } - } else if (id == MessagesController.mediaCountDidLoaded) { - long uid = (Long)args[0]; - if (uid == currentDialog) { - if ((int)currentDialog != 0) { - boolean fromCache = (Boolean)args[2]; - if (fromCache) { - MessagesController.getInstance().getMediaCount(currentDialog, classGuid, false); - } - } - totalCount = (Integer)args[1]; - if (needSearchMessage && firstLoad) { - firstLoad = false; - MessagesController.getInstance().loadMedia(currentDialog, 0, 100, 0, true, classGuid); - loadingMore = true; - } else { - if (mViewPager != null && localPagerAdapter != null && localPagerAdapter.imagesArr != null) { - final int pos = (totalCount - localPagerAdapter.imagesArr.size()) + mViewPager.getCurrentItem() + 1; - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - getSupportActionBar().setTitle(LocaleController.formatString("Of", R.string.Of, pos, totalCount)); - if (title != null) { - fakeTitleView.setText(LocaleController.formatString("Of", R.string.Of, pos, totalCount)); - fakeTitleView.measure(View.MeasureSpec.makeMeasureSpec(400, View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.AT_MOST)); - title.setWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); - title.setMaxWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); - } - } - }); - } - } - } - } else if (id == MessagesController.mediaDidLoaded) { - long uid = (Long)args[0]; - int guid = (Integer)args[4]; - if (uid == currentDialog && guid == classGuid) { - if (localPagerAdapter == null || localPagerAdapter.imagesArr == null) { - return; - } - loadingMore = false; - ArrayList arr = (ArrayList)args[2]; - boolean fromCache = (Boolean)args[3]; - cacheEndReached = !fromCache; - if (needSearchMessage) { - if (arr.isEmpty()) { - needSearchMessage = false; - return; - } - int foundIndex = -1; - - int index = mViewPager.getCurrentItem(); - MessageObject currentMessage = localPagerAdapter.imagesArr.get(index); - - int added = 0; - for (MessageObject message : arr) { - if (!imagesByIdsTemp.containsKey(message.messageOwner.id)) { - added++; - imagesArrTemp.add(0, message); - imagesByIdsTemp.put(message.messageOwner.id, message); - if (message.messageOwner.id == currentMessage.messageOwner.id) { - foundIndex = arr.size() - added; - } - } - } - if (added == 0) { - totalCount = imagesArrTemp.size(); - } - - if (foundIndex != -1) { - mViewPager.setAdapter(null); - int count = mViewPager.getChildCount(); - for (int a = 0; a < count; a++) { - View child = mViewPager.getChildAt(0); - mViewPager.removeView(child); - } - mViewPager.mCurrentView = null; - needSearchMessage = false; - ignoreSet = true; - mViewPager.setAdapter(localPagerAdapter = new LocalPagerAdapter(imagesArrTemp, imagesByIdsTemp)); - mViewPager.invalidate(); - ignoreSet = false; - mViewPager.setCurrentItem(foundIndex); - imagesArrTemp = null; - imagesByIdsTemp = null; - } else { - if (!cacheEndReached || !arr.isEmpty()) { - MessageObject lastMessage = imagesArrTemp.get(0); - loadingMore = true; - MessagesController.getInstance().loadMedia(currentDialog, 0, 100, lastMessage.messageOwner.id, true, classGuid); - } - } - } else { - int added = 0; - for (MessageObject message : arr) { - if (!localPagerAdapter.imagesByIds.containsKey(message.messageOwner.id)) { - added++; - localPagerAdapter.imagesArr.add(0, message); - localPagerAdapter.imagesByIds.put(message.messageOwner.id, message); - } - } - if (arr.isEmpty() && !fromCache) { - totalCount = arr.size(); - } - if (added != 0) { - int current = mViewPager.getCurrentItem(); - ignoreSet = true; - imagesArrTemp = new ArrayList(localPagerAdapter.imagesArr); - imagesByIdsTemp = new HashMap(localPagerAdapter.imagesByIds); - mViewPager.setAdapter(localPagerAdapter = new LocalPagerAdapter(imagesArrTemp, imagesByIdsTemp)); - mViewPager.invalidate(); - ignoreSet = false; - imagesArrTemp = null; - imagesByIdsTemp = null; - mViewPager.setCurrentItem(current + added); - } else { - totalCount = localPagerAdapter.imagesArr.size(); - } - } - } - } else if (id == 658) { - try { - if (!isFinishing()) { - finish(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - private TLRPC.InputFileLocation getCurrentFile() { - if (mViewPager == null || localPagerAdapter == null) { - return null; - } - int item = mViewPager.getCurrentItem(); - if (withoutBottom) { - TLRPC.FileLocation sizeFull = localPagerAdapter.imagesArrLocations.get(item); - TLRPC.TL_inputFileLocation location = new TLRPC.TL_inputFileLocation(); - location.local_id = sizeFull.local_id; - location.volume_id = sizeFull.volume_id; - location.id = sizeFull.dc_id; - location.secret = sizeFull.secret; - return location; - } else { - MessageObject message = localPagerAdapter.imagesArr.get(item); - if (message.messageOwner instanceof TLRPC.TL_messageService) { - if (message.messageOwner.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) { - TLRPC.FileLocation sizeFull = message.messageOwner.action.newUserPhoto.photo_big; - TLRPC.TL_inputFileLocation location = new TLRPC.TL_inputFileLocation(); - location.local_id = sizeFull.local_id; - location.volume_id = sizeFull.volume_id; - location.id = sizeFull.dc_id; - location.secret = sizeFull.secret; - return location; - } else { - TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(message.messageOwner.action.photo.sizes, 800, 800); - if (sizeFull != null) { - TLRPC.TL_inputFileLocation location = new TLRPC.TL_inputFileLocation(); - location.local_id = sizeFull.location.local_id; - location.volume_id = sizeFull.location.volume_id; - location.id = sizeFull.location.dc_id; - location.secret = sizeFull.location.secret; - return location; - } - } - } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { - TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(message.messageOwner.media.photo.sizes, 800, 800); - if (sizeFull != null) { - TLRPC.TL_inputFileLocation location = new TLRPC.TL_inputFileLocation(); - location.local_id = sizeFull.location.local_id; - location.volume_id = sizeFull.location.volume_id; - location.id = sizeFull.location.dc_id; - location.secret = sizeFull.location.secret; - return location; - } - } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { - TLRPC.TL_inputVideoFileLocation location = new TLRPC.TL_inputVideoFileLocation(); - location.volume_id = message.messageOwner.media.video.dc_id; - location.id = message.messageOwner.media.video.id; - return location; - } - } - return null; - } - - @Override - public void topBtn() { - if (getSupportActionBar().isShowing()) { - getSupportActionBar().hide(); - startViewAnimation(bottomView, false); - } else { - bottomView.setVisibility(View.VISIBLE); - getSupportActionBar().show(); - startViewAnimation(bottomView, true); - } - } - - @Override - public void didShowMessageObject(MessageObject obj) { - TLRPC.User user = MessagesController.getInstance().users.get(obj.messageOwner.from_id); - if (user != null) { - nameTextView.setText(Utilities.formatName(user.first_name, user.last_name)); - timeTextView.setText(LocaleController.formatterYearMax.format(((long)obj.messageOwner.date) * 1000)); - } else { - nameTextView.setText(""); - } - isVideo = obj.messageOwner.media != null && obj.messageOwner.media instanceof TLRPC.TL_messageMediaVideo; - - if (obj.messageOwner instanceof TLRPC.TL_messageService) { - if (obj.messageOwner.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) { - TLRPC.FileLocation file = obj.messageOwner.action.newUserPhoto.photo_big; - currentFileName = file.volume_id + "_" + file.local_id + ".jpg"; - } else { - ArrayList sizes = obj.messageOwner.action.photo.sizes; - if (sizes.size() > 0) { - TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(sizes, 800, 800); - if (sizeFull != null) { - currentFileName = sizeFull.location.volume_id + "_" + sizeFull.location.local_id + ".jpg"; - } - } - } - } else if (obj.messageOwner.media != null) { - TLRPC.InputFileLocation file = getCurrentFile(); - if (file != null) { - if (obj.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { - currentFileName = file.volume_id + "_" + file.id + ".mp4"; - } else if (obj.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { - currentFileName = file.volume_id + "_" + file.local_id + ".jpg"; - } - } else { - currentFileName = null; - } - } else { - currentFileName = null; - } - - checkCurrentFile(); - supportInvalidateOptionsMenu(); - } - - private void checkCurrentFile() { - if (currentFileName != null) { - File f = new File(Utilities.getCacheDir(), currentFileName); - if (f.exists()) { - loadingProgress.setVisibility(View.GONE); - } else { - loadingProgress.setVisibility(View.VISIBLE); - Float progress = FileLoader.getInstance().fileProgresses.get(currentFileName); - if (progress != null) { - loadingProgress.setProgress((int)(progress * 100)); - } else { - loadingProgress.setProgress(0); - } - } - } else { - loadingProgress.setVisibility(View.GONE); - } - if (isVideo) { - if (!FileLoader.getInstance().isLoadingFile(currentFileName)) { - loadingProgress.setVisibility(View.GONE); - } else { - loadingProgress.setVisibility(View.VISIBLE); - } - } - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - menu.add(Menu.NONE, gallery_menu_save, Menu.NONE, LocaleController.getString("SaveToGallery", R.string.SaveToGallery)); - if (!withoutBottom) { - menu.add(Menu.NONE, gallery_menu_showall, Menu.NONE, LocaleController.getString("ShowAllMedia", R.string.ShowAllMedia)); - } - return super.onCreateOptionsMenu(menu); - } - - @Override - public boolean onMenuOpened(int featureId, Menu menu) { - if (currentFileName != null) { - File f = new File(Utilities.getCacheDir(), currentFileName); - if (f.exists()) { - return super.onMenuOpened(featureId, menu); - } - } - try { - closeOptionsMenu(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - return false; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - int itemId = item.getItemId(); - processSelectedMenu(itemId); - return true; - } - - @Override - public void onConfigurationChanged(android.content.res.Configuration newConfig) { - super.onConfigurationChanged(newConfig); - fixLayout(); - } - - private void fixLayout() { - if (mViewPager != null) { - ViewTreeObserver obs = mViewPager.getViewTreeObserver(); - obs.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { - @Override - public boolean onPreDraw() { - try { - mViewPager.beginFakeDrag(); - if (mViewPager.isFakeDragging()) { - mViewPager.fakeDragBy(1); - mViewPager.endFakeDrag(); - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } - mViewPager.getViewTreeObserver().removeOnPreDrawListener(this); - return false; - } - }); - } - } - - @Override - public void onBackPressed() { - super.onBackPressed(); - cancelRunning = true; - mViewPager.setAdapter(null); - localPagerAdapter = null; - finish(); - System.gc(); - } - - private void processSelectedMenu(int itemId) { - switch (itemId) { - case android.R.id.home: - cancelRunning = true; - if (mViewPager != null) { - mViewPager.setAdapter(null); - } - localPagerAdapter = null; - finish(); - System.gc(); - break; - case gallery_menu_save: - if (currentFileName == null) { - return; - } - if (isVideo) { - MediaController.saveFile(currentFileName, null, this, 1, null); - } else { - MediaController.saveFile(currentFileName, null, this, 0, null); - } - break; -// case R.id.gallery_menu_send: { -// Intent intent = new Intent(this, MessagesActivity.class); -// intent.putExtra("onlySelect", true); -// startActivityForResult(intent, 10); -// break; -// } - case gallery_menu_showall: { - if (fromAll) { - finish(); - } else { - if (localPagerAdapter != null && localPagerAdapter.imagesArr != null && !localPagerAdapter.imagesArr.isEmpty() && currentDialog != 0) { - finish(); - NotificationCenter.getInstance().postNotificationName(needShowAllMedia, currentDialog); - } - } - } - } - } - - /*@Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - super.onActivityResult(requestCode, resultCode, data); - if (resultCode == RESULT_OK) { - if (requestCode == 10) { - int chatId = data.getIntExtra("chatId", 0); - int userId = data.getIntExtra("userId", 0); - int dialog_id = 0; - if (chatId != 0) { - dialog_id = -chatId; - } else if (userId != 0) { - dialog_id = userId; - } - TLRPC.FileLocation location = getCurrentFile(); - if (dialog_id != 0 && location != null) { - Intent intent = new Intent(GalleryImageViewer.this, ChatActivity.class); - if (chatId != 0) { - intent.putExtra("chatId", chatId); - } else { - intent.putExtra("userId", userId); - } - startActivity(intent); - NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats); - finish(); - if (withoutBottom) { - MessagesController.getInstance().sendMessage(location, dialog_id); - } else { - int item = mViewPager.getCurrentItem(); - MessageObject obj = localPagerAdapter.imagesArr.get(item); - MessagesController.getInstance().sendMessage(obj, dialog_id); - } - } - } - } - }*/ - - private void startViewAnimation(final View panel, boolean up) { - Animation animation; - if (!up) { - animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, - Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f); - animation.setAnimationListener(new Animation.AnimationListener() { - @Override - public void onAnimationStart(Animation animation) { - - } - - @Override - public void onAnimationEnd(Animation animation) { - panel.setVisibility(View.INVISIBLE); - } - - @Override - public void onAnimationRepeat(Animation animation) { - - } - }); - animation.setDuration(400); - } else { - animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, - Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.0f); - animation.setAnimationListener(new Animation.AnimationListener() { - @Override - public void onAnimationStart(Animation animation) { - panel.setVisibility(View.VISIBLE); - } - - @Override - public void onAnimationEnd(Animation animation) { - - } - - @Override - public void onAnimationRepeat(Animation animation) { - - } - }); - animation.setDuration(100); - } - panel.startAnimation(animation); - } - - public class LocalPagerAdapter extends PagerAdapter { - public ArrayList imagesArr; - public HashMap imagesByIds; - private ArrayList imagesArrLocations; - - public LocalPagerAdapter(ArrayList _imagesArr, HashMap _imagesByIds) { - imagesArr = _imagesArr; - imagesByIds = _imagesByIds; - } - - public LocalPagerAdapter(ArrayList locations) { - imagesArrLocations = locations; - } - - @Override - public void setPrimaryItem(ViewGroup container, final int position, Object object) { - super.setPrimaryItem(container, position, object); - if (container == null || object == null || ignoreSet) { - return; - } - ((GalleryViewPager) container).mCurrentView = (PZSImageView)((View) object).findViewById(R.id.page_image); - if (imagesArr != null) { - didShowMessageObject(imagesArr.get(position)); - if (totalCount != 0 && !needSearchMessage) { - if (imagesArr.size() < totalCount && !loadingMore && position < 5) { - MessageObject lastMessage = imagesArr.get(0); - MessagesController.getInstance().loadMedia(currentDialog, 0, 100, lastMessage.messageOwner.id, !cacheEndReached, classGuid); - loadingMore = true; - } - - - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - getSupportActionBar().setTitle(LocaleController.formatString("Of", R.string.Of, (totalCount - imagesArr.size()) + position + 1, totalCount)); - if (title != null) { - fakeTitleView.setText(LocaleController.formatString("Of", R.string.Of, (totalCount - imagesArr.size()) + position + 1, totalCount)); - fakeTitleView.measure(View.MeasureSpec.makeMeasureSpec(400, View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.AT_MOST)); - title.setWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); - title.setMaxWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); - } - } - }); - - } - } else if (imagesArrLocations != null) { - TLRPC.FileLocation file = imagesArrLocations.get(position); - currentFileName = file.volume_id + "_" + file.local_id + ".jpg"; - checkCurrentFile(); - if (imagesArrLocations.size() > 1) { - Utilities.RunOnUIThread(new Runnable() { - @Override - public void run() { - getSupportActionBar().setTitle(LocaleController.formatString("Of", R.string.Of, position + 1, imagesArrLocations.size())); - if (title != null) { - fakeTitleView.setText(LocaleController.formatString("Of", R.string.Of, position + 1, imagesArrLocations.size())); - fakeTitleView.measure(View.MeasureSpec.makeMeasureSpec(400, View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.AT_MOST)); - title.setWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); - title.setMaxWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); - } - } - }); - } else { - getSupportActionBar().setTitle(getString(R.string.Gallery)); - } - } - } - - public void updateViews() { - int count = mViewPager.getChildCount(); - for (int a = 0; a < count; a++) { - View v = mViewPager.getChildAt(a); - final TextView playButton = (TextView)v.findViewById(R.id.action_button); - MessageObject message = (MessageObject)playButton.getTag(); - if (message != null) { - processViews(playButton, message); - } - } - } - - public void processViews(TextView playButton, MessageObject message) { - if (message.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SENDING && message.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SEND_ERROR) { - playButton.setVisibility(View.VISIBLE); - String fileName = message.messageOwner.media.video.dc_id + "_" + message.messageOwner.media.video.id + ".mp4"; - boolean load = false; - if (message.messageOwner.attachPath != null && message.messageOwner.attachPath.length() != 0) { - File f = new File(message.messageOwner.attachPath); - if (f.exists()) { - playButton.setText(getString(R.string.ViewVideo)); - } else { - load = true; - } - } else { - File cacheFile = new File(Utilities.getCacheDir(), fileName); - if (cacheFile.exists()) { - playButton.setText(getString(R.string.ViewVideo)); - } else { - load = true; - } - } - if (load) { - Float progress = FileLoader.getInstance().fileProgresses.get(fileName); - if (FileLoader.getInstance().isLoadingFile(fileName)) { - playButton.setText(LocaleController.getString("CancelDownload", R.string.CancelDownload)); - } else { - playButton.setText(String.format("%s %.1f MB", LocaleController.getString("DOWNLOAD", R.string.DOWNLOAD), message.messageOwner.media.video.size / 1024.0f / 1024.0f)); - } - } - } - } - - @Override - public int getItemPosition(Object object) { - return POSITION_NONE; - } - - @Override - public Object instantiateItem(View collection, int position) { - View view = View.inflate(collection.getContext(), R.layout.gallery_page_layout, null); - ((ViewPager) collection).addView(view, 0); - - PZSImageView iv = (PZSImageView)view.findViewById(R.id.page_image); - final TextView playButton = (TextView)view.findViewById(R.id.action_button); - - if (imagesArr != null) { - final MessageObject message = imagesArr.get(position); - view.setTag(message.messageOwner.id); - if (message.messageOwner instanceof TLRPC.TL_messageService) { - if (message.messageOwner.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) { - iv.isVideo = false; - iv.setImage(message.messageOwner.action.newUserPhoto.photo_big, null, 0, -1); - } else { - ArrayList sizes = message.messageOwner.action.photo.sizes; - iv.isVideo = false; - if (sizes.size() > 0) { - TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(sizes, 800, 800); - if (message.imagePreview != null) { - iv.setImage(sizeFull.location, null, message.imagePreview, sizeFull.size); - } else { - iv.setImage(sizeFull.location, null, 0, sizeFull.size); - } - } - } - } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { - ArrayList sizes = message.messageOwner.media.photo.sizes; - iv.isVideo = false; - if (sizes.size() > 0) { - TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(sizes, 800, 800); - if (message.imagePreview != null) { - iv.setImage(sizeFull.location, null, message.imagePreview, sizeFull.size); - } else { - iv.setImage(sizeFull.location, null, 0, sizeFull.size); - } - } - } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { - processViews(playButton, message); - playButton.setTag(message); - - playButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - boolean loadFile = false; - String fileName = message.messageOwner.media.video.dc_id + "_" + message.messageOwner.media.video.id + ".mp4"; - if (message.messageOwner.attachPath != null && message.messageOwner.attachPath.length() != 0) { - File f = new File(message.messageOwner.attachPath); - if (f.exists()) { - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.setDataAndType(Uri.fromFile(f), "video/mp4"); - startActivity(intent); - } else { - loadFile = true; - } - } else { - File cacheFile = new File(Utilities.getCacheDir(), fileName); - if (cacheFile.exists()) { - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.setDataAndType(Uri.fromFile(cacheFile), "video/mp4"); - startActivity(intent); - } else { - loadFile = true; - } - } - if (loadFile) { - if (!FileLoader.getInstance().isLoadingFile(fileName)) { - FileLoader.getInstance().loadFile(message.messageOwner.media.video, null, null, null); - } else { - FileLoader.getInstance().cancelLoadFile(message.messageOwner.media.video, null, null, null); - } - checkCurrentFile(); - processViews(playButton, message); - } - } - }); - iv.isVideo = true; - if (message.messageOwner.media.video.thumb instanceof TLRPC.TL_photoCachedSize) { - iv.setImageBitmap(message.imagePreview); - } else { - if (message.messageOwner.media.video.thumb != null) { - iv.setImage(message.messageOwner.media.video.thumb.location, null, 0, message.messageOwner.media.video.thumb.size); - } - } - } - } else { - iv.isVideo = false; - iv.setImage(imagesArrLocations.get(position), null, 0, -1); - } - - return view; - } - - @Override - public void destroyItem(View collection, int position, Object view) { - ((ViewPager)collection).removeView((View)view); - PZSImageView iv = (PZSImageView)((View)view).findViewById(R.id.page_image); - if (cancelRunning) { - FileLoader.getInstance().cancelLoadingForImageView(iv); - } - iv.clearImage(); - } - - @Override - public int getCount() { - if (imagesArr != null) { - return imagesArr.size(); - } else if (imagesArrLocations != null) { - return imagesArrLocations.size(); - } else { - return 0; - } - } - - @Override - public boolean isViewFromObject(View view, Object object) { - return view == object; - } - - @Override - public Parcelable saveState() { - return null; - } - - @Override - public void restoreState(Parcelable state, ClassLoader loader) { - - } - - @Override - public void finishUpdate(View container) { - - } - - @Override - public void startUpdate(View container) { - - } - } -} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java index 5d2ba0e80..55cc58220 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java @@ -103,7 +103,6 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen NotificationCenter.getInstance().addObserver(this, 701); NotificationCenter.getInstance().addObserver(this, 702); NotificationCenter.getInstance().addObserver(this, 703); - NotificationCenter.getInstance().addObserver(this, GalleryImageViewer.needShowAllMedia); statusView = getLayoutInflater().inflate(R.layout.updating_state_layout, null); statusBackground = statusView.findViewById(R.id.back_button_background); @@ -601,7 +600,6 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen NotificationCenter.getInstance().removeObserver(this, 701); NotificationCenter.getInstance().removeObserver(this, 702); NotificationCenter.getInstance().removeObserver(this, 703); - NotificationCenter.getInstance().removeObserver(this, GalleryImageViewer.needShowAllMedia); if (notificationView != null) { notificationView.hide(false); notificationView.destroy(); @@ -642,17 +640,13 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen startActivity(intent2); onFinish(); finish(); - } else if (id == GalleryImageViewer.needShowAllMedia) { - long dialog_id = (Long)args[0]; - if (dialog_id != 0) { - Bundle args2 = new Bundle(); - args2.putLong("dialog_id", dialog_id); - presentFragment(new MediaActivity(args2), false, true); - } } else if (id == 658) { - Integer push_user_id = (Integer)NotificationCenter.getInstance().getFromMemCache("push_user_id", 0); - Integer push_chat_id = (Integer)NotificationCenter.getInstance().getFromMemCache("push_chat_id", 0); - Integer push_enc_id = (Integer)NotificationCenter.getInstance().getFromMemCache("push_enc_id", 0); + if (PhotoViewer.getInstance().isVisible()) { + PhotoViewer.getInstance().closePhoto(false); + } + Integer push_chat_id = (Integer)args[0]; + Integer push_user_id = (Integer)args[1]; + Integer push_enc_id = (Integer)args[2]; if (push_user_id != 0) { NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats); @@ -750,7 +744,7 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen @Override public void onBackPressed() { if (PhotoViewer.getInstance().isVisible()) { - PhotoViewer.getInstance().closePhoto(); + PhotoViewer.getInstance().closePhoto(true); } else { super.onBackPressed(); } @@ -759,7 +753,7 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen @Override public boolean onPreIme() { if (PhotoViewer.getInstance().isVisible()) { - PhotoViewer.getInstance().closePhoto(); + PhotoViewer.getInstance().closePhoto(true); return true; } return super.onPreIme(); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LocationActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/LocationActivity.java index 813d93bac..d246d92f3 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LocationActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LocationActivity.java @@ -60,7 +60,6 @@ public class LocationActivity extends BaseFragment implements NotificationCenter @Override public boolean onFragmentCreate() { super.onFragmentCreate(); - messageObject = (MessageObject)NotificationCenter.getInstance().getFromMemCache(0); NotificationCenter.getInstance().addObserver(this, MessagesController.closeChats); if (messageObject != null) { NotificationCenter.getInstance().addObserver(this, MessagesController.updateInterfaces); @@ -294,6 +293,10 @@ public class LocationActivity extends BaseFragment implements NotificationCenter } } + public void setMessageObject(MessageObject message) { + messageObject = message; + } + @Override public void didReceivedNotification(int id, Object... args) { if (id == MessagesController.updateInterfaces) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/MediaActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/MediaActivity.java index b9e49ec92..c83042933 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/MediaActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/MediaActivity.java @@ -10,7 +10,6 @@ package org.telegram.ui; import android.app.Activity; import android.content.Context; -import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.LayoutInflater; @@ -32,6 +31,7 @@ import org.telegram.objects.MessageObject; import org.telegram.messenger.MessagesController; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; +import org.telegram.objects.PhotoObject; import org.telegram.ui.Views.ActionBar.ActionBarLayer; import org.telegram.ui.Views.BackupImageView; import org.telegram.ui.Views.ActionBar.BaseFragment; @@ -39,7 +39,7 @@ import org.telegram.ui.Views.ActionBar.BaseFragment; import java.util.ArrayList; import java.util.HashMap; -public class MediaActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate { +public class MediaActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, PhotoViewer.PhotoViewerProvider { private GridView listView; private ListAdapter listAdapter; private ArrayList messages = new ArrayList(); @@ -114,10 +114,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView adapterView, View view, int i, long l) { - NotificationCenter.getInstance().addToMemCache(54, messages); - NotificationCenter.getInstance().addToMemCache(55, i); - Intent intent = new Intent(getParentActivity(), GalleryImageViewer.class); - getParentActivity().startActivity(intent); + PhotoViewer.getInstance().openPhoto(messages, i, MediaActivity.this); } }); if (loading && messages.isEmpty()) { @@ -266,6 +263,41 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No fixLayout(); } + @Override + public PhotoViewer.PlaceProviderObject getPlaceForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation) { + if (messageObject == null) { + return null; + } + int count = listView.getChildCount(); + + for (int a = 0; a < count; a++) { + View view = listView.getChildAt(a); + BackupImageView imageView = (BackupImageView)view.findViewById(R.id.media_photo_image); + if (imageView != null) { + int num = (Integer)imageView.getTag(); + if (num < 0 || num >= messages.size()) { + continue; + } + MessageObject message = messages.get(num); + if (message != null && message.messageOwner.id == messageObject.messageOwner.id) { + int coords[] = new int[2]; + imageView.getLocationInWindow(coords); + PhotoViewer.PlaceProviderObject object = new PhotoViewer.PlaceProviderObject(); + object.viewX = coords[0]; + object.viewY = coords[1] - Utilities.statusBarHeight; + object.parentView = listView; + object.imageReceiver = imageView.imageReceiver; + object.thumb = object.imageReceiver.getBitmap(); + return object; + } + } + } + return null; +// NotificationCenter.getInstance().addToMemCache(54, messages); TODO +// NotificationCenter.getInstance().addToMemCache(55, i); + + } + private void fixLayout() { if (listView != null) { ViewTreeObserver obs = listView.getViewTreeObserver(); @@ -351,20 +383,20 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No view.setLayoutParams(params); BackupImageView imageView = (BackupImageView)view.findViewById(R.id.media_photo_image); + imageView.setTag(i); if (message.messageOwner.media != null && message.messageOwner.media.photo != null && !message.messageOwner.media.photo.sizes.isEmpty()) { ArrayList sizes = message.messageOwner.media.photo.sizes; - boolean set = false; - if (!set) { - if (message.imagePreview != null) { - imageView.setImageBitmap(message.imagePreview); - } else { - imageView.setImage(message.messageOwner.media.photo.sizes.get(0).location, null, R.drawable.photo_placeholder_in); - } + if (message.imagePreview != null) { + imageView.setImageBitmap(message.imagePreview); + } else { + TLRPC.PhotoSize photoSize = PhotoObject.getClosestPhotoSizeWithSize(message.messageOwner.media.photo.sizes, 80, 80); + imageView.setImage(photoSize.location, null, R.drawable.photo_placeholder_in); } } else { imageView.setImageResource(R.drawable.photo_placeholder_in); } + imageView.imageReceiver.setVisible(!PhotoViewer.getInstance().isShowingImage(message), false); } else if (type == 1) { MessageObject message = messages.get(i); if (view == null) { @@ -378,6 +410,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No TextView textView = (TextView)view.findViewById(R.id.chat_video_time); BackupImageView imageView = (BackupImageView)view.findViewById(R.id.media_photo_image); + imageView.setTag(i); if (message.messageOwner.media.video != null && message.messageOwner.media.video.thumb != null) { int duration = message.messageOwner.media.video.duration; @@ -394,6 +427,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No textView.setVisibility(View.GONE); imageView.setImageResource(R.drawable.photo_placeholder_in); } + imageView.imageReceiver.setVisible(!PhotoViewer.getInstance().isShowingImage(message), false); } else if (type == 2) { if (view == null) { LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/PhotoViewer.java b/TMessagesProj/src/main/java/org/telegram/ui/PhotoViewer.java index 30ae0ee9a..e9cee70ff 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/PhotoViewer.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/PhotoViewer.java @@ -14,44 +14,195 @@ import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.app.Activity; import android.content.Context; +import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; -import android.graphics.Paint; import android.graphics.PixelFormat; -import android.graphics.Rect; +import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; +import android.net.Uri; +import android.os.Bundle; +import android.text.TextUtils; +import android.view.GestureDetector; import android.view.Gravity; import android.view.MotionEvent; +import android.view.VelocityTracker; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.WindowManager; +import android.view.animation.AlphaAnimation; +import android.view.animation.DecelerateInterpolator; import android.widget.FrameLayout; +import android.widget.ImageView; +import android.widget.ProgressBar; +import android.widget.TextView; +import org.telegram.messenger.ConnectionsManager; +import org.telegram.messenger.FileLoader; +import org.telegram.messenger.FileLog; +import org.telegram.messenger.LocaleController; +import org.telegram.messenger.MediaController; +import org.telegram.messenger.MessagesController; +import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; +import org.telegram.messenger.TLRPC; +import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; +import org.telegram.objects.MessageObject; +import org.telegram.objects.PhotoObject; import org.telegram.ui.Views.ActionBar.ActionBar; +import org.telegram.ui.Views.ActionBar.ActionBarActivity; import org.telegram.ui.Views.ActionBar.ActionBarLayer; import org.telegram.ui.Views.ActionBar.ActionBarMenu; +import org.telegram.ui.Views.ActionBar.ActionBarMenuItem; +import org.telegram.ui.Views.ClippingImageView; import org.telegram.ui.Views.ImageReceiver; -public class PhotoViewer { - private FrameLayout containerView; - private ClippingImageView animatingImageView; - private ColorDrawable backgroundDrawable = new ColorDrawable(0xff000000); - private View parentView; - private int imageX, imageY; - private ImageReceiver currentImageReceiver; - private boolean animationInProgress = false; +import java.io.File; +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; + +public class PhotoViewer implements NotificationCenter.NotificationCenterDelegate, GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener { + private int classGuid; + private PhotoViewerProvider placeProvider; + private boolean isVisible; + + private Activity parentActivity; + private ActionBar actionBar; private ActionBarLayer actionBarLayer; - private Activity parentActivity; - private WindowManager.LayoutParams windowLayoutParams; - private boolean isVisible; private boolean isActionBarVisible = true; - public static class FrameLayoutTest extends FrameLayout { - public FrameLayoutTest(Context context) { + private WindowManager.LayoutParams windowLayoutParams; + private FrameLayoutTouchListener containerView; + private ClippingImageView animatingImageView; + private FrameLayout bottomLayout; + private TextView nameTextView; + private TextView dateTextView; + private ProgressBar progressBar; + private ActionBarMenuItem menuItem; + private ColorDrawable backgroundDrawable = new ColorDrawable(0xff000000); + private OverlayView currentOverlay; + private boolean canShowBottom = true; + private boolean overlayViewVisible = true; + + private boolean animationInProgress = false; + private boolean disableShowCheck = false; + + private ImageReceiver leftImage = new ImageReceiver(); + private ImageReceiver centerImage = new ImageReceiver(); + private ImageReceiver rightImage = new ImageReceiver(); + private int currentIndex; + private MessageObject currentMessageObject; + private TLRPC.FileLocation currentFileLocation; + private String currentFileName; + private PlaceProviderObject currentPlaceObject; + private Bitmap currentThumb = null; + + private int avatarsUserId; + private long currentDialogId; + private int totalImagesCount; + private boolean isFirstLoading; + private boolean needSearchImageInArr; + private boolean loadingMoreImages; + private boolean cacheEndReached; + private boolean opennedFromMedia; + + private boolean draggingDown = false; + private float dragY; + private float translationX = 0; + private float translationY = 0; + private float scale = 1; + private float animateToX; + private float animateToY; + private float animateToScale; + private long animationDuration; + private long animationStartTime; + private GestureDetector gestureDetector; + private DecelerateInterpolator interpolator = new DecelerateInterpolator(); + private float pinchStartDistance = 0; + private float pinchStartScale = 1; + private float pinchCenterX; + private float pinchCenterY; + private float pinchStartX; + private float pinchStartY; + private float moveStartX; + private float moveStartY; + private float minX; + private float maxX; + private float minY; + private float maxY; + private boolean canZoom = true; + private boolean changingPage = false; + private boolean zooming = false; + private boolean moving = false; + private boolean doubleTap = false; + private boolean invalidCoords = false; + private boolean canDragDown = true; + private int switchImageAfterAnimation = 0; + private VelocityTracker velocityTracker = null; + + private ArrayList imagesArrTemp = new ArrayList(); + private HashMap imagesByIdsTemp = new HashMap(); + private ArrayList imagesArr = new ArrayList(); + private HashMap imagesByIds = new HashMap(); + private ArrayList imagesArrLocations = new ArrayList(); + private ArrayList imagesArrLocationsSizes = new ArrayList(); + + private final static int gallery_menu_save = 1; + private final static int gallery_menu_showall = 2; + private final static int gallery_menu_send = 3; + + private final static int PAGE_SPACING = Utilities.dp(30); + + private static class OverlayView extends FrameLayout { + + public TextView actionButton; + + public OverlayView(Context context) { + super(context); + + actionButton = new TextView(context); + actionButton.setBackgroundResource(R.drawable.system_black); + actionButton.setPadding(Utilities.dp(8), Utilities.dp(2), Utilities.dp(8), Utilities.dp(2)); + actionButton.setTextColor(0xffffffff); + actionButton.setTextSize(26); + actionButton.setGravity(Gravity.CENTER); + addView(actionButton); + LayoutParams layoutParams = (LayoutParams)actionButton.getLayoutParams(); + layoutParams.width = LayoutParams.WRAP_CONTENT; + layoutParams.height = LayoutParams.WRAP_CONTENT; + layoutParams.gravity = Gravity.CENTER; + actionButton.setLayoutParams(layoutParams); + actionButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + getInstance().onActionClick(OverlayView.this); + } + }); + } + } + + public static class PlaceProviderObject { + public ImageReceiver imageReceiver; + public int viewX; + public int viewY; + public View parentView; + public Bitmap thumb; + public int user_id; + public int index; + public int size; + } + + public static interface PhotoViewerProvider { + public abstract PlaceProviderObject getPlaceForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation); + } + + private static class FrameLayoutTouchListener extends FrameLayout { + public FrameLayoutTouchListener(Context context) { super(context); } @@ -59,97 +210,16 @@ public class PhotoViewer { public boolean onTouchEvent(MotionEvent event) { return getInstance().onTouchEvent(event); } - } - public static class ClippingImageView extends View { - private int clipBottom; - private int clipLeft; - private int clipRight; - private int clipTop; - private Rect drawRect; - private Paint paint; - private Bitmap bmp; - public onDrawListener drawListener; - - public static interface onDrawListener { - public abstract void onDraw(); + @Override + protected void onDraw(Canvas canvas) { + getInstance().onDraw(canvas); } - public ClippingImageView(Context paramContext) { - super(paramContext); - paint = new Paint(); - paint.setFilterBitmap(true); - drawRect = new Rect(); - } - - public int getClipBottom() { - return clipBottom; - } - - public int getClipHorizontal() { - return clipRight; - } - - public int getClipLeft() { - return clipLeft; - } - - public int getClipRight() { - return clipRight; - } - - public int getClipTop() { - return clipTop; - } - - public void onDraw(Canvas canvas) { - if (drawListener != null) { - drawListener.onDraw(); - } - if (bmp != null) { - canvas.save(); - canvas.clipRect(clipLeft / getScaleY(), clipTop / getScaleY(), getWidth() - clipRight / getScaleY(), getHeight() - clipBottom / getScaleY()); - drawRect.set(0, 0, getWidth(), getHeight()); - canvas.drawBitmap(this.bmp, null, drawRect, this.paint); - canvas.restore(); - } - } - - public void setClipBottom(int value) { - clipBottom = value; - invalidate(); - } - - public void setClipHorizontal(int value) { - clipRight = value; - clipLeft = value; - invalidate(); - } - - public void setClipLeft(int value) { - clipLeft = value; - invalidate(); - } - - public void setClipRight(int value) { - clipRight = value; - invalidate(); - } - - public void setClipTop(int value) { - clipTop = value; - invalidate(); - } - - public void setClipVertical(int value) { - clipBottom = value; - clipTop = value; - invalidate(); - } - - public void setImageBitmap(Bitmap bitmap) { - bmp = bitmap; - invalidate(); + @Override + protected void onLayout(boolean changed, int left, int top, int right, int bottom) { + super.onLayout(changed, left, top, right, bottom); + getInstance().onLayout(changed, left, top, right, bottom); } } @@ -167,19 +237,165 @@ public class PhotoViewer { return localInstance; } + @SuppressWarnings("unchecked") + @Override + public void didReceivedNotification(int id, Object... args) { + if (id == FileLoader.FileDidFailedLoad) { + String location = (String)args[0]; + if (currentFileName != null && currentFileName.equals(location)) { + progressBar.setVisibility(View.GONE); + updateActionOverlays(); + } + } else if (id == FileLoader.FileDidLoaded) { + String location = (String)args[0]; + if (currentFileName != null && currentFileName.equals(location)) { + progressBar.setVisibility(View.GONE); + updateActionOverlays(); + } + } else if (id == FileLoader.FileLoadProgressChanged) { + String location = (String)args[0]; + if (currentFileName != null && currentFileName.equals(location)) { + Float progress = (Float)args[1]; + progressBar.setVisibility(View.VISIBLE); + progressBar.setProgress((int)(progress * 100)); + } + } else if (id == MessagesController.userPhotosLoaded) { + int guid = (Integer)args[4]; + int uid = (Integer)args[0]; + if (avatarsUserId == uid && classGuid == guid) { + boolean fromCache = (Boolean)args[3]; + + int setToImage = -1; + ArrayList photos = (ArrayList)args[5]; + if (photos.isEmpty()) { + return; + } + imagesArrLocations.clear(); + imagesArrLocationsSizes.clear(); + for (TLRPC.Photo photo : photos) { + if (photo instanceof TLRPC.TL_photoEmpty) { + continue; + } + TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(photo.sizes, 640, 640); + if (sizeFull != null) { + if (currentFileLocation != null && sizeFull.location.local_id == currentFileLocation.local_id && sizeFull.location.volume_id == currentFileLocation.volume_id) { + setToImage = imagesArrLocations.size(); + } + imagesArrLocations.add(sizeFull.location); + imagesArrLocationsSizes.add(sizeFull.size); + } + } + needSearchImageInArr = false; + currentIndex = -1; + if (setToImage != -1) { + setImageIndex(setToImage, true); + } else { + setImageIndex(0, true); + } + if (fromCache) { + MessagesController.getInstance().loadUserPhotos(avatarsUserId, 0, 30, 0, false, classGuid); + } + } + } else if (id == MessagesController.mediaCountDidLoaded) { + long uid = (Long)args[0]; + if (uid == currentDialogId) { + if ((int)currentDialogId != 0 && (Boolean)args[2]) { + MessagesController.getInstance().getMediaCount(currentDialogId, classGuid, false); + } + totalImagesCount = (Integer)args[1]; + if (needSearchImageInArr && isFirstLoading) { + isFirstLoading = false; + loadingMoreImages = true; + MessagesController.getInstance().loadMedia(currentDialogId, 0, 100, 0, true, classGuid); + } else if (!imagesArr.isEmpty()) { + actionBarLayer.setTitle(LocaleController.formatString("Of", R.string.Of, (totalImagesCount - imagesArr.size()) + currentIndex + 1, totalImagesCount)); + } + } + } else if (id == MessagesController.mediaDidLoaded) { + long uid = (Long)args[0]; + int guid = (Integer)args[4]; + if (uid == currentDialogId && guid == classGuid) { + loadingMoreImages = false; + ArrayList arr = (ArrayList)args[2]; + boolean fromCache = (Boolean)args[3]; + cacheEndReached = !fromCache; + if (needSearchImageInArr) { + if (arr.isEmpty()) { + needSearchImageInArr = false; + return; + } + int foundIndex = -1; + + MessageObject currentMessage = imagesArr.get(currentIndex); + + int added = 0; + for (MessageObject message : arr) { + if (!imagesByIdsTemp.containsKey(message.messageOwner.id)) { + added++; + imagesArrTemp.add(0, message); + imagesByIdsTemp.put(message.messageOwner.id, message); + if (message.messageOwner.id == currentMessage.messageOwner.id) { + foundIndex = arr.size() - added; + } + } + } + if (added == 0) { + totalImagesCount = imagesArr.size(); + } + + if (foundIndex != -1) { + imagesArr.clear(); + imagesArr.addAll(imagesArrTemp); + imagesByIds.clear(); + imagesByIds.putAll(imagesByIdsTemp); + imagesArrTemp.clear(); + imagesByIdsTemp.clear(); + needSearchImageInArr = false; + currentIndex = -1; + setImageIndex(foundIndex, true); + } else { + if (!cacheEndReached || !arr.isEmpty() && added != 0) { + loadingMoreImages = true; + MessagesController.getInstance().loadMedia(currentDialogId, 0, 100, imagesArrTemp.get(0).messageOwner.id, true, classGuid); + } + } + } else { + int added = 0; + for (MessageObject message : arr) { + if (!imagesByIds.containsKey(message.messageOwner.id)) { + added++; + imagesArr.add(0, message); + imagesByIds.put(message.messageOwner.id, message); + } + } + if (arr.isEmpty() && !fromCache) { + totalImagesCount = arr.size(); + } + if (added != 0) { + int index = currentIndex; + currentIndex = -1; + setImageIndex(index + added, true); + } else { + totalImagesCount = imagesArr.size(); + } + } + } + } + } + public void setParentActivity(Activity activity) { parentActivity = activity; - containerView = new FrameLayoutTest(activity); + containerView = new FrameLayoutTouchListener(activity); + containerView.setBackgroundDrawable(backgroundDrawable); containerView.setFocusable(false); - containerView.setBackground(backgroundDrawable); 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.TYPE_SYSTEM_ALERT; + windowLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION; windowLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; animatingImageView = new ClippingImageView(containerView.getContext()); @@ -194,91 +410,793 @@ public class PhotoViewer { actionBar.setLayoutParams(layoutParams); actionBarLayer = actionBar.createLayer(); actionBarLayer.setDisplayHomeAsUpEnabled(true); - actionBarLayer.setTitle("Photo"); + actionBarLayer.setTitle(LocaleController.getString("Gallery", R.string.Gallery)); actionBar.setCurrentActionBarLayer(actionBarLayer); actionBarLayer.setActionBarMenuOnItemClick(new ActionBarLayer.ActionBarMenuOnItemClick() { @Override public void onItemClick(int id) { if (id == -1) { - closePhoto(); + closePhoto(true); + } else if (id == gallery_menu_save) { + if (currentFileName == null) { + return; + } + MediaController.saveFile(currentFileName, null, parentActivity, currentFileName.endsWith("mp4") ? 1 : 0, null); + } else if (id == gallery_menu_showall) { + if (opennedFromMedia) { + closePhoto(true); + } else if (currentDialogId != 0) { + closePhoto(false); + Bundle args2 = new Bundle(); + args2.putLong("dialog_id", currentDialogId); + ((ActionBarActivity)parentActivity).presentFragment(new MediaActivity(args2), false, true); + } + } else if (id == gallery_menu_send) { + /*Intent intent = new Intent(this, MessagesActivity.class); + intent.putExtra("onlySelect", true); + startActivityForResult(intent, 10); + if (requestCode == 10) { + int chatId = data.getIntExtra("chatId", 0); + int userId = data.getIntExtra("userId", 0); + int dialog_id = 0; + if (chatId != 0) { + dialog_id = -chatId; + } else if (userId != 0) { + dialog_id = userId; + } + TLRPC.FileLocation location = getCurrentFile(); + if (dialog_id != 0 && location != null) { + Intent intent = new Intent(GalleryImageViewer.this, ChatActivity.class); + if (chatId != 0) { + intent.putExtra("chatId", chatId); + } else { + intent.putExtra("userId", userId); + } + startActivity(intent); + NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats); + finish(); + if (withoutBottom) { + MessagesController.getInstance().sendMessage(location, dialog_id); + } else { + int item = mViewPager.getCurrentItem(); + MessageObject obj = localPagerAdapter.imagesArr.get(item); + MessagesController.getInstance().sendMessage(obj, dialog_id); + } + } + }*/ } } + + @Override + public boolean canOpenMenu() { + if (currentFileName != null) { + File f = new File(Utilities.getCacheDir(), currentFileName); + if (f.exists()) { + return true; + } + } + return false; + } }); ActionBarMenu menu = actionBarLayer.createMenu(); - menu.addItem(0, R.drawable.ic_ab_other_white); + menuItem = menu.addItem(0, R.drawable.ic_ab_other_white); + menuItem.addSubItem(gallery_menu_save, LocaleController.getString("SaveToGallery", R.string.SaveToGallery), 0); + menuItem.addSubItem(gallery_menu_showall, LocaleController.getString("ShowAllMedia", R.string.ShowAllMedia), 0); + + bottomLayout = new FrameLayout(containerView.getContext()); + containerView.addView(bottomLayout); + layoutParams = (FrameLayout.LayoutParams)bottomLayout.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = Utilities.dp(48); + layoutParams.gravity = Gravity.BOTTOM | Gravity.LEFT; + bottomLayout.setLayoutParams(layoutParams); + bottomLayout.setBackgroundColor(0xdd000000); + + ImageView shareButton = new ImageView(containerView.getContext()); + shareButton.setImageResource(R.drawable.ic_ab_share_white); + shareButton.setScaleType(ImageView.ScaleType.CENTER); + shareButton.setBackgroundResource(R.drawable.bar_selector_white); + bottomLayout.addView(shareButton); + layoutParams = (FrameLayout.LayoutParams) shareButton.getLayoutParams(); + layoutParams.width = Utilities.dp(50); + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + shareButton.setLayoutParams(layoutParams); + shareButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (parentActivity == null) { + return; + } + try { + String fileName = getFileName(currentIndex, null); + if (fileName == null) { + return; + } + File f = new File(Utilities.getCacheDir(), fileName); + if (f.exists()) { + Intent intent = new Intent(Intent.ACTION_SEND); + if (fileName.endsWith("mp4")) { + intent.setType("video/mp4"); + } else { + intent.setType("image/jpeg"); + } + intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f)); + parentActivity.startActivity(intent); + } + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + }); + + ImageView deleteButton = new ImageView(containerView.getContext()); + deleteButton.setImageResource(R.drawable.ic_ab_delete_white); + deleteButton.setScaleType(ImageView.ScaleType.CENTER); + deleteButton.setBackgroundResource(R.drawable.bar_selector_white); + bottomLayout.addView(deleteButton); + layoutParams = (FrameLayout.LayoutParams) deleteButton.getLayoutParams(); + layoutParams.width = Utilities.dp(50); + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.gravity = Gravity.RIGHT; + deleteButton.setLayoutParams(layoutParams); + deleteButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (currentIndex < 0 || currentIndex >= imagesArr.size()) { + return; + } + MessageObject obj = imagesArr.get(currentIndex); + if (obj.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENT) { + ArrayList arr = new ArrayList(); + arr.add(obj.messageOwner.id); + MessagesController.getInstance().deleteMessages(arr, null, null); + closePhoto(false); + } + } + }); + + nameTextView = new TextView(containerView.getContext()); + nameTextView.setTextSize(17); + nameTextView.setSingleLine(true); + nameTextView.setMaxLines(1); + nameTextView.setEllipsize(TextUtils.TruncateAt.END); + nameTextView.setTextColor(0xffffffff); + nameTextView.setGravity(Gravity.CENTER); + bottomLayout.addView(nameTextView); + layoutParams = (FrameLayout.LayoutParams)nameTextView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.gravity = Gravity.TOP; + layoutParams.leftMargin = Utilities.dp(60); + layoutParams.rightMargin = Utilities.dp(60); + layoutParams.topMargin = Utilities.dp(2); + nameTextView.setLayoutParams(layoutParams); + + dateTextView = new TextView(containerView.getContext()); + dateTextView.setTextSize(14); + dateTextView.setSingleLine(true); + dateTextView.setMaxLines(1); + dateTextView.setEllipsize(TextUtils.TruncateAt.END); + dateTextView.setTextColor(0xffb8bdbe); + dateTextView.setGravity(Gravity.CENTER); + bottomLayout.addView(dateTextView); + layoutParams = (FrameLayout.LayoutParams)dateTextView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.gravity = Gravity.TOP; + layoutParams.leftMargin = Utilities.dp(60); + layoutParams.rightMargin = Utilities.dp(60); + layoutParams.topMargin = Utilities.dp(26); + dateTextView.setLayoutParams(layoutParams); + + progressBar = new ProgressBar(containerView.getContext(), null, android.R.attr.progressBarStyleHorizontal); + progressBar.setVisibility(View.GONE); + progressBar.setMax(100); + progressBar.setProgressDrawable(parentActivity.getResources().getDrawable(R.drawable.photo_progress)); + containerView.addView(progressBar); + layoutParams = (FrameLayout.LayoutParams)progressBar.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = Utilities.dp(3); + layoutParams.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL; + layoutParams.leftMargin = Utilities.dp(6); + layoutParams.rightMargin = Utilities.dp(6); + layoutParams.bottomMargin = Utilities.dp(48); + progressBar.setLayoutParams(layoutParams); + + gestureDetector = new GestureDetector(containerView.getContext(), this); + gestureDetector.setOnDoubleTapListener(this); + + centerImage.parentView = new WeakReference(containerView); + leftImage.parentView = new WeakReference(containerView); + rightImage.parentView = new WeakReference(containerView); + + currentOverlay = new OverlayView(containerView.getContext()); + containerView.addView(currentOverlay); + currentOverlay.setVisibility(View.GONE); } - public void openPhoto(final ImageReceiver imageReceiver, final int x, final int y, final View parent) { - if (parentActivity == null || isVisible) { + private void toggleOverlayView(boolean show) { + if (overlayViewVisible == show) { return; } + overlayViewVisible = show; + if (android.os.Build.VERSION.SDK_INT >= 11) { + AnimatorSet animatorSet = new AnimatorSet(); + animatorSet.playTogether( + ObjectAnimator.ofFloat(currentOverlay, "alpha", show ? 1.0f : 0.0f) + ); + animatorSet.setDuration(200); + animatorSet.start(); + } else { + AlphaAnimation animation = new AlphaAnimation(show ? 0.0f : 1.0f, show ? 1.0f : 0.0f); + animation.setDuration(200); + animation.setFillAfter(true); + currentOverlay.startAnimation(animation); + } + } + + private void toggleActionBar(boolean show, boolean animated) { + if (show) { + actionBar.setVisibility(View.VISIBLE); + if (canShowBottom) { + bottomLayout.setVisibility(View.VISIBLE); + } + } + isActionBarVisible = show; + actionBar.setEnabled(show); + actionBarLayer.setEnabled(show); + bottomLayout.setEnabled(show); + if (android.os.Build.VERSION.SDK_INT >= 11) { + if (animated) { + AnimatorSet animatorSet = new AnimatorSet(); + animatorSet.playTogether( + ObjectAnimator.ofFloat(actionBar, "alpha", show ? 1.0f : 0.0f), + ObjectAnimator.ofFloat(bottomLayout, "alpha", show ? 1.0f : 0.0f) + ); + if (!show) { + animatorSet.addListener(new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd(Animator animation) { + actionBar.setVisibility(View.GONE); + if (canShowBottom) { + bottomLayout.setVisibility(View.GONE); + } + } + }); + } + + animatorSet.setDuration(250); + animatorSet.start(); + } else { + actionBar.setAlpha(show ? 1.0f : 0.0f); + bottomLayout.setAlpha(show ? 1.0f : 0.0f); + if (!show) { + actionBar.setVisibility(View.GONE); + if (canShowBottom) { + bottomLayout.setVisibility(View.GONE); + } + } + } + } else { + if (!show) { + actionBar.setVisibility(View.GONE); + if (canShowBottom) { + bottomLayout.setVisibility(View.GONE); + } + } + } + } + + private String getFileName(int index, TLRPC.InputFileLocation fileLocation) { + if (index < 0) { + return null; + } + TLRPC.InputFileLocation file = fileLocation != null ? fileLocation : getInputFileLocation(index); + if (file == null) { + return null; + } + if (!imagesArrLocations.isEmpty()) { + return file.volume_id + "_" + file.local_id + ".jpg"; + } else if (!imagesArr.isEmpty()) { + MessageObject message = imagesArr.get(index); + if (message.messageOwner instanceof TLRPC.TL_messageService) { + return file.volume_id + "_" + file.local_id + ".jpg"; + } else if (message.messageOwner.media != null) { + if (message.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { + return file.volume_id + "_" + file.id + ".mp4"; + } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { + return file.volume_id + "_" + file.local_id + ".jpg"; + } + } + } + return null; + } + + private TLRPC.FileLocation getFileLocation(int index, int size[]) { + if (index < 0) { + return null; + } + if (!imagesArrLocations.isEmpty()) { + if (index >= imagesArrLocations.size()) { + return null; + } + size[0] = imagesArrLocationsSizes.get(index); + return imagesArrLocations.get(index); + } else if (!imagesArr.isEmpty()) { + if (index >= imagesArr.size()) { + return null; + } + MessageObject message = imagesArr.get(index); + if (message.messageOwner instanceof TLRPC.TL_messageService) { + if (message.messageOwner.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) { + return message.messageOwner.action.newUserPhoto.photo_big; + } else { + TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(message.messageOwner.action.photo.sizes, 800, 800); + if (sizeFull != null) { + size[0] = sizeFull.size; + return sizeFull.location; + } + } + } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto && message.messageOwner.media.photo != null) { + TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(message.messageOwner.media.photo.sizes, 800, 800); + if (sizeFull != null) { + size[0] = sizeFull.size; + return sizeFull.location; + } + } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaVideo && message.messageOwner.media.video != null && message.messageOwner.media.video.thumb != null) { + size[0] = message.messageOwner.media.video.thumb.size; + return message.messageOwner.media.video.thumb.location; + } + } + return null; + } + + private TLRPC.InputFileLocation getInputFileLocation(int index) { + if (index < 0) { + return null; + } + if (!imagesArrLocations.isEmpty()) { + if (index >= imagesArrLocations.size()) { + return null; + } + TLRPC.FileLocation sizeFull = imagesArrLocations.get(index); + TLRPC.TL_inputFileLocation location = new TLRPC.TL_inputFileLocation(); + location.local_id = sizeFull.local_id; + location.volume_id = sizeFull.volume_id; + location.id = sizeFull.dc_id; + location.secret = sizeFull.secret; + return location; + } else if (!imagesArr.isEmpty()) { + if (index >= imagesArr.size()) { + return null; + } + MessageObject message = imagesArr.get(index); + if (message.messageOwner instanceof TLRPC.TL_messageService) { + if (message.messageOwner.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) { + TLRPC.FileLocation sizeFull = message.messageOwner.action.newUserPhoto.photo_big; + TLRPC.TL_inputFileLocation location = new TLRPC.TL_inputFileLocation(); + location.local_id = sizeFull.local_id; + location.volume_id = sizeFull.volume_id; + location.id = sizeFull.dc_id; + location.secret = sizeFull.secret; + return location; + } else { + TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(message.messageOwner.action.photo.sizes, 800, 800); + if (sizeFull != null) { + TLRPC.TL_inputFileLocation location = new TLRPC.TL_inputFileLocation(); + location.local_id = sizeFull.location.local_id; + location.volume_id = sizeFull.location.volume_id; + location.id = sizeFull.location.dc_id; + location.secret = sizeFull.location.secret; + return location; + } + } + } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { + TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(message.messageOwner.media.photo.sizes, 800, 800); + if (sizeFull != null) { + TLRPC.TL_inputFileLocation location = new TLRPC.TL_inputFileLocation(); + location.local_id = sizeFull.location.local_id; + location.volume_id = sizeFull.location.volume_id; + location.id = sizeFull.location.dc_id; + location.secret = sizeFull.location.secret; + return location; + } + } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { + TLRPC.TL_inputVideoFileLocation location = new TLRPC.TL_inputVideoFileLocation(); + location.volume_id = message.messageOwner.media.video.dc_id; + location.id = message.messageOwner.media.video.id; + return location; + } + } + return null; + } + + private void updateActionOverlays() { + if (currentMessageObject == null) { + currentOverlay.setVisibility(View.GONE); + return; + } + if (currentFileName.endsWith("mp4")) { + if (currentMessageObject.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SENDING && currentMessageObject.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SEND_ERROR) { + currentOverlay.setVisibility(View.VISIBLE); + boolean load = false; + if (currentMessageObject.messageOwner.attachPath != null && currentMessageObject.messageOwner.attachPath.length() != 0) { + File f = new File(currentMessageObject.messageOwner.attachPath); + if (f.exists()) { + currentOverlay.actionButton.setText(LocaleController.getString("ViewVideo", R.string.ViewVideo)); + } else { + load = true; + } + } else { + File cacheFile = new File(Utilities.getCacheDir(), currentFileName); + if (cacheFile.exists()) { + currentOverlay.actionButton.setText(LocaleController.getString("ViewVideo", R.string.ViewVideo)); + } else { + load = true; + } + } + if (load) { + Float progress = FileLoader.getInstance().fileProgresses.get(currentFileName); + if (FileLoader.getInstance().isLoadingFile(currentFileName)) { + currentOverlay.actionButton.setText(LocaleController.getString("CancelDownload", R.string.CancelDownload)); + progressBar.setVisibility(View.VISIBLE); + } else { + currentOverlay.actionButton.setText(String.format("%s %s", LocaleController.getString("DOWNLOAD", R.string.DOWNLOAD), Utilities.formatFileSize(currentMessageObject.messageOwner.media.video.size))); + progressBar.setVisibility(View.GONE); + } + } + } + } else { + currentOverlay.setVisibility(View.GONE); + } + } + + private void onPhotoShow(final MessageObject messageObject, final TLRPC.FileLocation fileLocation, final ArrayList messages, int index, final PlaceProviderObject object) { + classGuid = ConnectionsManager.getInstance().generateClassGuid(); + currentMessageObject = null; + currentFileLocation = null; + currentIndex = -1; + currentFileName = null; + avatarsUserId = 0; + currentDialogId = 0; + totalImagesCount = 0; + isFirstLoading = true; + needSearchImageInArr = false; + loadingMoreImages = false; + cacheEndReached = false; + opennedFromMedia = false; + imagesArr.clear(); + imagesArrLocations.clear(); + imagesArrLocationsSizes.clear(); + imagesByIds.clear(); + imagesArrTemp.clear(); + imagesByIdsTemp.clear(); + currentThumb = object.thumb; + + if (messageObject != null && messages == null) { + imagesArr.add(messageObject); + if (messageObject.messageOwner.action == null || messageObject.messageOwner.action instanceof TLRPC.TL_messageActionEmpty) { + needSearchImageInArr = true; + imagesByIds.put(messageObject.messageOwner.id, messageObject); + if (messageObject.messageOwner.dialog_id != 0) { + currentDialogId = messageObject.messageOwner.dialog_id; + } else { + if (messageObject.messageOwner.to_id.chat_id != 0) { + currentDialogId = -messageObject.messageOwner.to_id.chat_id; + } else { + if (messageObject.messageOwner.to_id.user_id == UserConfig.clientUserId) { + currentDialogId = messageObject.messageOwner.from_id; + } else { + currentDialogId = messageObject.messageOwner.to_id.user_id; + } + } + } + menuItem.showSubItem(gallery_menu_showall); + } else { + menuItem.hideSubItem(gallery_menu_showall); + } + bottomLayout.setVisibility(View.VISIBLE); + canShowBottom = true; + setImageIndex(0, true); + } else if (fileLocation != null) { + avatarsUserId = object.user_id; + imagesArrLocations.add(fileLocation); + imagesArrLocationsSizes.add(object.size); + bottomLayout.setVisibility(View.GONE); + menuItem.hideSubItem(gallery_menu_showall); + setImageIndex(0, true); + canShowBottom = false; + } else if (messages != null) { + imagesArr.addAll(messages); + Collections.reverse(imagesArr); + for (MessageObject message : imagesArr) { + imagesByIds.put(message.messageOwner.id, message); + } + index = imagesArr.size() - index - 1; + + if (messageObject.messageOwner.dialog_id != 0) { + currentDialogId = messageObject.messageOwner.dialog_id; + } else { + if (messageObject.messageOwner.to_id == null) { + closePhoto(false); + return; + } + if (messageObject.messageOwner.to_id.chat_id != 0) { + currentDialogId = -messageObject.messageOwner.to_id.chat_id; + } else { + if (messageObject.messageOwner.to_id.user_id == UserConfig.clientUserId) { + currentDialogId = messageObject.messageOwner.from_id; + } else { + currentDialogId = messageObject.messageOwner.to_id.user_id; + } + } + } + opennedFromMedia = true; + setImageIndex(index, true); + } + + if (currentDialogId != 0 && totalImagesCount == 0) { + MessagesController.getInstance().getMediaCount(currentDialogId, classGuid, true); + } else if (avatarsUserId != 0) { + MessagesController.getInstance().loadUserPhotos(avatarsUserId, 0, 30, 0, true, classGuid); + } + } + + public void setImageIndex(int index, boolean init) { + if (currentIndex == index) { + return; + } + if (!init) { + currentThumb = null; + } + int prevIndex = currentIndex; + currentIndex = index; + currentFileName = getFileName(index, null); + + if (!imagesArr.isEmpty()) { + currentMessageObject = imagesArr.get(currentIndex); + TLRPC.User user = MessagesController.getInstance().users.get(currentMessageObject.messageOwner.from_id); + if (user != null) { + nameTextView.setText(Utilities.formatName(user.first_name, user.last_name)); + } else { + nameTextView.setText(""); + } + dateTextView.setText(LocaleController.formatterYearMax.format(((long) currentMessageObject.messageOwner.date) * 1000)); + + if (totalImagesCount != 0 && !needSearchImageInArr) { + if (imagesArr.size() < totalImagesCount && !loadingMoreImages && currentIndex < 5) { + MessageObject lastMessage = imagesArr.get(0); + MessagesController.getInstance().loadMedia(currentDialogId, 0, 100, lastMessage.messageOwner.id, !cacheEndReached, classGuid); + loadingMoreImages = true; + } + actionBarLayer.setTitle(LocaleController.formatString("Of", R.string.Of, (totalImagesCount - imagesArr.size()) + currentIndex + 1, totalImagesCount)); + } + updateActionOverlays(); + } else if (!imagesArrLocations.isEmpty()) { + currentFileLocation = imagesArrLocations.get(index); + if (imagesArrLocations.size() > 1) { + actionBarLayer.setTitle(LocaleController.formatString("Of", R.string.Of, currentIndex + 1, imagesArrLocations.size())); + } + } + + if (!init) { + if (currentPlaceObject != null) { + currentPlaceObject.imageReceiver.setVisible(true, true); + } + } + currentPlaceObject = placeProvider.getPlaceForPhoto(currentMessageObject, currentFileLocation); + if (!init) { + if (currentPlaceObject != null) { + currentPlaceObject.imageReceiver.setVisible(false, true); + } + } + + draggingDown = false; + translationX = 0; + translationY = 0; + scale = 1; + animateToX = 0; + animateToY = 0; + animateToScale = 1; + animationDuration = 0; + animationStartTime = 0; + + pinchStartDistance = 0; + pinchStartScale = 1; + pinchCenterX = 0; + pinchCenterY = 0; + pinchStartX = 0; + pinchStartY = 0; + moveStartX = 0; + moveStartY = 0; + zooming = false; + moving = false; + doubleTap = false; + invalidCoords = false; + canDragDown = true; + changingPage = false; + switchImageAfterAnimation = 0; + canZoom = !currentFileName.endsWith("mp4"); + updateMinMax(scale); + + if (prevIndex == -1) { + setIndexToImage(centerImage, currentIndex); + setIndexToImage(rightImage, currentIndex + 1); + setIndexToImage(leftImage, currentIndex - 1); + } else { + if (prevIndex > currentIndex) { + ImageReceiver temp = rightImage; + rightImage = centerImage; + centerImage = leftImage; + leftImage = temp; + setIndexToImage(leftImage, currentIndex - 1); + } else if (prevIndex < currentIndex) { + ImageReceiver temp = leftImage; + leftImage = centerImage; + centerImage = rightImage; + rightImage = temp; + setIndexToImage(rightImage, currentIndex + 1); + } + } + + if (currentFileName != null) { + File f = new File(Utilities.getCacheDir(), currentFileName); + if (f.exists()) { + progressBar.setVisibility(View.GONE); + } else { + if (currentFileName.endsWith("mp4")) { + if (!FileLoader.getInstance().isLoadingFile(currentFileName)) { + progressBar.setVisibility(View.GONE); + } else { + progressBar.setVisibility(View.VISIBLE); + } + } else { + progressBar.setVisibility(View.VISIBLE); + } + Float progress = FileLoader.getInstance().fileProgresses.get(currentFileName); + if (progress != null) { + progressBar.setProgress((int)(progress * 100)); + } else { + progressBar.setProgress(0); + } + } + } else { + progressBar.setVisibility(View.GONE); + } + } + + private void setIndexToImage(ImageReceiver imageReceiver, int index) { + int size[] = new int[1]; + TLRPC.FileLocation fileLocation = getFileLocation(index, size); + + if (fileLocation != null) { + MessageObject messageObject = null; + if (!imagesArr.isEmpty()) { + messageObject = imagesArr.get(index); + } + + if (messageObject != null && messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { + if (messageObject.imagePreview != null) { + imageReceiver.setImageBitmap(messageObject.imagePreview); + } else if (messageObject.messageOwner.media.video.thumb != null) { + Bitmap placeHolder = null; + if (currentThumb != null && imageReceiver == centerImage) { + placeHolder = currentThumb; + } + imageReceiver.setImage(fileLocation, null, placeHolder != null ? new BitmapDrawable(null, placeHolder) : null, size[0]); + } else { + imageReceiver.setImageBitmap((Bitmap)null); + } + } else { + Bitmap placeHolder = null; + if (messageObject != null) { + placeHolder = messageObject.imagePreview; + } + if (currentThumb != null && imageReceiver == centerImage) { + placeHolder = currentThumb; + } + imageReceiver.setImage(fileLocation, null, placeHolder != null ? new BitmapDrawable(null, placeHolder) : null, size[0]); + } + } else { + imageReceiver.setImageBitmap((Bitmap)null); + } + } + + public boolean isShowingImage(MessageObject object) { + return !disableShowCheck && object != null && currentMessageObject != null && currentMessageObject.messageOwner.id == object.messageOwner.id; + } + + public boolean isShowingImage(TLRPC.FileLocation object) { + return !disableShowCheck && object != null && currentFileLocation != null && object.local_id == currentFileLocation.local_id && object.volume_id == currentFileLocation.volume_id && object.dc_id == currentFileLocation.dc_id; + } + + public void openPhoto(final MessageObject messageObject, final PhotoViewerProvider provider) { + openPhoto(messageObject, null, null, 0, provider); + } + + public void openPhoto(final TLRPC.FileLocation fileLocation, final PhotoViewerProvider provider) { + openPhoto(null, fileLocation, null, 0, provider); + } + + public void openPhoto(final ArrayList messages, final int index, final PhotoViewerProvider provider) { + openPhoto(messages.get(index), null, messages, index, provider); + } + + public void openPhoto(final MessageObject messageObject, final TLRPC.FileLocation fileLocation, final ArrayList messages, final int index, final PhotoViewerProvider provider) { + if (parentActivity == null || isVisible || provider == null || animationInProgress || messageObject == null && fileLocation == null && messages == null) { + return; + } + final PlaceProviderObject object = provider.getPlaceForPhoto(messageObject, fileLocation); + if (object == null) { + return; + } + + actionBarLayer.setTitle(LocaleController.getString("Gallery", R.string.Gallery)); + NotificationCenter.getInstance().addObserver(this, FileLoader.FileDidFailedLoad); + NotificationCenter.getInstance().addObserver(this, FileLoader.FileDidLoaded); + NotificationCenter.getInstance().addObserver(this, FileLoader.FileLoadProgressChanged); + NotificationCenter.getInstance().addObserver(this, MessagesController.mediaCountDidLoaded); + NotificationCenter.getInstance().addObserver(this, MessagesController.mediaDidLoaded); + NotificationCenter.getInstance().addObserver(this, MessagesController.userPhotosLoaded); + + placeProvider = provider; WindowManager wm = (WindowManager) parentActivity.getSystemService(Context.WINDOW_SERVICE); wm.addView(containerView, windowLayoutParams); - if(android.os.Build.VERSION.SDK_INT >= 11) { - if (animationInProgress) { - return; - } - isVisible = true; - animationInProgress = true; - toggleActionBar(true, false); - parentView = parent; - imageX = x; - imageY = y; + if (velocityTracker == null) { + velocityTracker = VelocityTracker.obtain(); + } + + disableShowCheck = true; + onPhotoShow(messageObject, fileLocation, messages, index, object); + isVisible = true; + backgroundDrawable.setAlpha(255); + toggleActionBar(true, false); + overlayViewVisible = true; + + if(android.os.Build.VERSION.SDK_INT >= 11) { + Utilities.lockOrientation(parentActivity); + + animationInProgress = true; - currentImageReceiver = imageReceiver; animatingImageView.setVisibility(View.VISIBLE); - containerView.invalidate(); - animatingImageView.invalidate(); - animatingImageView.setImageBitmap(imageReceiver.getBitmap()); + animatingImageView.setImageBitmap(object.thumb); + + animatingImageView.setAlpha(1.0f); + animatingImageView.setPivotX(0); + animatingImageView.setPivotY(0); + animatingImageView.setScaleX(1); + animatingImageView.setScaleY(1); + animatingImageView.setTranslationX(object.viewX + object.imageReceiver.drawRegion.left); + animatingImageView.setTranslationY(object.viewY + object.imageReceiver.drawRegion.top); + final ViewGroup.LayoutParams layoutParams = animatingImageView.getLayoutParams(); + layoutParams.width = object.imageReceiver.drawRegion.right - object.imageReceiver.drawRegion.left; + layoutParams.height = object.imageReceiver.drawRegion.bottom - object.imageReceiver.drawRegion.top; + animatingImageView.setLayoutParams(layoutParams); containerView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { containerView.getViewTreeObserver().removeOnPreDrawListener(this); - animatingImageView.drawListener = new ClippingImageView.onDrawListener() { - @Override - public void onDraw() { - animatingImageView.drawListener = null; - animatingImageView.post(new Runnable() { - @Override - public void run() { - imageReceiver.setVisible(false); - } - }); - } - }; - animatingImageView.setPivotX(0); - animatingImageView.setPivotY(0); - animatingImageView.setScaleX(1); - animatingImageView.setScaleY(1); - animatingImageView.setTranslationX(x + imageReceiver.drawRegion.left); - animatingImageView.setTranslationY(y + imageReceiver.drawRegion.top); - ViewGroup.LayoutParams layoutParams = animatingImageView.getLayoutParams(); - layoutParams.width = imageReceiver.drawRegion.right - imageReceiver.drawRegion.left; - layoutParams.height = imageReceiver.drawRegion.bottom - imageReceiver.drawRegion.top; - animatingImageView.setLayoutParams(layoutParams); - - - float scaleX = (float)Utilities.displaySize.x / layoutParams.width; - float scaleY = (float)(Utilities.displaySize.y - Utilities.statusBarHeight) / layoutParams.height; + float scaleX = (float) Utilities.displaySize.x / layoutParams.width; + float scaleY = (float) (Utilities.displaySize.y - Utilities.statusBarHeight) / layoutParams.height; float scale = scaleX > scaleY ? scaleY : scaleX; float width = layoutParams.width * scale; float height = layoutParams.height * scale; float xPos = (Utilities.displaySize.x - width) / 2.0f; float yPos = (Utilities.displaySize.y - Utilities.statusBarHeight - height) / 2.0f; - int clipHorizontal = Math.abs(imageReceiver.drawRegion.left - imageReceiver.imageX); + int clipHorizontal = Math.abs(object.imageReceiver.drawRegion.left - object.imageReceiver.imageX); int coords2[] = new int[2]; - parent.getLocationInWindow(coords2); - int clipTop = coords2[1] - Utilities.statusBarHeight - (y + imageReceiver.drawRegion.top); + object.parentView.getLocationInWindow(coords2); + int clipTop = coords2[1] - Utilities.statusBarHeight - (object.viewY + object.imageReceiver.drawRegion.top); if (clipTop < 0) { clipTop = 0; } - int clipBottom = (y + imageReceiver.drawRegion.top + layoutParams.height) - (coords2[1] + parent.getHeight() - Utilities.statusBarHeight); + int clipBottom = (object.viewY + object.imageReceiver.drawRegion.top + layoutParams.height) - (coords2[1] + object.parentView.getHeight() - Utilities.statusBarHeight); if (clipBottom < 0) { clipBottom = 0; } @@ -293,7 +1211,10 @@ public class PhotoViewer { ObjectAnimator.ofInt(animatingImageView, "clipHorizontal", clipHorizontal, 0), ObjectAnimator.ofInt(animatingImageView, "clipTop", clipTop, 0), ObjectAnimator.ofInt(animatingImageView, "clipBottom", clipBottom, 0), - ObjectAnimator.ofFloat(actionBar, "alpha", 0.0f, 1.0f) + ObjectAnimator.ofFloat(actionBar, "alpha", 0.0f, 1.0f), + ObjectAnimator.ofFloat(bottomLayout, "alpha", 0.0f, 1.0f), + ObjectAnimator.ofFloat(progressBar, "alpha", 0.0f, 1.0f), + ObjectAnimator.ofFloat(currentOverlay, "alpha", 0.0f, 1.0f) ); animatorSet.setDuration(250); @@ -301,163 +1222,636 @@ public class PhotoViewer { @Override public void onAnimationEnd(Animator animation) { animationInProgress = false; + animatingImageView.setVisibility(View.GONE); + Utilities.unlockOrientation(parentActivity); } }); animatorSet.start(); + + animatingImageView.setOnDrawListener(new ClippingImageView.onDrawListener() { + @Override + public void onDraw() { + disableShowCheck = false; + animatingImageView.setOnDrawListener(null); + object.imageReceiver.setVisible(false, true); + } + }); return true; } }); + } else { + disableShowCheck = false; } } - public void closePhoto() { - if (parentActivity == null || !isVisible) { + public void closePhoto(boolean animated) { + if (parentActivity == null || !isVisible || animationInProgress) { return; } - if(android.os.Build.VERSION.SDK_INT >= 11) { - if (animationInProgress) { - return; - } - isVisible = false; + + NotificationCenter.getInstance().removeObserver(this, FileLoader.FileDidFailedLoad); + NotificationCenter.getInstance().removeObserver(this, FileLoader.FileDidLoaded); + NotificationCenter.getInstance().removeObserver(this, FileLoader.FileLoadProgressChanged); + NotificationCenter.getInstance().removeObserver(this, MessagesController.mediaCountDidLoaded); + NotificationCenter.getInstance().removeObserver(this, MessagesController.mediaDidLoaded); + NotificationCenter.getInstance().removeObserver(this, MessagesController.userPhotosLoaded); + ConnectionsManager.getInstance().cancelRpcsForClassGuid(classGuid); + + isVisible = false; + isActionBarVisible = false; + + if (velocityTracker != null) { + velocityTracker.recycle(); + velocityTracker = null; + } + + final PlaceProviderObject object = placeProvider.getPlaceForPhoto(currentMessageObject, currentFileLocation); + + if(android.os.Build.VERSION.SDK_INT >= 11 && animated) { + Utilities.lockOrientation(parentActivity); + animationInProgress = true; - isActionBarVisible = false; animatingImageView.setVisibility(View.VISIBLE); - int clipHorizontal = Math.abs(currentImageReceiver.drawRegion.left - currentImageReceiver.imageX); - - int coords2[] = new int[2]; - parentView.getLocationInWindow(coords2); - int clipTop = coords2[1] - Utilities.statusBarHeight - (imageY + currentImageReceiver.drawRegion.top); - if (clipTop < 0) { - clipTop = 0; - } - int clipBottom = (imageY + currentImageReceiver.drawRegion.top + (currentImageReceiver.drawRegion.bottom - currentImageReceiver.drawRegion.top)) - (coords2[1] + parentView.getHeight() - Utilities.statusBarHeight); - if (clipBottom < 0) { - clipBottom = 0; - } - AnimatorSet animatorSet = new AnimatorSet(); - animatorSet.playTogether( - ObjectAnimator.ofFloat(animatingImageView, "scaleX", 1), - ObjectAnimator.ofFloat(animatingImageView, "scaleY", 1), - ObjectAnimator.ofFloat(animatingImageView, "translationX", imageX + currentImageReceiver.drawRegion.left), - ObjectAnimator.ofFloat(animatingImageView, "translationY", imageY + currentImageReceiver.drawRegion.top), - ObjectAnimator.ofInt(backgroundDrawable, "alpha", 0), - ObjectAnimator.ofInt(animatingImageView, "clipHorizontal", clipHorizontal), - ObjectAnimator.ofInt(animatingImageView, "clipTop", clipTop), - ObjectAnimator.ofInt(animatingImageView, "clipBottom", clipBottom), - ObjectAnimator.ofFloat(actionBar, "alpha", 0.0f) - ); + + final ViewGroup.LayoutParams layoutParams = animatingImageView.getLayoutParams(); + if (object != null) { + layoutParams.width = object.imageReceiver.drawRegion.right - object.imageReceiver.drawRegion.left; + layoutParams.height = object.imageReceiver.drawRegion.bottom - object.imageReceiver.drawRegion.top; + animatingImageView.setImageBitmap(object.thumb); + } else { + layoutParams.width = centerImage.imageW; + layoutParams.height = centerImage.imageH; + animatingImageView.setImageBitmap(centerImage.getBitmap()); + } + animatingImageView.setLayoutParams(layoutParams); + + float scaleX = (float) Utilities.displaySize.x / layoutParams.width; + float scaleY = (float) (Utilities.displaySize.y - Utilities.statusBarHeight) / layoutParams.height; + float scale2 = scaleX > scaleY ? scaleY : scaleX; + float width = layoutParams.width * scale * scale2; + float height = layoutParams.height * scale * scale2; + float xPos = (Utilities.displaySize.x - width) / 2.0f; + float yPos = (Utilities.displaySize.y - Utilities.statusBarHeight - height) / 2.0f; + animatingImageView.setTranslationX(xPos + translationX); + animatingImageView.setTranslationY(yPos + translationY); + animatingImageView.setScaleX(scale * scale2); + animatingImageView.setScaleY(scale * scale2); + + if (object != null) { + object.imageReceiver.setVisible(false, true); + int clipHorizontal = Math.abs(object.imageReceiver.drawRegion.left - object.imageReceiver.imageX); + + int coords2[] = new int[2]; + object.parentView.getLocationInWindow(coords2); + int clipTop = coords2[1] - Utilities.statusBarHeight - (object.viewY + object.imageReceiver.drawRegion.top); + if (clipTop < 0) { + clipTop = 0; + } + int clipBottom = (object.viewY + object.imageReceiver.drawRegion.top + (object.imageReceiver.drawRegion.bottom - object.imageReceiver.drawRegion.top)) - (coords2[1] + object.parentView.getHeight() - Utilities.statusBarHeight); + if (clipBottom < 0) { + clipBottom = 0; + } + + animatorSet.playTogether( + ObjectAnimator.ofFloat(animatingImageView, "scaleX", 1), + ObjectAnimator.ofFloat(animatingImageView, "scaleY", 1), + ObjectAnimator.ofFloat(animatingImageView, "translationX", object.viewX + object.imageReceiver.drawRegion.left), + ObjectAnimator.ofFloat(animatingImageView, "translationY", object.viewY + object.imageReceiver.drawRegion.top), + ObjectAnimator.ofInt(backgroundDrawable, "alpha", 0), + ObjectAnimator.ofInt(animatingImageView, "clipHorizontal", clipHorizontal), + ObjectAnimator.ofInt(animatingImageView, "clipTop", clipTop), + ObjectAnimator.ofInt(animatingImageView, "clipBottom", clipBottom), + ObjectAnimator.ofFloat(actionBar, "alpha", 0.0f), + ObjectAnimator.ofFloat(bottomLayout, "alpha", 0.0f), + ObjectAnimator.ofFloat(progressBar, "alpha", 0.0f), + ObjectAnimator.ofFloat(currentOverlay, "alpha", 0.0f) + ); + } else { + animatorSet.playTogether( + ObjectAnimator.ofInt(backgroundDrawable, "alpha", 0), + ObjectAnimator.ofFloat(actionBar, "alpha", 0.0f), + ObjectAnimator.ofFloat(animatingImageView, "alpha", 0.0f), + ObjectAnimator.ofFloat(bottomLayout, "alpha", 0.0f), + ObjectAnimator.ofFloat(progressBar, "alpha", 0.0f), + ObjectAnimator.ofFloat(animatingImageView, "translationY", translationY >= 0 ? Utilities.displaySize.y : -Utilities.displaySize.y), + ObjectAnimator.ofFloat(currentOverlay, "alpha", 0.0f) + ); + } animatorSet.setDuration(250); animatorSet.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { - containerView.post(new Runnable() { - @Override - public void run() { - WindowManager wm = (WindowManager) parentActivity.getSystemService(Context.WINDOW_SERVICE); - wm.removeView(containerView); - } - }); + Utilities.unlockOrientation(parentActivity); animationInProgress = false; - currentImageReceiver.setVisible(true); + onPhotoClosed(object); } }); animatorSet.start(); } else { - WindowManager wm = (WindowManager) parentActivity.getSystemService(Context.WINDOW_SERVICE); - wm.removeView(containerView); + onPhotoClosed(object); } } + private void onPhotoClosed(PlaceProviderObject object) { + placeProvider = null; + currentMessageObject = null; + currentFileLocation = null; + currentThumb = null; + animatingImageView.setImageBitmap(null); + centerImage.setImageBitmap((Bitmap)null); + leftImage.setImageBitmap((Bitmap) null); + rightImage.setImageBitmap((Bitmap)null); + if (object != null) { + object.imageReceiver.setVisible(true, true); + } + containerView.post(new Runnable() { + @Override + public void run() { + WindowManager wm = (WindowManager) parentActivity.getSystemService(Context.WINDOW_SERVICE); + wm.removeView(containerView); + } + }); + } + public boolean isVisible() { return isVisible; } - private boolean maybeStartDragDown = false; - private boolean draggingDown = false; - private int startDraggingPointerIndex = -1; - private float dragY; - private float startDragOriginY = 0; + private void updateMinMax(float scale) { + int maxW = (int) (centerImage.imageW * scale - containerView.getWidth()) / 2; + int maxH = (int) (centerImage.imageH * scale - containerView.getHeight()) / 2; + if (maxW > 0) { + minX = -maxW; + maxX = maxW; + } else { + minX = maxX = 0; + } + if (maxH > 0) { + minY = -maxH; + maxY = maxH; + } else { + minY = maxY = 0; + } + } - public boolean onTouchEvent(MotionEvent ev) { - if (animationInProgress) { + private boolean onTouchEvent(MotionEvent ev) { + if (animationInProgress || animationStartTime != 0) { + if (animationStartTime == 0) { + Utilities.unlockOrientation(parentActivity); + } return false; } - if (ev.getAction() == MotionEvent.ACTION_DOWN) { - if (!maybeStartDragDown) { - maybeStartDragDown = true; - dragY = ev.getY(); + + if(ev.getPointerCount() == 1 && gestureDetector.onTouchEvent(ev) && doubleTap) { + doubleTap = false; + moving = false; + zooming = false; + float moveToX = translationX; + float moveToY = translationY; + updateMinMax(scale); + if (translationX < minX) { + moveToX = minX; + } else if (translationX > maxX) { + moveToX = maxX; } - } else if (ev.getAction() == MotionEvent.ACTION_MOVE) { - if (!draggingDown && maybeStartDragDown) { - if (Math.abs(ev.getY() - dragY) >= Utilities.dp(10)) { + if (translationY < minY) { + moveToY = minY; + } else if (translationY > maxY) { + moveToY = maxY; + } + animateTo(scale, moveToX, moveToY); + return true; + } + + if (ev.getActionMasked() == MotionEvent.ACTION_DOWN || ev.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN) { + if (!draggingDown && !changingPage) { + if (canZoom && ev.getPointerCount() == 2) { + pinchStartDistance = (float) Math.hypot(ev.getX(1) - ev.getX(0), ev.getY(1) - ev.getY(0)); + pinchStartScale = scale; + pinchCenterX = (ev.getX(0) + ev.getX(1)) / 2.0f; + pinchCenterY = (ev.getY(0) + ev.getY(1)) / 2.0f; + pinchStartX = translationX; + pinchStartY = translationY; + zooming = true; + moving = false; + if (velocityTracker != null) { + velocityTracker.clear(); + } + } else if (ev.getPointerCount() == 1) { + moveStartX = ev.getX(); + dragY = moveStartY = ev.getY(); + draggingDown = false; + canDragDown = true; + Utilities.lockOrientation(parentActivity); + if (velocityTracker != null) { + velocityTracker.clear(); + } + } + } + } else if (ev.getActionMasked() == MotionEvent.ACTION_MOVE) { + if (canZoom && ev.getPointerCount() == 2 && !draggingDown && zooming && !changingPage) { + scale = (float)Math.hypot(ev.getX(1) - ev.getX(0), ev.getY(1) - ev.getY(0)) / pinchStartDistance * pinchStartScale; + translationX = (pinchCenterX - containerView.getWidth() / 2) - ((pinchCenterX - containerView.getWidth() / 2) - pinchStartX) * (scale / pinchStartScale); + translationY = (pinchCenterY - containerView.getHeight() / 2) - ((pinchCenterY - containerView.getHeight() / 2) - pinchStartY) * (scale / pinchStartScale); + updateMinMax(scale); + containerView.invalidate(); + } else if (ev.getPointerCount() == 1) { + if (velocityTracker != null) { + velocityTracker.addMovement(ev); + } + if (canDragDown && !draggingDown && scale == 1 && Math.abs(ev.getY() - dragY) >= Utilities.dp(30)) { draggingDown = true; - maybeStartDragDown = false; + moving = false; dragY = ev.getY(); - startDragOriginY = animatingImageView.getTranslationY(); if (isActionBarVisible) { toggleActionBar(false, true); } return true; - } - } else if (draggingDown) { - float diff = ev.getY() - dragY; - float maxValue = Utilities.displaySize.y / 4.0f; - backgroundDrawable.setAlpha((int)Math.max(127, 255 * (1.0f - (Math.min(Math.abs(diff), maxValue) / maxValue)))); - animatingImageView.setTranslationY(startDragOriginY + diff); - } - } else if (ev.getAction() == MotionEvent.ACTION_CANCEL || ev.getAction() == MotionEvent.ACTION_UP) { - if (draggingDown) { - if (Math.abs(dragY - ev.getY()) > Utilities.displaySize.y / 6.0f) { - closePhoto(); - } else { - AnimatorSet animatorSet = new AnimatorSet(); - animatorSet.playTogether( - ObjectAnimator.ofFloat(animatingImageView, "translationY", startDragOriginY), - ObjectAnimator.ofInt(backgroundDrawable, "alpha", 255) - ); + } else if (draggingDown) { + translationY = ev.getY() - dragY; + containerView.invalidate(); + toggleOverlayView(false); + } else if (!invalidCoords && animationStartTime == 0) { + float moveDx = moveStartX - ev.getX(); + float moveDy = moveStartY - ev.getY(); + if (moving || scale == 1 && Math.abs(moveDy) + Utilities.dp(12) < Math.abs(moveDx) || scale != 1) { + if (!moving) { + moveDx = 0; + moveDy = 0; + moving = true; + canDragDown = false; + } - animatorSet.setDuration(250); - animatorSet.start(); + toggleOverlayView(false); + + moveStartX = ev.getX(); + moveStartY = ev.getY(); + updateMinMax(scale); + if (translationX < minX && !rightImage.hasImage() || translationX > maxX && !leftImage.hasImage()) { + moveDx /= 3.0f; + } + if (translationY < minY || translationY > maxY) { + moveDy /= 3.0f; + } + + translationX -= moveDx; + if (scale != 1) { + translationY -= moveDy; + } + + containerView.invalidate(); + } + } else { + invalidCoords = false; + moveStartX = ev.getX(); + moveStartY = ev.getY(); + } + } + } else if (ev.getActionMasked() == MotionEvent.ACTION_CANCEL || ev.getActionMasked() == MotionEvent.ACTION_UP || ev.getActionMasked() == MotionEvent.ACTION_POINTER_UP) { + if (zooming) { + invalidCoords = true; + if (scale < 1.0f) { + updateMinMax(1.0f); + animateTo(1.0f, 0, 0); + } else if(scale > 3.0f) { + float atx = (pinchCenterX - containerView.getWidth() / 2) - ((pinchCenterX - containerView.getWidth() / 2) - pinchStartX) * (3.0f / pinchStartScale); + float aty = (pinchCenterY - containerView.getHeight() / 2) - ((pinchCenterY - containerView.getHeight() / 2) - pinchStartY) * (3.0f / pinchStartScale); + updateMinMax(3.0f); + if (atx < minX) { + atx = minX; + } else if (atx > maxX) { + atx = maxX; + } + if (aty < minY) { + aty = minY; + } else if (aty > maxY) { + aty = maxY; + } + animateTo(3.0f, atx, aty); + } + zooming = false; + } else if (draggingDown) { + if (Math.abs(dragY - ev.getY()) > containerView.getHeight() / 6.0f) { + closePhoto(true); + } else { + animateTo(1, 0, 0); } draggingDown = false; + } else if (moving) { + float moveToX = translationX; + float moveToY = translationY; + updateMinMax(scale); + moving = false; + canDragDown = true; + float velocity = 0; + if (velocityTracker != null && scale == 1) { + velocityTracker.computeCurrentVelocity(1000); + velocity = velocityTracker.getXVelocity(); + } + + if((translationX < minX - containerView.getWidth() / 3 || velocity < -Utilities.dp(650)) && rightImage.hasImage()){ + goToNext(); + return true; + } + if((translationX > maxX + containerView.getWidth() / 3 || velocity > Utilities.dp(650)) && leftImage.hasImage()){ + goToPrev(); + return true; + } + + if (translationX < minX) { + moveToX = minX; + } else if (translationX > maxX) { + moveToX = maxX; + } + if (translationY < minY) { + moveToY = minY; + } else if (translationY > maxY) { + moveToY = maxY; + } + animateTo(scale, moveToX, moveToY); } else { - toggleActionBar(!isActionBarVisible, true); + Utilities.unlockOrientation(parentActivity); } } return false; } - private void toggleActionBar(boolean show, boolean animated) { - if (show) { - actionBar.setVisibility(View.VISIBLE); + private void goToNext() { + float extra = 0; + if (scale != 1) { + extra = (containerView.getWidth() - centerImage.imageW) / 2 * scale; } - isActionBarVisible = show; - actionBar.setEnabled(show); - actionBarLayer.setEnabled(show); - if (animated) { - AnimatorSet animatorSet = new AnimatorSet(); - animatorSet.playTogether( - ObjectAnimator.ofFloat(actionBar, "alpha", show ? 1.0f : 0.0f) - ); - if (!show) { - animatorSet.addListener(new AnimatorListenerAdapter() { - @Override - public void onAnimationEnd(Animator animation) { - actionBar.setVisibility(View.GONE); - } - }); + switchImageAfterAnimation = 1; + animateTo(scale, minX - containerView.getWidth() - extra - PAGE_SPACING / 2, translationY); + } + + private void goToPrev() { + float extra = 0; + if (scale != 1) { + extra = (containerView.getWidth() - centerImage.imageW) / 2 * scale; + } + switchImageAfterAnimation = 2; + animateTo(scale, maxX + containerView.getWidth() + extra + PAGE_SPACING / 2, translationY); + } + + private void animateTo(float newScale, float newTx, float newTy) { + if (switchImageAfterAnimation == 0) { + toggleOverlayView(true); + } + if (scale == newScale && translationX == newTx && translationY == newTy) { + Utilities.unlockOrientation(parentActivity); + return; + } + animateToScale = newScale; + animateToX = newTx; + animateToY = newTy; + animationStartTime = System.currentTimeMillis(); + animationDuration = 250; + containerView.postInvalidate(); + Utilities.lockOrientation(parentActivity); + } + + private void onDraw(Canvas canvas) { + if (animationInProgress || !isVisible) { + return; + } + + canvas.save(); + + canvas.translate(containerView.getWidth() / 2, containerView.getHeight() / 2); + float currentTranslationY; + float currentTranslationX; + + float aty = -1; + float ai = -1; + if (System.currentTimeMillis() - animationStartTime < animationDuration) { + ai = interpolator.getInterpolation((float)(System.currentTimeMillis() - animationStartTime) / animationDuration); + if (ai >= 0.95) { + ai = -1; + } + } + + if (ai != -1) { + float ts = scale + (animateToScale - scale) * ai; + float tx = translationX + (animateToX - translationX) * ai; + float ty = translationY + (animateToY - translationY) * ai; + + if (animateToScale == 1 && scale == 1 && translationX == 0) { + aty = ty; + } + canvas.translate(tx, ty); + canvas.scale(ts, ts); + currentTranslationY = ty / ts; + currentTranslationX = tx; + containerView.invalidate(); + } else { + if (animationStartTime != 0) { + translationX = animateToX; + translationY = animateToY; + scale = animateToScale; + animationStartTime = 0; + updateMinMax(scale); + Utilities.unlockOrientation(parentActivity); + } + if (switchImageAfterAnimation != 0) { + if (switchImageAfterAnimation == 1) { + setImageIndex(currentIndex + 1, false); + } else if (switchImageAfterAnimation == 2) { + setImageIndex(currentIndex - 1, false); + } + switchImageAfterAnimation = 0; + toggleOverlayView(true); } - animatorSet.setDuration(250); - animatorSet.start(); - } else { - actionBar.setAlpha(show ? 1.0f : 0.0f); - if (!show) { - actionBar.setVisibility(View.GONE); + canvas.translate(translationX, translationY); + canvas.scale(scale, scale); + currentTranslationY = translationY / scale; + currentTranslationX = translationX; + if (!moving) { + aty = translationY; } } + + if (scale == 1 && aty != -1) { + float maxValue = containerView.getHeight() / 4.0f; + backgroundDrawable.setAlpha((int) Math.max(127, 255 * (1.0f - (Math.min(Math.abs(aty), maxValue) / maxValue)))); + } else { + backgroundDrawable.setAlpha(255); + } + + 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.imageX = -width / 2; + centerImage.imageY = -height / 2; + centerImage.imageW = width; + centerImage.imageH = height; + centerImage.draw(canvas, centerImage.imageX, centerImage.imageY, centerImage.imageW, centerImage.imageH); + } + + if (scale >= 1.0f) { + ImageReceiver sideImage = null; + float k = 1; + if (currentTranslationX > maxX + Utilities.dp(20)) { + k = -1; + sideImage = leftImage; + } else if (currentTranslationX < minX - Utilities.dp(20)) { + sideImage = rightImage; + } + + if (sideImage != null) { + changingPage = true; + canvas.translate(k * containerView.getWidth() / 2, -currentTranslationY); + canvas.scale(1.0f / scale, 1.0f / scale); + canvas.translate(k * (containerView.getWidth() + PAGE_SPACING) / 2, 0); + + bitmap = sideImage.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); + + sideImage.imageX = -width / 2; + sideImage.imageY = -height / 2; + sideImage.imageW = width; + sideImage.imageH = height; + sideImage.draw(canvas, sideImage.imageX, sideImage.imageY, sideImage.imageW, sideImage.imageH); + } + } else { + changingPage = false; + } + } + + canvas.restore(); + } + + private void onLayout(boolean changed, int left, int top, int right, int bottom) { + if(changed) { + scale = 1; + translationX = 0; + translationY = 0; + updateMinMax(scale); + } + } + + private void onActionClick(View view) { + if (currentMessageObject == null) { + return; + } + boolean loadFile = false; + if (currentMessageObject.messageOwner.attachPath != null && currentMessageObject.messageOwner.attachPath.length() != 0) { + File f = new File(currentMessageObject.messageOwner.attachPath); + if (f.exists()) { + Intent intent = new Intent(Intent.ACTION_VIEW); + intent.setDataAndType(Uri.fromFile(f), "video/mp4"); + parentActivity.startActivity(intent); + } else { + loadFile = true; + } + } else { + File cacheFile = new File(Utilities.getCacheDir(), currentFileName); + if (cacheFile.exists()) { + Intent intent = new Intent(Intent.ACTION_VIEW); + intent.setDataAndType(Uri.fromFile(cacheFile), "video/mp4"); + parentActivity.startActivity(intent); + } else { + loadFile = true; + } + } + if (loadFile) { + if (!FileLoader.getInstance().isLoadingFile(currentFileName)) { + FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.video, null, null, null); + } else { + FileLoader.getInstance().cancelLoadFile(currentMessageObject.messageOwner.media.video, null, null, null); + } + updateActionOverlays(); + } + } + + @Override + public boolean onDown(MotionEvent e) { + return false; + } + + @Override + public void onShowPress(MotionEvent e) { + + } + + @Override + public boolean onSingleTapUp(MotionEvent e) { + return false; + } + + @Override + public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { + return false; + } + + @Override + public void onLongPress(MotionEvent e) { + + } + + @Override + public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { + return false; + } + + @Override + public boolean onSingleTapConfirmed(MotionEvent e) { + toggleActionBar(!isActionBarVisible, true); + return true; + } + + @Override + public boolean onDoubleTap(MotionEvent e) { + if (!canZoom || scale == 1.0f && (translationY != 0 || translationX != 0)) { + return false; + } + if (animationStartTime != 0) { + return false; + } + if (scale == 1.0f) { + float atx = (e.getX() - containerView.getWidth() / 2) - ((e.getX() - containerView.getWidth() / 2) - translationX) * (3.0f / scale); + float aty = (e.getY() - containerView.getHeight() / 2) - ((e.getY() - containerView.getHeight() / 2) - translationY) * (3.0f / scale); + updateMinMax(3.0f); + if (atx < minX) { + atx = minX; + } else if (atx > maxX) { + atx = maxX; + } + if (aty < minY) { + aty = minY; + } else if (aty > maxY) { + aty = maxY; + } + animateTo(3.0f, atx, aty); + } else { + animateTo(1.0f, 0, 0); + } + doubleTap = true; + return true; + } + + @Override + public boolean onDoubleTapEvent(MotionEvent e) { + return false; } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/SettingsActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/SettingsActivity.java index bc56db407..e98749a17 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/SettingsActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/SettingsActivity.java @@ -51,6 +51,7 @@ import org.telegram.messenger.R; import org.telegram.messenger.RPCRequest; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; +import org.telegram.objects.MessageObject; import org.telegram.objects.PhotoObject; import org.telegram.ui.Views.ActionBar.ActionBarLayer; import org.telegram.ui.Views.AvatarUpdater; @@ -61,7 +62,7 @@ import java.io.File; import java.util.ArrayList; import java.util.Locale; -public class SettingsActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate { +public class SettingsActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, PhotoViewer.PhotoViewerProvider { private ListView listView; private ListAdapter listAdapter; private AvatarUpdater avatarUpdater = new AvatarUpdater(); @@ -411,6 +412,38 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter return fragmentView; } + @Override + public PhotoViewer.PlaceProviderObject getPlaceForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation) { + if (fileLocation == null) { + return null; + } + TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.clientUserId); + if (user != null && user.photo != null && user.photo.photo_big != null) { + TLRPC.FileLocation photoBig = user.photo.photo_big; + if (photoBig.local_id == fileLocation.local_id && photoBig.volume_id == fileLocation.volume_id && photoBig.dc_id == fileLocation.dc_id) { + int count = listView.getChildCount(); + for (int a = 0; a < count; a++) { + View view = listView.getChildAt(a); + BackupImageView avatarImage = (BackupImageView)view.findViewById(R.id.settings_avatar_image); + if (avatarImage != null) { + int coords[] = new int[2]; + avatarImage.getLocationInWindow(coords); + PhotoViewer.PlaceProviderObject object = new PhotoViewer.PlaceProviderObject(); + object.viewX = coords[0]; + object.viewY = coords[1] - Utilities.statusBarHeight; + object.parentView = listView; + object.imageReceiver = avatarImage.imageReceiver; + object.user_id = UserConfig.clientUserId; + object.thumb = object.imageReceiver.getBitmap(); + object.size = -1; + return object; + } + } + } + } + return null; + } + public void performAskAQuestion() { final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); int uid = preferences.getInt("support_id", 0); @@ -638,10 +671,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter if (i == 0 && full) { TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.clientUserId); if (user != null && user.photo != null && user.photo.photo_big != null) { - NotificationCenter.getInstance().addToMemCache(56, user.id); - NotificationCenter.getInstance().addToMemCache(53, user.photo.photo_big); - Intent intent = new Intent(getParentActivity(), GalleryImageViewer.class); - getParentActivity().startActivity(intent); + PhotoViewer.getInstance().openPhoto(user.photo.photo_big, SettingsActivity.this); } } else if (i == 0 && !full || i == 1 && full) { avatarUpdater.openCamera(); @@ -714,10 +744,13 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter BackupImageView avatarImage = (BackupImageView)view.findViewById(R.id.settings_avatar_image); avatarImage.processDetach = false; TLRPC.FileLocation photo = null; + TLRPC.FileLocation photoBig = null; if (user.photo != null) { photo = user.photo.photo_small; + photoBig = user.photo.photo_big; } - avatarImage.setImage(photo, null, Utilities.getUserAvatarForId(user.id)); + avatarImage.setImage(photo, "50_50", Utilities.getUserAvatarForId(user.id)); + avatarImage.imageReceiver.setVisible(!PhotoViewer.getInstance().isShowingImage(photoBig), false); } return view; } else if (type == 1) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/SettingsBlockedUsers.java b/TMessagesProj/src/main/java/org/telegram/ui/SettingsBlockedUsers.java index 5ca9d5826..ced697f97 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/SettingsBlockedUsers.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/SettingsBlockedUsers.java @@ -184,10 +184,8 @@ public class SettingsBlockedUsers extends BaseFragment implements NotificationCe if (progressView != null) { progressView.setVisibility(View.GONE); } - if (listView != null) { - if (listView.getEmptyView() == null) { - listView.setEmptyView(emptyView); - } + if (listView != null && listView.getEmptyView() == null) { + listView.setEmptyView(emptyView); } if (listViewAdapter != null) { listViewAdapter.notifyDataSetChanged(); @@ -212,10 +210,8 @@ public class SettingsBlockedUsers extends BaseFragment implements NotificationCe if (progressView != null) { progressView.setVisibility(View.GONE); } - if (listView != null) { - if (listView.getEmptyView() == null) { - listView.setEmptyView(emptyView); - } + if (listView != null && listView.getEmptyView() == null) { + listView.setEmptyView(emptyView); } if (listViewAdapter != null) { listViewAdapter.notifyDataSetChanged(); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/SettingsNotificationsActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/SettingsNotificationsActivity.java index e60c9a791..4acc174e6 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/SettingsNotificationsActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/SettingsNotificationsActivity.java @@ -212,9 +212,13 @@ public class SettingsNotificationsActivity extends BaseFragment { SharedPreferences.Editor editor = preferences.edit(); editor.clear(); editor.commit(); - listView.invalidateViews(); - Toast toast = Toast.makeText(getParentActivity(), R.string.ResetNotificationsText, Toast.LENGTH_SHORT); - toast.show(); + if (listView != null) { + listView.invalidateViews(); + } + if (getParentActivity() != null) { + Toast toast = Toast.makeText(getParentActivity(), R.string.ResetNotificationsText, Toast.LENGTH_SHORT); + toast.show(); + } } }); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/UserProfileActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/UserProfileActivity.java index 6c5710d69..9ef0ab1b9 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/UserProfileActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/UserProfileActivity.java @@ -42,6 +42,7 @@ import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.RPCRequest; import org.telegram.messenger.Utilities; +import org.telegram.objects.MessageObject; import org.telegram.ui.Views.ActionBar.ActionBarLayer; import org.telegram.ui.Views.ActionBar.ActionBarMenu; import org.telegram.ui.Views.ActionBar.ActionBarMenuItem; @@ -51,7 +52,7 @@ import org.telegram.ui.Views.IdenticonView; import java.util.ArrayList; -public class UserProfileActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, MessagesActivity.MessagesActivityDelegate { +public class UserProfileActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, MessagesActivity.MessagesActivityDelegate, PhotoViewer.PhotoViewerProvider { private ListView listView; private ListAdapter listAdapter; private int user_id; @@ -452,6 +453,38 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen } } + @Override + public PhotoViewer.PlaceProviderObject getPlaceForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation) { + if (fileLocation == null) { + return null; + } + TLRPC.User user = MessagesController.getInstance().users.get(user_id); + if (user != null && user.photo != null && user.photo.photo_big != null) { + TLRPC.FileLocation photoBig = user.photo.photo_big; + if (photoBig.local_id == fileLocation.local_id && photoBig.volume_id == fileLocation.volume_id && photoBig.dc_id == fileLocation.dc_id) { + int count = listView.getChildCount(); + for (int a = 0; a < count; a++) { + View view = listView.getChildAt(a); + BackupImageView avatarImage = (BackupImageView)view.findViewById(R.id.settings_avatar_image); + if (avatarImage != null) { + int coords[] = new int[2]; + avatarImage.getLocationInWindow(coords); + PhotoViewer.PlaceProviderObject object = new PhotoViewer.PlaceProviderObject(); + object.viewX = coords[0]; + object.viewY = coords[1] - Utilities.statusBarHeight; + object.parentView = listView; + object.imageReceiver = avatarImage.imageReceiver; + object.user_id = user_id; + object.thumb = object.imageReceiver.getBitmap(); + object.size = -1; + return object; + } + } + } + } + return null; + } + private void createActionBarMenu() { ActionBarMenu menu = actionBarLayer.createMenu(); menu.clearItems(); @@ -557,10 +590,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen public void onClick(View view) { TLRPC.User user = MessagesController.getInstance().users.get(user_id); if (user.photo != null && user.photo.photo_big != null) { - NotificationCenter.getInstance().addToMemCache(56, user_id); - NotificationCenter.getInstance().addToMemCache(53, user.photo.photo_big); - Intent intent = new Intent(getParentActivity(), GalleryImageViewer.class); - getParentActivity().startActivity(intent); + PhotoViewer.getInstance().openPhoto(user.photo.photo_big, UserProfileActivity.this); } } }); @@ -576,10 +606,13 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen onlineText.setText(LocaleController.formatUserStatus(user)); TLRPC.FileLocation photo = null; + TLRPC.FileLocation photoBig = null; if (user.photo != null) { photo = user.photo.photo_small; + photoBig = user.photo.photo_big; } avatarImage.setImage(photo, "50_50", Utilities.getUserAvatarForId(user.id)); + avatarImage.imageReceiver.setVisible(!PhotoViewer.getInstance().isShowingImage(photoBig), false); return view; } else if (type == 1) { if (view == null) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Views/AbstractGalleryActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/Views/AbstractGalleryActivity.java deleted file mode 100755 index 1f4a1b431..000000000 --- a/TMessagesProj/src/main/java/org/telegram/ui/Views/AbstractGalleryActivity.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * This is the source code of Telegram for Android v. 1.3.2. - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2013. - */ - -package org.telegram.ui.Views; - -import org.telegram.objects.MessageObject; - -public abstract class AbstractGalleryActivity extends PausableActivity { - public abstract void topBtn(); - public abstract void didShowMessageObject(MessageObject obj); -} \ No newline at end of file diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/ActionBar.java b/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/ActionBar.java index 61a993f95..13dc763ce 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/ActionBar.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/ActionBar.java @@ -111,12 +111,13 @@ public class ActionBar extends FrameLayout { currentLayer.setBackLayoutVisible(currentLayer.isSearchFieldVisible || currentBackOverlay == null ? VISIBLE : INVISIBLE); } if (currentBackOverlay != null) { - currentBackOverlay.setVisibility(currentLayer.isSearchFieldVisible ? GONE : VISIBLE); ViewGroup.LayoutParams layoutParams = currentBackOverlay.getLayoutParams(); if (currentLayer != null) { + currentBackOverlay.setVisibility(currentLayer.isSearchFieldVisible ? GONE : VISIBLE); currentLayer.measure(widthMeasureSpec, heightMeasureSpec); layoutParams.width = Math.min(currentBackOverlayWidth, currentLayer.getBackLayoutWidth()); } else { + currentBackOverlay.setVisibility(VISIBLE); layoutParams.width = LayoutParams.WRAP_CONTENT; } if (layoutParams.width != 0) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/ActionBarActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/ActionBarActivity.java index 77d38b7cc..7ba3eccf6 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/ActionBarActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/ActionBarActivity.java @@ -13,7 +13,6 @@ import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.app.Activity; import android.content.Context; -import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; @@ -21,7 +20,6 @@ import android.view.ActionMode; import android.view.Gravity; import android.view.KeyEvent; import android.view.MotionEvent; -import android.view.Surface; import android.view.VelocityTracker; import android.view.View; import android.view.ViewGroup; @@ -51,7 +49,6 @@ public class ActionBarActivity extends Activity { private boolean maybeStartTracking = false; protected boolean startedTracking = false; private int startedTrackingX; - private int prevOrientation = -10; protected boolean animationInProgress = false; private VelocityTracker velocityTracker = null; private boolean beginTrackingSent = false; @@ -206,14 +203,7 @@ public class ActionBarActivity extends Activity { } } containerViewBack.setVisibility(View.GONE); - try { - if (prevOrientation != -10) { - setRequestedOrientation(prevOrientation); - prevOrientation = -10; - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } + Utilities.unlockOrientation(this); startedTracking = false; animationInProgress = false; } @@ -244,30 +234,7 @@ public class ActionBarActivity extends Activity { } lastFragment.onResume(); - try { - prevOrientation = getRequestedOrientation(); - WindowManager manager = (WindowManager)getSystemService(Activity.WINDOW_SERVICE); - if (manager != null && manager.getDefaultDisplay() != null) { - int rotation = manager.getDefaultDisplay().getRotation(); - if (rotation == Surface.ROTATION_270) { - if (Build.VERSION.SDK_INT >= 9) { - setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE); - } else { - setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); - } - } else if (rotation == Surface.ROTATION_90) { - setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); - } else if (rotation == Surface.ROTATION_0) { - setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); - } else { - if (Build.VERSION.SDK_INT >= 9) { - setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT); - } - } - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } + Utilities.lockOrientation(this); } public boolean onTouchEvent(MotionEvent ev) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/ActionBarLayer.java b/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/ActionBarLayer.java index 82797dd5d..7f22c6c7b 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/ActionBarLayer.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/ActionBarLayer.java @@ -26,8 +26,14 @@ import org.telegram.messenger.Utilities; public class ActionBarLayer extends FrameLayout { - public interface ActionBarMenuOnItemClick { - public abstract void onItemClick(int id); + public static class ActionBarMenuOnItemClick { + public void onItemClick(int id) { + + } + + public boolean canOpenMenu() { + return true; + } } private FrameLayout backButtonFrameLayout; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/ActionBarMenu.java b/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/ActionBarMenu.java index 48f947f98..87abb9c2d 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/ActionBarMenu.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/ActionBarMenu.java @@ -75,7 +75,9 @@ public class ActionBarMenu extends LinearLayout { public void onClick(View view) { ActionBarMenuItem item = (ActionBarMenuItem)view; if (item.hasSubMenu()) { - item.toggleSubMenu(); + if (parentActionBarLayer.actionBarMenuOnItemClick.canOpenMenu()) { + item.toggleSubMenu(); + } } else if (item.isSearchField()) { parentActionBarLayer.onSearchFieldVisibilityChanged(item.toggleSearch()); } else { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/ActionBarMenuItem.java b/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/ActionBarMenuItem.java index 3c171d586..5d244836a 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/ActionBarMenuItem.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Views/ActionBar/ActionBarMenuItem.java @@ -79,6 +79,7 @@ public class ActionBarMenuItem extends ImageView { layoutParams.width = Utilities.dp(196); layoutParams.height = Utilities.density >= 3 ? 2 : 1; delimeter.setLayoutParams(layoutParams); + delimeter.setTag(100 + id); } TextView textView = new TextView(getContext()); textView.setTextColor(0xff000000); @@ -255,4 +256,26 @@ public class ActionBarMenuItem extends ImageView { popupWindow.update(this, parentActionBar.getMeasuredWidth() - popupLayout.getMeasuredWidth() - getLeft() - parentMenu.getLeft(), 0, -1, -1); } } + + public void hideSubItem(int id) { + View view = popupLayout.findViewWithTag(id); + if (view != null) { + view.setVisibility(GONE); + } + view = popupLayout.findViewWithTag(100 + id); + if (view != null) { + view.setVisibility(GONE); + } + } + + public void showSubItem(int id) { + View view = popupLayout.findViewWithTag(id); + if (view != null) { + view.setVisibility(VISIBLE); + } + view = popupLayout.findViewWithTag(100 + id); + if (view != null) { + view.setVisibility(VISIBLE); + } + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Views/BackupImageView.java b/TMessagesProj/src/main/java/org/telegram/ui/Views/BackupImageView.java index 641a8b0de..a16a5dabc 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Views/BackupImageView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Views/BackupImageView.java @@ -8,43 +8,40 @@ package org.telegram.ui.Views; +import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; -import android.graphics.drawable.NinePatchDrawable; -import android.os.Build; -import android.widget.ImageView; +import android.util.AttributeSet; +import android.view.View; import org.telegram.messenger.TLRPC; -import org.telegram.messenger.FileLoader; -import org.telegram.messenger.FileLog; -import org.telegram.messenger.Utilities; -public class BackupImageView extends ImageView { - boolean makeRequest = true; - public String currentPath; +import java.lang.ref.WeakReference; + +public class BackupImageView extends View { + public ImageReceiver imageReceiver; public boolean processDetach = true; - private boolean isPlaceholder; - private boolean ignoreLayout = true; - TLRPC.FileLocation last_path; - String last_httpUrl; - String last_filter; - int last_placeholder; - Bitmap last_placeholderBitmap; - int last_size; - - public BackupImageView(android.content.Context context) { + public BackupImageView(Context context) { super(context); + init(); } - public BackupImageView(android.content.Context context, android.util.AttributeSet attrs) { + public BackupImageView(Context context, AttributeSet attrs) { super(context, attrs); + init(); } - public BackupImageView(android.content.Context context, android.util.AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); + public BackupImageView(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + init(); + } + + private void init() { + imageReceiver = new ImageReceiver(); + imageReceiver.parentView = new WeakReference(this); } public void setImage(TLRPC.FileLocation path, String filter, int placeholder) { @@ -68,135 +65,42 @@ public class BackupImageView extends ImageView { } public void setImage(TLRPC.FileLocation path, String httpUrl, String filter, int placeholder, Bitmap placeholderBitmap, int size) { - if ((path == null && httpUrl == null) || (path != null && !(path instanceof TLRPC.TL_fileLocation) && !(path instanceof TLRPC.TL_fileEncryptedLocation))) { - recycleBitmap(null); - currentPath = null; - isPlaceholder = true; - - last_path = null; - last_httpUrl = null; - last_filter = null; - last_placeholder = 0; - last_size = 0; - last_placeholderBitmap = null; - - FileLoader.getInstance().cancelLoadingForImageView(this); - if (placeholder != 0) { - setImageResourceMy(placeholder); - } else if (placeholderBitmap != null) { - setImageBitmapMy(placeholderBitmap); - } - return; - } - String key; - if (path != null) { - key = path.volume_id + "_" + path.local_id; - } else { - key = Utilities.MD5(httpUrl); - } - if (filter != null) { - key += "@" + filter; - } - Bitmap img; - if (currentPath != null) { - if (currentPath.equals(key)) { - return; - } else { - img = FileLoader.getInstance().getImageFromMemory(path, httpUrl, this, filter, true); - recycleBitmap(img); - } - } else { - img = FileLoader.getInstance().getImageFromMemory(path, httpUrl, this, filter, true); - } - currentPath = key; - last_path = path; - last_httpUrl = httpUrl; - last_filter = filter; - last_placeholder = placeholder; - last_placeholderBitmap = placeholderBitmap; - last_size = size; - if (img == null) { - isPlaceholder = true; - if (placeholder != 0) { - setImageResourceMy(placeholder); - } else if (placeholderBitmap != null) { - setImageBitmapMy(placeholderBitmap); - } - FileLoader.getInstance().loadImage(path, httpUrl, this, filter, true, size); - } else { - setImageBitmap(img, currentPath); + Drawable placeholderDrawable = null; + if (placeholderBitmap != null) { + placeholderDrawable = new BitmapDrawable(null, placeholderBitmap); + } else if (placeholder != 0) { + placeholderDrawable = getResources().getDrawable(placeholder); } + imageReceiver.setImage(path, httpUrl, filter, placeholderDrawable, size); } - public void setImageBitmap(Bitmap bitmap, String imgKey) { - if (currentPath == null || !imgKey.equals(currentPath)) { - return; - } - isPlaceholder = false; - FileLoader.getInstance().incrementUseCount(currentPath); - if (ignoreLayout) { - makeRequest = false; - } - super.setImageBitmap(bitmap); - if (ignoreLayout) { - makeRequest = true; - } + public void setImageBitmap(Bitmap bitmap) { + imageReceiver.setImageBitmap(bitmap); } - public void clearImage() { - recycleBitmap(null); - } - - private void recycleBitmap(Bitmap newBitmap) { - Drawable drawable = getDrawable(); - if (drawable == null || isPlaceholder) { - return; - } - if (drawable instanceof BitmapDrawable) { - Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap(); - if (bitmap != null && bitmap != newBitmap) { - if (currentPath != null) { - boolean canDelete = FileLoader.getInstance().decrementUseCount(currentPath); - if (!FileLoader.getInstance().isInCache(currentPath)) { - if (FileLoader.getInstance().runtimeHack != null) { - FileLoader.getInstance().runtimeHack.trackAlloc(bitmap.getRowBytes() * bitmap.getHeight()); - } - if (canDelete) { - setImageBitmap(null); - if (Build.VERSION.SDK_INT < 11) { - bitmap.recycle(); - } - } - } else { - setImageBitmap(null); - } - } - } - } else if (drawable instanceof NinePatchDrawable) { - - } + public void setImageResource(int resId) { + imageReceiver.setImageBitmap(getResources().getDrawable(resId)); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (processDetach) { - recycleBitmap(null); + imageReceiver.clearImage(); } } @Override protected void onDraw(Canvas canvas) { - try { - super.onDraw(canvas); - } catch (Exception e) { - FileLoader.getInstance().removeImage(currentPath); - currentPath = null; - setImage(last_path, last_httpUrl, last_filter, last_placeholder, last_placeholderBitmap, last_size); - FileLog.e("tmessages", e); - } + imageReceiver.imageX = 0; + imageReceiver.imageY = 0; + imageReceiver.imageW = getWidth(); + imageReceiver.imageH = getHeight(); + imageReceiver.draw(canvas, 0, 0, imageReceiver.imageW, imageReceiver.imageH); } + /* + public void setImageResourceMy(int resId) { if (ignoreLayout) { makeRequest = false; @@ -207,25 +111,7 @@ public class BackupImageView extends ImageView { } } - public void setImageResource(int resId) { - if (resId != 0) { - recycleBitmap(null); - } - currentPath = null; - last_path = null; - last_httpUrl = null; - last_filter = null; - last_placeholder = 0; - last_size = 0; - last_placeholderBitmap = null; - if (ignoreLayout) { - makeRequest = false; - } - super.setImageResource(resId); - if (ignoreLayout) { - makeRequest = true; - } - } + public void setImageBitmapMy(Bitmap bitmap) { if (ignoreLayout) { @@ -238,29 +124,5 @@ public class BackupImageView extends ImageView { } @Override - public void setImageBitmap(Bitmap bitmap) { - if (bitmap != null) { - recycleBitmap(null); - } - currentPath = null; - last_path = null; - last_httpUrl = null; - last_filter = null; - last_placeholder = 0; - last_size = 0; - last_placeholderBitmap = null; - if (ignoreLayout) { - makeRequest = false; - } - super.setImageBitmap(bitmap); - if (ignoreLayout) { - makeRequest = true; - } - } - - @Override public void requestLayout() { - if (makeRequest) { - super.requestLayout(); - } - } + */ } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Views/ClippingImageView.java b/TMessagesProj/src/main/java/org/telegram/ui/Views/ClippingImageView.java new file mode 100644 index 000000000..69b04d21d --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/ui/Views/ClippingImageView.java @@ -0,0 +1,112 @@ +/* + * This is the source code of Telegram for Android v. 1.4.x. + * It is licensed under GNU GPL v. 2 or later. + * You should have received a copy of the license in this archive (see LICENSE). + * + * Copyright Nikolai Kudashov, 2013-2014. + */ + +package org.telegram.ui.Views; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Paint; +import android.graphics.Rect; +import android.view.View; + +public class ClippingImageView extends View { + private int clipBottom; + private int clipLeft; + private int clipRight; + private int clipTop; + private Rect drawRect; + private Paint paint; + private Bitmap bmp; + private onDrawListener drawListener; + + public static interface onDrawListener { + public abstract void onDraw(); + } + + public ClippingImageView(Context context) { + super(context); + paint = new Paint(); + paint.setFilterBitmap(true); + drawRect = new Rect(); + } + + public int getClipBottom() { + return clipBottom; + } + + public int getClipHorizontal() { + return clipRight; + } + + public int getClipLeft() { + return clipLeft; + } + + public int getClipRight() { + return clipRight; + } + + public int getClipTop() { + return clipTop; + } + + public void onDraw(Canvas canvas) { + if (bmp != null) { + if (drawListener != null && getScaleY() != 1) { + drawListener.onDraw(); + } + canvas.save(); + canvas.clipRect(clipLeft / getScaleY(), clipTop / getScaleY(), getWidth() - clipRight / getScaleY(), getHeight() - clipBottom / getScaleY()); + drawRect.set(0, 0, getWidth(), getHeight()); + canvas.drawBitmap(this.bmp, null, drawRect, this.paint); + canvas.restore(); + } + } + + public void setClipBottom(int value) { + clipBottom = value; + invalidate(); + } + + public void setClipHorizontal(int value) { + clipRight = value; + clipLeft = value; + invalidate(); + } + + public void setClipLeft(int value) { + clipLeft = value; + invalidate(); + } + + public void setClipRight(int value) { + clipRight = value; + invalidate(); + } + + public void setClipTop(int value) { + clipTop = value; + invalidate(); + } + + public void setClipVertical(int value) { + clipBottom = value; + clipTop = value; + invalidate(); + } + + public void setImageBitmap(Bitmap bitmap) { + bmp = bitmap; + invalidate(); + } + + public void setOnDrawListener(onDrawListener listener) { + drawListener = listener; + } +} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Views/GalleryViewPager.java b/TMessagesProj/src/main/java/org/telegram/ui/Views/GalleryViewPager.java deleted file mode 100755 index 501ab9baf..000000000 --- a/TMessagesProj/src/main/java/org/telegram/ui/Views/GalleryViewPager.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * This is the source code of Telegram for Android v. 1.3.2. - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2013. - */ - -package org.telegram.ui.Views; - -import android.content.Context; -import android.graphics.PointF; -import android.support.v4.view.ViewPager; -import android.util.AttributeSet; -import android.view.MotionEvent; - -import org.telegram.messenger.FileLog; - -public class GalleryViewPager extends ViewPager { - PointF last; - public PZSImageView mCurrentView; - - public GalleryViewPager(Context context) { - super(context); - } - - public GalleryViewPager(Context context, AttributeSet attrs) { - super(context, attrs); - } - - private float[] handleMotionEvent(MotionEvent event) { - switch (event.getAction() & MotionEvent.ACTION_MASK) { - case MotionEvent.ACTION_DOWN: - last = new PointF(event.getX(0), event.getY(0)); - break; - case MotionEvent.ACTION_MOVE: - case MotionEvent.ACTION_UP: - PointF curr = new PointF(event.getX(0), event.getY(0)); - return new float[] { curr.x - last.x, curr.y - last.y }; - - } - return null; - } - - @Override - public boolean onTouchEvent(MotionEvent event) { - try { - if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP) { - super.onTouchEvent(event); - } - - if (mCurrentView == null) { - return super.onTouchEvent(event); - } - - float[] difference = handleMotionEvent(event); - - if (difference != null && mCurrentView.getOnRightSide() && difference[0] < 0) { - return super.onTouchEvent(event); - } else if (difference != null && mCurrentView.getOnLeftSide() && difference[0] > 0) { - return super.onTouchEvent(event); - } else if (difference == null && (mCurrentView.getOnLeftSide() || mCurrentView.getOnRightSide())) { - return super.onTouchEvent(event); - } - - return false; - } catch (Exception e) { - try { - getAdapter().notifyDataSetChanged(); - } catch (Exception e2) { - e2.printStackTrace(); - } - FileLog.e("tmessages", e); - } - - return false; - } - - @Override - public boolean onInterceptTouchEvent(MotionEvent event) { - try { - if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP) { - super.onInterceptTouchEvent(event); - } - - if (mCurrentView == null) { - return super.onInterceptTouchEvent(event); - } - - float[] difference = handleMotionEvent(event); - - if (difference != null && difference.length > 0 && mCurrentView.getOnRightSide() && difference[0] < 0) { - return super.onInterceptTouchEvent(event); - } else if (difference != null && difference.length > 0 && mCurrentView.getOnLeftSide() && difference[0] > 0) { - return super.onInterceptTouchEvent(event); - } else if ((difference == null || difference.length == 0) && (mCurrentView.getOnLeftSide() || mCurrentView.getOnRightSide())) { - return super.onInterceptTouchEvent(event); - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } - - return false; - } -} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Views/ImageReceiver.java b/TMessagesProj/src/main/java/org/telegram/ui/Views/ImageReceiver.java index 3ea7eeca2..625466633 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Views/ImageReceiver.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Views/ImageReceiver.java @@ -108,7 +108,7 @@ public class ImageReceiver { isPlaceholder = false; FileLoader.getInstance().incrementUseCount(currentPath); currentImage = new BitmapDrawable(null, bitmap); - if (!selfSetting && parentView.get() != null) { + if (!selfSetting && parentView != null && parentView.get() != null) { if (imageW != 0) { parentView.get().invalidate(imageX, imageY, imageX + imageW, imageY + imageH); } else { @@ -120,7 +120,12 @@ public class ImageReceiver { public void setImageBitmap(Bitmap bitmap) { FileLoader.getInstance().cancelLoadingForImageView(this); recycleBitmap(null); - last_placeholder = new BitmapDrawable(null, bitmap); + if (bitmap != null) { + last_placeholder = new BitmapDrawable(null, bitmap); + } else { + last_placeholder = null; + } + isPlaceholder = true; currentPath = null; last_path = null; last_httpUrl = null; @@ -175,13 +180,14 @@ public class ImageReceiver { } public void draw(Canvas canvas, int x, int y, int w, int h) { - if (!isVisible) { - return; - } try { - if (currentImage != null) { - int bitmapW = currentImage.getIntrinsicWidth(); - int bitmapH = currentImage.getIntrinsicHeight(); + Drawable bitmapDrawable = currentImage; + if (bitmapDrawable == null && last_placeholder != null && last_placeholder instanceof BitmapDrawable) { + bitmapDrawable = last_placeholder; + } + if (bitmapDrawable != null) { + int bitmapW = bitmapDrawable.getIntrinsicWidth(); + int bitmapH = bitmapDrawable.getIntrinsicHeight(); float scaleW = bitmapW / (float)w; float scaleH = bitmapH / (float)h; @@ -196,19 +202,25 @@ public class ImageReceiver { bitmapH /= scaleW; drawRegion.set(x, y - (bitmapH - h) / 2, x + w, y + (bitmapH + h) / 2); } - currentImage.setBounds(drawRegion); - currentImage.draw(canvas); + bitmapDrawable.setBounds(drawRegion); + if (isVisible) { + bitmapDrawable.draw(canvas); + } canvas.restore(); } else { drawRegion.set(x, y, x + w, y + h); - currentImage.setBounds(drawRegion); - currentImage.draw(canvas); + bitmapDrawable.setBounds(drawRegion); + if (isVisible) { + bitmapDrawable.draw(canvas); + } } } else if (last_placeholder != null) { drawRegion.set(x, y, x + w, y + h); last_placeholder.setBounds(drawRegion); - last_placeholder.draw(canvas); + if (isVisible) { + last_placeholder.draw(canvas); + } } } catch (Exception e) { if (currentPath != null) { @@ -229,18 +241,24 @@ public class ImageReceiver { return null; } - public void setVisible(boolean value) { + public void setVisible(boolean value, boolean invalidate) { if (isVisible == value) { return; } isVisible = value; - View parent = parentView.get(); - if (parent != null) { - parent.invalidate(); + if (invalidate) { + View parent = parentView.get(); + if (parent != null) { + parent.invalidate(); + } } } public boolean getVisible() { return isVisible; } + + public boolean hasImage() { + return currentImage != null || last_placeholder != null || currentPath != null; + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Views/NotificationView.java b/TMessagesProj/src/main/java/org/telegram/ui/Views/NotificationView.java index 7265fce50..3fef3f2a0 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Views/NotificationView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Views/NotificationView.java @@ -106,16 +106,7 @@ public class NotificationView extends LinearLayout { } hide(true); - if (currentChatId != 0) { - NotificationCenter.getInstance().addToMemCache("push_chat_id", currentChatId); - } - if (currentUserId != 0) { - NotificationCenter.getInstance().addToMemCache("push_user_id", currentUserId); - } - if (currentEncId != 0) { - NotificationCenter.getInstance().addToMemCache("push_enc_id", currentEncId); - } - NotificationCenter.getInstance().postNotificationName(658); + NotificationCenter.getInstance().postNotificationName(658, currentChatId, currentUserId, currentEncId); } }); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Views/PZSImageView.java b/TMessagesProj/src/main/java/org/telegram/ui/Views/PZSImageView.java deleted file mode 100755 index e57f80a4a..000000000 --- a/TMessagesProj/src/main/java/org/telegram/ui/Views/PZSImageView.java +++ /dev/null @@ -1,550 +0,0 @@ -/* - * This is the source code of Telegram for Android v. 1.3.2. - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2013. - */ - -package org.telegram.ui.Views; - -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.Matrix; -import android.graphics.PointF; -import android.graphics.RectF; -import android.util.AttributeSet; -import android.util.FloatMath; -import android.util.TypedValue; -import android.view.GestureDetector; -import android.view.GestureDetector.SimpleOnGestureListener; -import android.view.Gravity; -import android.view.MotionEvent; -import android.view.ViewGroup; -import android.widget.TextView; - -import org.telegram.messenger.FileLog; -import org.telegram.messenger.LocaleController; -import org.telegram.messenger.R; - -public class PZSImageView extends BackupImageView { - - enum ImageScaleType { - FitCenter, TopCrop, CenterCrop - } - - public ImageScaleType defaultScaleType = ImageScaleType.FitCenter; - public ImageScaleType doubleTapScaleType = ImageScaleType.TopCrop; - - // private static final String TAG = "GalleryImageView"; - - // wrapped motion event code. - protected static final int PZS_ACTION_INIT = 100; - protected static final int PZS_ACTION_SCALE = 1001; - protected static final int PZS_ACTION_TRANSLATE = 1002; - protected static final int PZS_ACTION_SCALE_TO_TRANSLATE = 1003; - protected static final int PZS_ACTION_TRANSLATE_TO_SCALE = 1004; - protected static final int PZS_ACTION_FIT_CENTER = 1005; - protected static final int PZS_ACTION_CENTER_CROP = 1006; - protected static final int PZS_ACTION_TO_LEFT_SIDE = 1007; - protected static final int PZS_ACTION_TO_RIGHT_SIDE = 1008; - protected static final int PZS_ACTION_TOP_CROP = 1009; - protected static final int PZS_ACTION_CANCEL = -1; - - private final static float MAX_SCALE_TO_SCREEN = 2.f; - private final static float MIN_SCALE_TO_SCREEN = 1.f; - - private static final float MIN_SCALE_SPAN = 10.f; - - // calculated min / max scale ratio based on image & screen size. - private float mMinScaleFactor = 1.f; - private float mMaxScaleFactor = 2.f; - - public boolean isVideo = false; - private boolean mIsFirstDraw = true; // check flag to calculate necessary - // init values. - private int mImageWidth; // current set image width - private int mImageHeight; // current set image height - - private Context mContext; - - public TextView videoText = null; - - public PZSImageView(Context context) { - super(context); - mContext = context; - init(); - - } - - public PZSImageView(Context context, AttributeSet attrs) { - super(context, attrs); - mContext = context; - init(); - - } - - public PZSImageView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - mContext = context; - init(); - } - - private void init() { - // should use matrix scale type. - setScaleType(ScaleType.MATRIX); - Matrix mat = getImageMatrix(); - mat.reset(); - setImageMatrix(mat); - - gd = new GestureDetector(mContext, new SimpleOnGestureListener() { - - /*@Override - public boolean onDoubleTap(MotionEvent event) { - int action = parseDoubleTapMotionEvent(event); - touchAction(action, event); - return true; // indicate event was handled - }*/ - - @Override - public boolean onSingleTapConfirmed(MotionEvent ev) { - ((AbstractGalleryActivity) mContext).topBtn(); - return true; - } - - }); - - videoText = new TextView(getContext()); - videoText.setTextColor(0xffffffff); - videoText.setBackgroundColor(0x66000000); - videoText.setGravity(Gravity.CENTER); - videoText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24); - videoText.setText(LocaleController.getString("NoChats", R.string.NoChats)); - videoText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); - } - - GestureDetector gd; - - @Override - public void setImageBitmap(Bitmap bitmap, String imgKey) { - super.setImageBitmap(bitmap, imgKey); - mIsFirstDraw = true; - if (bitmap != null) { - mImageWidth = bitmap.getWidth(); - mImageHeight = bitmap.getHeight(); - } else { - mImageWidth = getWidth(); - mImageHeight = getHeight(); - } - } - - public void setImageBitmap(Bitmap bitmap) { - super.setImageBitmap(bitmap); - mIsFirstDraw = true; - if (bitmap != null) { - mImageWidth = bitmap.getWidth(); - mImageHeight = bitmap.getHeight(); - } else { - mImageWidth = getWidth(); - mImageHeight = getHeight(); - } - } - - public void setImageBitmapMy(Bitmap bitmap) { - super.setImageBitmapMy(bitmap); - mIsFirstDraw = true; - if (bitmap != null) { - mImageWidth = bitmap.getWidth(); - mImageHeight = bitmap.getHeight(); - } else { - mImageWidth = getWidth(); - mImageHeight = getHeight(); - } - } - - @Override - protected void onSizeChanged(int w, int h, int oldw, int oldh) { - super.onSizeChanged(w, h, oldw, oldh); - mIsFirstDraw = true; - if (getDrawable() == null) { - mImageHeight = h; - mImageWidth = w; - } - } - - @Override - protected void onDraw(Canvas canvas) { - - if (mIsFirstDraw) { - mIsFirstDraw = false; - if (defaultScaleType == ImageScaleType.FitCenter) - fitCenter(); - else if (defaultScaleType == ImageScaleType.TopCrop) - topCrop(); - else if (defaultScaleType == ImageScaleType.CenterCrop) - centerCrop(); - calculateScaleFactorLimit(); - validateMatrix(); - } - - setImageMatrix(mCurrentMatrix); - - try { - super.onDraw(canvas); - } catch (Exception e) { - FileLog.e("tmessages", e); - FileLog.e("tmessages", "trying draw " + currentPath); - } - } - - private void calculateScaleFactorLimit() { - - // set max / min scale factor. - mMaxScaleFactor = Math.max(getHeight() * MAX_SCALE_TO_SCREEN - / mImageHeight, getWidth() * MAX_SCALE_TO_SCREEN / mImageWidth); - - mMinScaleFactor = Math.min(getHeight() * MIN_SCALE_TO_SCREEN - / mImageHeight, getWidth() * MIN_SCALE_TO_SCREEN / mImageWidth); - - if (getDrawable() == null) { - mMaxScaleFactor = mMinScaleFactor; - } - } - - @Override - public boolean onTouchEvent(MotionEvent event) { - if (gd.onTouchEvent(event)) { - return true; - } - int action = parseMotionEvent(event); - touchAction(action, event); - return true; // indicate event was handled - } - - private void touchAction(int action, MotionEvent event) { - switch (action) { - case PZS_ACTION_INIT: - initGestureAction(event.getX(), event.getY()); - break; - case PZS_ACTION_SCALE: - handleScale(event); - break; - case PZS_ACTION_TRANSLATE: - handleTranslate(event); - break; - case PZS_ACTION_TRANSLATE_TO_SCALE: - initGestureAction(event.getX(), event.getY()); - break; - case PZS_ACTION_SCALE_TO_TRANSLATE: - int activeIndex = (event.getActionIndex() == 0 ? 1 : 0); - initGestureAction(event.getX(activeIndex), event.getY(activeIndex)); - break; - case PZS_ACTION_FIT_CENTER: - fitCenter(); - initGestureAction(event.getX(), event.getY()); - break; - case PZS_ACTION_CENTER_CROP: - centerCrop(); - initGestureAction(event.getX(), event.getY()); - break; - case PZS_ACTION_TOP_CROP: - topCrop(); - initGestureAction(event.getX(), event.getY()); - break; - case PZS_ACTION_TO_LEFT_SIDE: - toLeftSide(); - break; - case PZS_ACTION_TO_RIGHT_SIDE: - toRightSide(); - break; - case PZS_ACTION_CANCEL: - break; - } - - // check current position of bitmap. - validateMatrix(); - updateMatrix(); - } - - private int parseDoubleTapMotionEvent(MotionEvent ev) { - float values[] = new float[9]; - mCurrentMatrix.getValues(values); - float scaleNow = values[Matrix.MSCALE_X]; - float scaleX = (getWidth() - getPaddingLeft() - getPaddingRight()) - / (float) mImageWidth; - float scaleY = (getHeight() - getPaddingTop() - getPaddingBottom()) - / (float) mImageHeight; - if (scaleNow >= Math.max(scaleX, scaleY)) - return PZS_ACTION_FIT_CENTER; - else if (scaleNow < Math.max(scaleX, scaleY)) { - if (doubleTapScaleType == ImageScaleType.FitCenter) - return PZS_ACTION_FIT_CENTER; - else if (doubleTapScaleType == ImageScaleType.TopCrop) - return PZS_ACTION_TOP_CROP; - else if (doubleTapScaleType == ImageScaleType.CenterCrop) - return PZS_ACTION_CENTER_CROP; - - } - return PZS_ACTION_FIT_CENTER; - } - - private int parseMotionEvent(MotionEvent ev) { - - switch (ev.getAction() & MotionEvent.ACTION_MASK) { - case MotionEvent.ACTION_DOWN: - return PZS_ACTION_INIT; - case MotionEvent.ACTION_POINTER_DOWN: - // more than one pointer is pressed... - return PZS_ACTION_TRANSLATE_TO_SCALE; - case MotionEvent.ACTION_UP: - case MotionEvent.ACTION_POINTER_UP: - if (ev.getPointerCount() == 2) { - return PZS_ACTION_SCALE_TO_TRANSLATE; - } else { - return PZS_ACTION_INIT; - } - case MotionEvent.ACTION_MOVE: - if (ev.getPointerCount() == 1) - return PZS_ACTION_TRANSLATE; - else if (ev.getPointerCount() == 2) - return PZS_ACTION_SCALE; - return 0; - } - return 0; - } - - // /////////////////////////////////////////////// - // Related matrix calculation stuffs. - // /////////////////////////////////////////////// - - private Matrix mCurrentMatrix = new Matrix(); - private Matrix mSavedMatrix = new Matrix(); - - // Remember some things for zooming - private PointF mStartPoint = new PointF(); - private PointF mMidPoint = new PointF(); - private float mInitScaleSpan = 1f; - - protected void initGestureAction(float x, float y) { - mSavedMatrix.set(mCurrentMatrix); - mStartPoint.set(x, y); - mInitScaleSpan = 0.f; - } - - protected void handleScale(MotionEvent event) { - if (isVideo) { - return; - } - float newSpan = spacing(event); - - // if two finger is too close, pointer index is bumped.. so just ignore - // it. - if (newSpan < MIN_SCALE_SPAN) - return; - - if (mInitScaleSpan == 0.f) { - // init values. scale gesture action is just started. - mInitScaleSpan = newSpan; - midPoint(mMidPoint, event); - } else { - float scale = normalizeScaleFactor(mSavedMatrix, newSpan, - mInitScaleSpan); - mCurrentMatrix.set(mSavedMatrix); - mCurrentMatrix.postScale(scale, scale, mMidPoint.x, mMidPoint.y); - } - } - - private float normalizeScaleFactor(Matrix curMat, float newSpan, - float stdSpan) { - - float values[] = new float[9]; - curMat.getValues(values); - float scale = values[Matrix.MSCALE_X]; - - if (stdSpan == newSpan) { - return scale; - } else { - float newScaleFactor = newSpan / stdSpan; - float candinateScale = scale * newScaleFactor; - - if (candinateScale > mMaxScaleFactor) { - return mMaxScaleFactor / scale; - } else if (candinateScale < mMinScaleFactor) { - return mMinScaleFactor / scale; - } else { - return newScaleFactor; - } - } - } - - protected void handleTranslate(MotionEvent event) { - mCurrentMatrix.set(mSavedMatrix); - mCurrentMatrix.postTranslate(event.getX() - mStartPoint.x, event.getY() - - mStartPoint.y); - } - - private RectF mTraslateLimitRect = new RectF(); // reuse instance. - - public boolean getOnLeftSide() { - float values[] = new float[9]; - mCurrentMatrix.getValues(values); - float tranX = values[Matrix.MTRANS_X]; - return tranX >= mTraslateLimitRect.right; - } - - public boolean getOnRightSide() { - float values[] = new float[9]; - mCurrentMatrix.getValues(values); - float tranX = values[Matrix.MTRANS_X]; - return tranX <= mTraslateLimitRect.left; - } - - private void validateMatrix() { - float values[] = new float[9]; - mCurrentMatrix.getValues(values); - - // get current matrix values. - float scale = values[Matrix.MSCALE_X]; - float tranX = values[Matrix.MTRANS_X]; - float tranY = values[Matrix.MTRANS_Y]; - - int imageHeight = (int) (scale * mImageHeight); - int imageWidth = (int) (scale * mImageWidth); - if (imageHeight == 0 || imageWidth == 0) { - imageHeight = getHeight(); - imageWidth = getWidth(); - } - - mTraslateLimitRect.setEmpty(); - // don't think about optimize code. first, just write code case by case. - - // check TOP & BOTTOM - if (imageHeight > getHeight()) { - // image height is taller than view - mTraslateLimitRect.top = getHeight() - imageHeight - - getPaddingTop() - getPaddingBottom(); - mTraslateLimitRect.bottom = 0.f; - } else { - mTraslateLimitRect.top = mTraslateLimitRect.bottom = (getHeight() - - imageHeight - getPaddingTop() - getPaddingBottom()) / 2.f; - } - - // check LEFT & RIGHT - if (imageWidth > getWidth()) { - // image width is longer than view - mTraslateLimitRect.left = getWidth() - imageWidth - - getPaddingRight() - getPaddingLeft(); - mTraslateLimitRect.right = 0.f; - } else { - mTraslateLimitRect.left = mTraslateLimitRect.right = (getWidth() - - imageWidth - getPaddingLeft() - getPaddingRight()) / 2.f; - } - - float newTranX = tranX; - newTranX = Math.max(newTranX, mTraslateLimitRect.left); - newTranX = Math.min(newTranX, mTraslateLimitRect.right); - - float newTranY = tranY; - newTranY = Math.max(newTranY, mTraslateLimitRect.top); - newTranY = Math.min(newTranY, mTraslateLimitRect.bottom); - - values[Matrix.MTRANS_X] = newTranX; - values[Matrix.MTRANS_Y] = newTranY; - mCurrentMatrix.setValues(values); - - if (!mTraslateLimitRect.contains(tranX, tranY)) { - // set new start point. - mStartPoint.offset(tranX - newTranX, tranY - newTranY); - } - } - - protected void updateMatrix() { - setImageMatrix(mCurrentMatrix); - } - - protected void fitCenter() { - // move image to center.... - mCurrentMatrix.reset(); - - float scaleX = (getWidth() - getPaddingLeft() - getPaddingRight()) - / (float) mImageWidth; - float scaleY = (getHeight() - getPaddingTop() - getPaddingBottom()) - / (float) mImageHeight; - float scale = Math.min(scaleX, scaleY); - - float dx = (getWidth() - getPaddingLeft() - getPaddingRight() - mImageWidth - * scale) / 2.f; - float dy = (getHeight() - getPaddingTop() - getPaddingBottom() - mImageHeight - * scale) / 2.f; - mCurrentMatrix.postScale(scale, scale); - mCurrentMatrix.postTranslate(dx, dy); - setImageMatrix(mCurrentMatrix); - } - - public void toLeftSide() { - float values[] = new float[9]; - mCurrentMatrix.getValues(values); - float tranX = values[Matrix.MTRANS_X]; - mCurrentMatrix.postTranslate(mTraslateLimitRect.right - tranX, 0); - setImageMatrix(mCurrentMatrix); - } - - public void toRightSide() { - float values[] = new float[9]; - mCurrentMatrix.getValues(values); - float tranX = values[Matrix.MTRANS_X]; - mCurrentMatrix.postTranslate(mTraslateLimitRect.left - tranX, 0); - setImageMatrix(mCurrentMatrix); - } - - protected void centerCrop() { - mCurrentMatrix.reset(); - - float scaleX = (getWidth() - getPaddingLeft() - getPaddingRight()) - / (float) mImageWidth; - float scaleY = (getHeight() - getPaddingTop() - getPaddingBottom()) - / (float) mImageHeight; - float scale = Math.max(scaleX, scaleY); - - float dx = (getWidth() - getPaddingLeft() - getPaddingRight() - mImageWidth - * scale) / 2.f; - float dy = (getHeight() - getPaddingTop() - getPaddingBottom() - mImageHeight - * scale) / 2.f; - - mCurrentMatrix.postScale(scale, scale); - mCurrentMatrix.postTranslate(dx, dy); - setImageMatrix(mCurrentMatrix); - } - - protected void topCrop() { - mCurrentMatrix.reset(); - - float scaleX = (getWidth() - getPaddingLeft() - getPaddingRight()) - / (float) mImageWidth; - float scaleY = (getHeight() - getPaddingTop() - getPaddingBottom()) - / (float) mImageHeight; - float scale = Math.max(scaleX, scaleY); - - mCurrentMatrix.postScale(scale, scale); - mCurrentMatrix.postTranslate(0, 0); - setImageMatrix(mCurrentMatrix); - } - - /** Determine the space between the first two fingers */ - private float spacing(MotionEvent event) { - // ... - float x = event.getX(0) - event.getX(1); - float y = event.getY(0) - event.getY(1); - return FloatMath.sqrt(x * x + y * y); - } - - /** Calculate the mid point of the first two fingers */ - private void midPoint(PointF point, MotionEvent event) { - // ... - float x = event.getX(0) + event.getX(1); - float y = event.getY(0) + event.getY(1); - point.set(x / 2, y / 2); - } - -} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Views/PausableActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/Views/PausableActivity.java deleted file mode 100644 index 8aee1b949..000000000 --- a/TMessagesProj/src/main/java/org/telegram/ui/Views/PausableActivity.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * This is the source code of Telegram for Android v. 1.3.2. - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2013. - */ - -package org.telegram.ui.Views; - -import android.support.v7.app.ActionBarActivity; - -import org.telegram.ui.ApplicationLoader; - -public class PausableActivity extends ActionBarActivity { - - @Override - protected void onPause() { - super.onPause(); - ApplicationLoader.lastPauseTime = System.currentTimeMillis(); - } - - @Override - protected void onResume() { - super.onResume(); - ApplicationLoader.resetLastPauseTime(); - } -} diff --git a/TMessagesProj/src/main/res/drawable/gallery_action_bar.xml b/TMessagesProj/src/main/res/drawable/gallery_action_bar.xml deleted file mode 100644 index 972995297..000000000 --- a/TMessagesProj/src/main/res/drawable/gallery_action_bar.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/TMessagesProj/src/main/res/drawable/photo_download_cancel_states.xml b/TMessagesProj/src/main/res/drawable/photo_download_cancel_states.xml deleted file mode 100644 index df64a4b09..000000000 --- a/TMessagesProj/src/main/res/drawable/photo_download_cancel_states.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/TMessagesProj/src/main/res/drawable/photo_download_states.xml b/TMessagesProj/src/main/res/drawable/photo_download_states.xml deleted file mode 100644 index 122ca213c..000000000 --- a/TMessagesProj/src/main/res/drawable/photo_download_states.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/TMessagesProj/src/main/res/layout/gallery_layout.xml b/TMessagesProj/src/main/res/layout/gallery_layout.xml deleted file mode 100644 index 916b9cd78..000000000 --- a/TMessagesProj/src/main/res/layout/gallery_layout.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/TMessagesProj/src/main/res/layout/gallery_page_layout.xml b/TMessagesProj/src/main/res/layout/gallery_page_layout.xml deleted file mode 100644 index d9dbb8b07..000000000 --- a/TMessagesProj/src/main/res/layout/gallery_page_layout.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - diff --git a/TMessagesProj/src/main/res/values/styles.xml b/TMessagesProj/src/main/res/values/styles.xml index 8d83da71d..dcaa2c83a 100644 --- a/TMessagesProj/src/main/res/values/styles.xml +++ b/TMessagesProj/src/main/res/values/styles.xml @@ -24,48 +24,12 @@ @drawable/bar_selector - - - - @@ -75,18 +39,6 @@ 18sp - - - - - -