diff --git a/TMessagesProj/build.gradle b/TMessagesProj/build.gradle index 09f4e23bb..7aa13b57d 100644 --- a/TMessagesProj/build.gradle +++ b/TMessagesProj/build.gradle @@ -82,7 +82,7 @@ android { defaultConfig { minSdkVersion 8 targetSdkVersion 22 - versionCode 479 - versionName "2.6.1" + versionCode 492 + versionName "2.7.0" } } diff --git a/TMessagesProj/jni/Android.mk b/TMessagesProj/jni/Android.mk index ae2c63233..f9b84ba96 100755 --- a/TMessagesProj/jni/Android.mk +++ b/TMessagesProj/jni/Android.mk @@ -104,7 +104,7 @@ include $(BUILD_STATIC_LIBRARY) include $(CLEAR_VARS) LOCAL_PRELINK_MODULE := false LOCAL_STATIC_LIBRARIES := webp sqlite -LOCAL_MODULE := tmessages.6 +LOCAL_MODULE := tmessages.7 LOCAL_CFLAGS := -w -std=gnu99 -O2 -DNULL=0 -DSOCKLEN_T=socklen_t -DLOCALE_NOT_USED -D_LARGEFILE_SOURCE=1 -D_FILE_OFFSET_BITS=64 LOCAL_CFLAGS += -Drestrict='' -D__EMX__ -DOPUS_BUILD -DFIXED_POINT -DUSE_ALLOCA -DHAVE_LRINT -DHAVE_LRINTF -fno-math-errno LOCAL_CFLAGS += -DANDROID_NDK -DDISABLE_IMPORTGL -fno-strict-aliasing -fprefetch-loop-arrays -DAVOID_TABLES -DANDROID_TILE_BASED_DECODE -DANDROID_ARMV6_IDCT -ffast-math diff --git a/TMessagesProj/jni/image.c b/TMessagesProj/jni/image.c index 06c5e9f3b..85a859007 100644 --- a/TMessagesProj/jni/image.c +++ b/TMessagesProj/jni/image.c @@ -419,6 +419,11 @@ JNIEXPORT void Java_org_telegram_messenger_Utilities_calcCDT(JNIEnv *env, jclass free(cdfsMin); } +JNIEXPORT int Java_org_telegram_messenger_Utilities_pinBitmap(JNIEnv *env, jclass class, jobject bitmap) { + unsigned char *pixels; + return AndroidBitmap_lockPixels(env, bitmap, &pixels) >= 0 ? 1 : 0; +} + JNIEXPORT void Java_org_telegram_messenger_Utilities_loadBitmap(JNIEnv *env, jclass class, jstring path, jobject bitmap, int scale, int width, int height, int stride) { AndroidBitmapInfo info; diff --git a/TMessagesProj/libs/armeabi-v7a/libtmessages.6.so b/TMessagesProj/libs/armeabi-v7a/libtmessages.7.so similarity index 85% rename from TMessagesProj/libs/armeabi-v7a/libtmessages.6.so rename to TMessagesProj/libs/armeabi-v7a/libtmessages.7.so index 41f66ec83..c086f4a98 100755 Binary files a/TMessagesProj/libs/armeabi-v7a/libtmessages.6.so and b/TMessagesProj/libs/armeabi-v7a/libtmessages.7.so differ diff --git a/TMessagesProj/libs/armeabi/libtmessages.6.so b/TMessagesProj/libs/armeabi/libtmessages.7.so similarity index 78% rename from TMessagesProj/libs/armeabi/libtmessages.6.so rename to TMessagesProj/libs/armeabi/libtmessages.7.so index aa46c0891..42ad265ae 100755 Binary files a/TMessagesProj/libs/armeabi/libtmessages.6.so and b/TMessagesProj/libs/armeabi/libtmessages.7.so differ diff --git a/TMessagesProj/libs/x86/libtmessages.6.so b/TMessagesProj/libs/x86/libtmessages.7.so similarity index 73% rename from TMessagesProj/libs/x86/libtmessages.6.so rename to TMessagesProj/libs/x86/libtmessages.7.so index e455cf5ad..aaa768eac 100755 Binary files a/TMessagesProj/libs/x86/libtmessages.6.so and b/TMessagesProj/libs/x86/libtmessages.7.so differ diff --git a/TMessagesProj/src/main/java/org/telegram/android/AndroidUtilities.java b/TMessagesProj/src/main/java/org/telegram/android/AndroidUtilities.java index 5134c3985..b14c401b2 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/AndroidUtilities.java +++ b/TMessagesProj/src/main/java/org/telegram/android/AndroidUtilities.java @@ -14,6 +14,7 @@ import android.content.Context; import android.content.DialogInterface; import android.content.pm.ActivityInfo; import android.content.res.Configuration; +import android.graphics.Color; import android.graphics.Point; import android.graphics.Rect; import android.graphics.Typeface; @@ -23,6 +24,7 @@ import android.os.Environment; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.Spanned; +import android.text.style.ForegroundColorSpan; import android.util.DisplayMetrics; import android.util.StateSet; import android.view.Display; @@ -43,6 +45,10 @@ import org.telegram.messenger.R; import org.telegram.messenger.TLRPC; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.UserConfig; +import org.telegram.ui.AnimationCompat.AnimatorListenerAdapterProxy; +import org.telegram.ui.AnimationCompat.AnimatorSetProxy; +import org.telegram.ui.AnimationCompat.ObjectAnimatorProxy; +import org.telegram.ui.AnimationCompat.ViewProxy; import org.telegram.ui.Components.ForegroundDetector; import org.telegram.ui.Components.NumberPicker; import org.telegram.ui.Components.TypefaceSpan; @@ -538,21 +544,51 @@ public class AndroidUtilities { } } - public static Spannable replaceBold(String str) { - int start; - ArrayList bolds = new ArrayList<>(); - while ((start = str.indexOf("")) != -1) { - int end = str.indexOf("") - 3; - str = str.replaceFirst("", "").replaceFirst("", ""); - bolds.add(start); - bolds.add(end); + public static Spannable replaceTags(String str) { + try { + int start = -1; + int startColor = -1; + int end = -1; + StringBuilder stringBuilder = new StringBuilder(str); + while ((start = stringBuilder.indexOf("
")) != -1) { + stringBuilder.replace(start, start + 4, "\n"); + } + while ((start = stringBuilder.indexOf("
")) != -1) { + stringBuilder.replace(start, start + 5, "\n"); + } + ArrayList bolds = new ArrayList<>(); + ArrayList colors = new ArrayList<>(); + while ((start = stringBuilder.indexOf("")) != -1 || (startColor = stringBuilder.indexOf(""); + stringBuilder.replace(end, end + 4, ""); + bolds.add(start); + bolds.add(end); + } else if (startColor != -1) { + stringBuilder.replace(startColor, startColor + 2, ""); + end = stringBuilder.indexOf(">", startColor); + int color = Color.parseColor(stringBuilder.substring(startColor, end)); + stringBuilder.replace(startColor, end + 1, ""); + end = stringBuilder.indexOf(""); + stringBuilder.replace(end, end + 4, ""); + colors.add(startColor); + colors.add(end); + colors.add(color); + } + } + SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(stringBuilder); + for (int a = 0; a < bolds.size() / 2; a++) { + spannableStringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")), bolds.get(a * 2), bolds.get(a * 2 + 1), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + } + for (int a = 0; a < colors.size() / 3; a++) { + spannableStringBuilder.setSpan(new ForegroundColorSpan(colors.get(a * 3 + 2)), colors.get(a * 3), colors.get(a * 3 + 1), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + } + return spannableStringBuilder; + } catch (Exception e) { + FileLog.e("tmessages", e); } - SpannableStringBuilder stringBuilder = new SpannableStringBuilder(str); - for (int a = 0; a < bolds.size() / 2; a++) { - TypefaceSpan span = new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - stringBuilder.setSpan(span, bolds.get(a * 2), bolds.get(a * 2 + 1), Spanned.SPAN_INCLUSIVE_INCLUSIVE); - } - return stringBuilder; + return new SpannableStringBuilder(str); } public static boolean needShowPasscode(boolean reset) { @@ -569,6 +605,61 @@ public class AndroidUtilities { (UserConfig.appLocked || UserConfig.autoLockIn != 0 && UserConfig.lastPauseTime != 0 && !UserConfig.appLocked && (UserConfig.lastPauseTime + UserConfig.autoLockIn) <= ConnectionsManager.getInstance().getCurrentTime()); } + public static void shakeTextView(final TextView textView, final float x, final int num) { + if (num == 6) { + ViewProxy.setTranslationX(textView, 0); + textView.clearAnimation(); + return; + } + AnimatorSetProxy animatorSetProxy = new AnimatorSetProxy(); + animatorSetProxy.playTogether(ObjectAnimatorProxy.ofFloat(textView, "translationX", AndroidUtilities.dp(x))); + animatorSetProxy.setDuration(50); + animatorSetProxy.addListener(new AnimatorListenerAdapterProxy() { + @Override + public void onAnimationEnd(Object animation) { + shakeTextView(textView, num == 5 ? 0 : -x, num + 1); + } + }); + animatorSetProxy.start(); + } + + + + /*public static String ellipsize(String text, int maxLines, int maxWidth, TextPaint paint) { + if (text == null || paint == null) { + return null; + } + int count; + int offset = 0; + StringBuilder result = null; + TextView + for (int a = 0; a < maxLines; a++) { + count = paint.breakText(text, true, maxWidth, null); + if (a != maxLines - 1) { + if (result == null) { + result = new StringBuilder(count * maxLines + 1); + } + boolean foundSpace = false; + for (int c = count - 1; c >= offset; c--) { + if (text.charAt(c) == ' ') { + foundSpace = true; + result.append(text.substring(offset, c - 1)); + offset = c - 1; + } + } + if (!foundSpace) { + offset = count; + } + text = text.substring(0, offset); + } else if (maxLines == 1) { + return text.substring(0, count); + } else { + result.append(text.substring(0, count)); + } + } + return result.toString(); + }*/ + /*public static void turnOffHardwareAcceleration(Window window) { if (window == null || Build.MODEL == null || Build.VERSION.SDK_INT < 11) { return; diff --git a/TMessagesProj/src/main/java/org/telegram/android/ImageLoader.java b/TMessagesProj/src/main/java/org/telegram/android/ImageLoader.java index 2cca9e968..fb6363697 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/ImageLoader.java +++ b/TMessagesProj/src/main/java/org/telegram/android/ImageLoader.java @@ -645,9 +645,13 @@ public class ImageLoader { } else { opts.inPreferredConfig = Bitmap.Config.RGB_565; } + //if (Build.VERSION.SDK_INT < 21) { + // opts.inPurgeable = true; + //} + opts.inDither = false; if (mediaId != null) { - image = MediaStore.Images.Thumbnails.getThumbnail(ApplicationLoader.applicationContext.getContentResolver(), mediaId, MediaStore.Images.Thumbnails.MINI_KIND, null); + image = MediaStore.Images.Thumbnails.getThumbnail(ApplicationLoader.applicationContext.getContentResolver(), mediaId, MediaStore.Images.Thumbnails.MINI_KIND, opts); } if (image == null) { if (isWebp) { @@ -1981,6 +1985,15 @@ public class ImageLoader { } } } + } else if (message.media instanceof TLRPC.TL_messageMediaWebPage) { + if (message.media.webpage.photo != null) { + for (TLRPC.PhotoSize size : message.media.webpage.photo.sizes) { + if (size instanceof TLRPC.TL_photoCachedSize) { + photoSize = size; + break; + } + } + } } if (photoSize != null && photoSize.bytes != null && photoSize.bytes.length != 0) { if (photoSize.location instanceof TLRPC.TL_fileLocationUnavailable) { @@ -2018,6 +2031,13 @@ public class ImageLoader { message.media.video.thumb = newPhotoSize; } else if (message.media instanceof TLRPC.TL_messageMediaDocument) { message.media.document.thumb = newPhotoSize; + } else if (message.media instanceof TLRPC.TL_messageMediaWebPage) { + for (int a = 0; a < message.media.webpage.photo.sizes.size(); a++) { + if (message.media.webpage.photo.sizes.get(a) instanceof TLRPC.TL_photoCachedSize) { + message.media.webpage.photo.sizes.set(a, newPhotoSize); + break; + } + } } } } diff --git a/TMessagesProj/src/main/java/org/telegram/android/ImageReceiver.java b/TMessagesProj/src/main/java/org/telegram/android/ImageReceiver.java index fa79c264b..6f50bdc59 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/ImageReceiver.java +++ b/TMessagesProj/src/main/java/org/telegram/android/ImageReceiver.java @@ -68,7 +68,6 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg private Matrix shaderMatrix; private int alpha = 255; private boolean isPressed; - private boolean disableRecycle; private int orientation; private boolean centerRotation; private ImageReceiverDelegate delegate; @@ -224,10 +223,6 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg setImageBitmap(bitmap != null ? new BitmapDrawable(null, bitmap) : null); } - public void setDisableRecycle(boolean value) { - disableRecycle = value; - } - public void setImageBitmap(Drawable bitmap) { ImageLoader.getInstance().cancelLoadingForImageReceiver(this, 0); recycleBitmap(null, false); @@ -497,10 +492,18 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg return imageX; } + public int getImageX2() { + return imageX + imageW; + } + public int getImageY() { return imageY; } + public int getImageY2() { + return imageY + imageH; + } + public int getImageWidth() { return imageW; } @@ -682,7 +685,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg if (newKey != null) { newBitmap = ImageLoader.getInstance().getImageFromMemory(newKey); } - if (key == null || image == null || image == newBitmap || disableRecycle) { + if (key == null || image == null || image == newBitmap) { return; } Bitmap bitmap = image.getBitmap(); diff --git a/TMessagesProj/src/main/java/org/telegram/android/MediaController.java b/TMessagesProj/src/main/java/org/telegram/android/MediaController.java index 0fd27e2ad..629268341 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/MediaController.java +++ b/TMessagesProj/src/main/java/org/telegram/android/MediaController.java @@ -1105,8 +1105,16 @@ public class MediaController implements NotificationCenter.NotificationCenterDel if (proximitySensor != null && audioTrackPlayer == null && audioPlayer == null || isPaused || (useFrontSpeaker == (event.values[0] < proximitySensor.getMaximumRange() / 10))) { return; } + boolean newValue = event.values[0] < proximitySensor.getMaximumRange() / 10; + try { + if (newValue && NotificationsController.getInstance().audioManager.isWiredHeadsetOn()) { + return; + } + } catch (Exception e) { + FileLog.e("tmessages", e); + } ignoreProximity = true; - useFrontSpeaker = event.values[0] < proximitySensor.getMaximumRange() / 10; + useFrontSpeaker = newValue; NotificationCenter.getInstance().postNotificationName(NotificationCenter.audioRouteChanged, useFrontSpeaker); MessageObject currentMessageObject = playingMessageObject; float progress = playingMessageObject.audioProgress; diff --git a/TMessagesProj/src/main/java/org/telegram/android/MessageObject.java b/TMessagesProj/src/main/java/org/telegram/android/MessageObject.java index 8c5f00ab2..525c91eba 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/MessageObject.java +++ b/TMessagesProj/src/main/java/org/telegram/android/MessageObject.java @@ -41,6 +41,7 @@ public class MessageObject { public TLRPC.Message messageOwner; public CharSequence messageText; + public CharSequence linkDescription; public MessageObject replyMessageObject; public int type; public int contentType; @@ -273,7 +274,7 @@ public class MessageObject { messageText = LocaleController.formatString("YouCreatedBroadcastList", R.string.YouCreatedBroadcastList); } } - } else if (message.media != null && !(message.media instanceof TLRPC.TL_messageMediaEmpty)) { + } else if (!isMediaEmpty()) { if (message.media instanceof TLRPC.TL_messageMediaPhoto) { messageText = LocaleController.getString("AttachPhoto", R.string.AttachPhoto); } else if (message.media instanceof TLRPC.TL_messageMediaVideo) { @@ -309,22 +310,22 @@ public class MessageObject { messageText = Emoji.replaceEmoji(messageText, textPaint.getFontMetricsInt(), AndroidUtilities.dp(20)); if (message instanceof TLRPC.TL_message || message instanceof TLRPC.TL_messageForwarded_old2) { - if (message.media == null || message.media instanceof TLRPC.TL_messageMediaEmpty) { + if (isMediaEmpty()) { contentType = type = 0; - } else if (message.media != null && message.media instanceof TLRPC.TL_messageMediaPhoto) { + } else if (message.media instanceof TLRPC.TL_messageMediaPhoto) { contentType = type = 1; - } else if (message.media != null && message.media instanceof TLRPC.TL_messageMediaGeo) { + } else if (message.media instanceof TLRPC.TL_messageMediaGeo) { contentType = 1; type = 4; - } else if (message.media != null && message.media instanceof TLRPC.TL_messageMediaVideo) { + } else if (message.media instanceof TLRPC.TL_messageMediaVideo) { contentType = 1; type = 3; - } else if (message.media != null && message.media instanceof TLRPC.TL_messageMediaContact) { + } else if (message.media instanceof TLRPC.TL_messageMediaContact) { contentType = 3; type = 12; - } else if (message.media != null && message.media instanceof TLRPC.TL_messageMediaUnsupported) { + } else if (message.media instanceof TLRPC.TL_messageMediaUnsupported) { contentType = type = 0; - } else if (message.media != null && message.media instanceof TLRPC.TL_messageMediaDocument) { + } else if (message.media instanceof TLRPC.TL_messageMediaDocument) { contentType = 1; if (message.media.document.mime_type != null) { if (message.media.document.mime_type.equals("image/gif") && message.media.document.thumb != null && !(message.media.document.thumb instanceof TLRPC.TL_photoSizeEmpty)) { @@ -340,7 +341,7 @@ public class MessageObject { } else { type = 9; } - } else if (message.media != null && message.media instanceof TLRPC.TL_messageMediaAudio) { + } else if (message.media instanceof TLRPC.TL_messageMediaAudio) { contentType = type = 2; } } else if (message instanceof TLRPC.TL_messageService) { @@ -433,6 +434,24 @@ public class MessageObject { photoObject.location = messageOwner.media.document.thumb.location; } } + } else if (messageOwner.media instanceof TLRPC.TL_messageMediaWebPage) { + if (messageOwner.media.webpage.photo != null) { + if (!update || photoThumbs == null) { + photoThumbs = new ArrayList<>(messageOwner.media.webpage.photo.sizes); + } else if (photoThumbs != null && !photoThumbs.isEmpty()) { + for (TLRPC.PhotoSize photoObject : photoThumbs) { + for (TLRPC.PhotoSize size : messageOwner.media.webpage.photo.sizes) { + if (size instanceof TLRPC.TL_photoSizeEmpty) { + continue; + } + if (size.type.equals(photoObject.type)) { + photoObject.location = size.location; + break; + } + } + } + } + } } } } @@ -538,11 +557,24 @@ public class MessageObject { return false; } + public void generateLinkDescription() { + if (linkDescription != null) { + return; + } + if (messageOwner.media instanceof TLRPC.TL_messageMediaWebPage && messageOwner.media.webpage instanceof TLRPC.TL_webPage && messageOwner.media.webpage.description != null) { + linkDescription = Spannable.Factory.getInstance().newSpannable(messageOwner.media.webpage.description); + if (containsUrls(linkDescription)) { + Linkify.addLinks((Spannable) linkDescription, Linkify.WEB_URLS); + } + } + } + private void generateLayout() { if (type != 0 || messageOwner.to_id == null || messageText == null || messageText.length() == 0) { return; } + generateLinkDescription(); textLayoutBlocks = new ArrayList<>(); if (messageText instanceof Spannable && containsUrls(messageText)) { @@ -781,7 +813,7 @@ public class MessageObject { } public boolean isSending() { - return messageOwner.send_state == MESSAGE_SEND_STATE_SENDING; + return messageOwner.send_state == MESSAGE_SEND_STATE_SENDING && messageOwner.id < 0; } public boolean isSendError() { @@ -789,7 +821,7 @@ public class MessageObject { } public boolean isSent() { - return messageOwner.send_state == MESSAGE_SEND_STATE_SENT; + return messageOwner.send_state == MESSAGE_SEND_STATE_SENT || messageOwner.id > 0; } public String getSecretTimeString() { @@ -944,4 +976,12 @@ public class MessageObject { public boolean isReply() { return !(replyMessageObject != null && replyMessageObject.messageOwner instanceof TLRPC.TL_messageEmpty) && messageOwner.reply_to_msg_id != 0 && (messageOwner.flags & TLRPC.MESSAGE_FLAG_REPLY) != 0; } + + public boolean isMediaEmpty() { + return isMediaEmpty(messageOwner); + } + + public static boolean isMediaEmpty(TLRPC.Message message) { + return message == null || message.media == null || message.media instanceof TLRPC.TL_messageMediaEmpty || message.media instanceof TLRPC.TL_messageMediaWebPage; + } } diff --git a/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java b/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java index 7f37da1f0..6d2b29972 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java +++ b/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java @@ -13,7 +13,6 @@ import android.app.AlertDialog; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.os.Build; -import android.text.Html; import android.util.Base64; import android.util.SparseArray; @@ -179,7 +178,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter } public void updateConfig(final TLRPC.TL_config config) { - AndroidUtilities.runOnUIThread(new Runnable() { + AndroidUtilities.runOnUIThread(new Runnable() { //TODO use new config params @Override public void run() { maxBroadcastCount = config.broadcast_size_max; @@ -1307,12 +1306,12 @@ public class MessagesController implements NotificationCenter.NotificationCenter if (label.length() != 0) { if (count > 1) { if (arr.size() > 2) { - newPrintingStrings.put(key, Html.fromHtml(String.format("%s %s", label, LocaleController.formatPluralString("AndMoreTyping", arr.size() - 2)))); + newPrintingStrings.put(key, String.format("%s %s", label, LocaleController.formatPluralString("AndMoreTyping", arr.size() - 2))); } else { - newPrintingStrings.put(key, Html.fromHtml(String.format("%s %s", label, LocaleController.getString("AreTyping", R.string.AreTyping)))); + newPrintingStrings.put(key, String.format("%s %s", label, LocaleController.getString("AreTyping", R.string.AreTyping))); } } else { - newPrintingStrings.put(key, Html.fromHtml(String.format("%s %s", label, LocaleController.getString("IsTyping", R.string.IsTyping)))); + newPrintingStrings.put(key, String.format("%s %s", label, LocaleController.getString("IsTyping", R.string.IsTyping))); } } } @@ -1472,12 +1471,21 @@ public class MessagesController implements NotificationCenter.NotificationCenter for (TLRPC.Message message : messagesRes.messages) { message.dialog_id = dialog_id; objects.add(new MessageObject(message, usersLocal, true)); - if (isCache && message.media instanceof TLRPC.TL_messageMediaUnsupported) { - if (message.media.bytes.length == 0 || message.media.bytes.length == 1 && message.media.bytes[0] < TLRPC.LAYER) { - if (messagesToReload == null) { - messagesToReload = new ArrayList<>(); + if (isCache) { + if (message.media instanceof TLRPC.TL_messageMediaUnsupported) { + if (message.media.bytes.length == 0 || message.media.bytes.length == 1 && message.media.bytes[0] < TLRPC.LAYER) { + if (messagesToReload == null) { + messagesToReload = new ArrayList<>(); + } + messagesToReload.add(message.id); + } + } else if (message.media instanceof TLRPC.TL_messageMediaWebPage) { + if (message.media.webpage instanceof TLRPC.TL_webPagePending && message.media.webpage.date <= ConnectionsManager.getInstance().getCurrentTime()) { + if (messagesToReload == null) { + messagesToReload = new ArrayList<>(); + } + messagesToReload.add(message.id); } - messagesToReload.add(message.id); } } } @@ -1941,7 +1949,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter } } - public long createChat(String title, ArrayList selectedContacts, final TLRPC.InputFile uploadedAvatar, boolean isBroadcast) { + public long createChat(String title, ArrayList selectedContacts, boolean isBroadcast) { if (isBroadcast) { TLRPC.TL_chat chat = new TLRPC.TL_chat(); chat.id = UserConfig.lastBroadcastId; @@ -2015,35 +2023,21 @@ public class MessagesController implements NotificationCenter.NotificationCenter }); return; } - final TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response; - MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true); - + final TLRPC.Updates updates = (TLRPC.Updates) response; + processUpdates(updates, false); AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { - putUsers(res.users, false); - putChats(res.chats, false); - final ArrayList messagesObj = new ArrayList<>(); - messagesObj.add(new MessageObject(res.message, users, true)); - TLRPC.Chat chat = res.chats.get(0); - updateInterfaceWithMessages(-chat.id, messagesObj); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidCreated, chat.id); - if (uploadedAvatar != null) { - changeChatAvatar(chat.id, uploadedAvatar); + putUsers(updates.users, false); + putChats(updates.chats, false); + TLRPC.Chat chat = null; + if (updates.chats != null && !updates.chats.isEmpty()) { + NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidCreated, updates.chats.get(0).id); + } else { + NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidFailCreate); } } }); - - final ArrayList messages = new ArrayList<>(); - messages.add(res.message); - MessagesStorage.getInstance().putMessages(messages, true, true, false, 0); - - if (res instanceof TLRPC.TL_messages_statedMessage) { - MessagesController.getInstance().processNewDifferenceParams(-1, res.pts, res.message.date, res.pts_count); - } else if (res instanceof TLRPC.TL_messages_statedMessageLink) { - MessagesController.getInstance().processNewDifferenceParams(res.seq, res.pts, res.message.date, res.pts_count); - } } }); } @@ -2066,48 +2060,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter if (error != null) { return; } - - final TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response; - MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true); - - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - putUsers(res.users, false); - putChats(res.chats, false); - final ArrayList messagesObj = new ArrayList<>(); - messagesObj.add(new MessageObject(res.message, users, true)); - TLRPC.Chat chat = res.chats.get(0); - updateInterfaceWithMessages(-chat.id, messagesObj); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_MEMBERS); - - if (info != null) { - for (TLRPC.TL_chatParticipant p : info.participants) { - if (p.user_id == user.id) { - return; - } - } - TLRPC.TL_chatParticipant newPart = new TLRPC.TL_chatParticipant(); - newPart.user_id = user.id; - newPart.inviter_id = UserConfig.getClientUserId(); - newPart.date = ConnectionsManager.getInstance().getCurrentTime(); - info.participants.add(0, newPart); - MessagesStorage.getInstance().updateChatInfo(info.chat_id, info, true); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatInfoDidLoaded, info.chat_id, info); - } - } - }); - - final ArrayList messages = new ArrayList<>(); - messages.add(res.message); - MessagesStorage.getInstance().putMessages(messages, true, true, false, 0); - - if (res instanceof TLRPC.TL_messages_statedMessage) { - MessagesController.getInstance().processNewDifferenceParams(-1, res.pts, res.message.date, res.pts_count); - } else if (res instanceof TLRPC.TL_messages_statedMessageLink) { - MessagesController.getInstance().processNewDifferenceParams(res.seq, res.pts, res.message.date, res.pts_count); - } + processUpdates((TLRPC.Updates) response, false); } }); } else { @@ -2150,57 +2103,15 @@ public class MessagesController implements NotificationCenter.NotificationCenter if (error != null) { return; } - final TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response; + final TLRPC.Updates updates = (TLRPC.Updates) response; + processUpdates(updates, false); if (user.id == UserConfig.getClientUserId()) { - res.chats = null; - } - MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true); - - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - putUsers(res.users, false); - putChats(res.chats, false); - if (user.id != UserConfig.getClientUserId()) { - final ArrayList messagesObj = new ArrayList<>(); - messagesObj.add(new MessageObject(res.message, users, true)); - TLRPC.Chat chat = res.chats.get(0); - updateInterfaceWithMessages(-chat.id, messagesObj); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_MEMBERS); + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + MessagesController.getInstance().deleteDialog(-chat_id, 0, false); } - boolean changed = false; - if (info != null) { - for (int a = 0; a < info.participants.size(); a++) { - TLRPC.TL_chatParticipant p = info.participants.get(a); - if (p.user_id == user.id) { - info.participants.remove(a); - changed = true; - break; - } - } - if (changed) { - MessagesStorage.getInstance().updateChatInfo(chat_id, info, true); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatInfoDidLoaded, info.chat_id, info); - } else { - MessagesStorage.getInstance().updateChatInfo(chat_id, user.id, true, 0, 0); - } - } else { - MessagesStorage.getInstance().updateChatInfo(chat_id, user.id, true, 0, 0); - } - } - }); - - if (user.id != UserConfig.getClientUserId()) { - final ArrayList messages = new ArrayList<>(); - messages.add(res.message); - MessagesStorage.getInstance().putMessages(messages, true, true, false, 0); - } - - if (res instanceof TLRPC.TL_messages_statedMessage) { - MessagesController.getInstance().processNewDifferenceParams(-1, res.pts, res.message.date, res.pts_count); - } else if (res instanceof TLRPC.TL_messages_statedMessageLink) { - MessagesController.getInstance().processNewDifferenceParams(res.seq, res.pts, res.message.date, res.pts_count); + }); } } }); @@ -2243,32 +2154,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter if (error != null) { return; } - final TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response; - MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true); - - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - putUsers(res.users, false); - putChats(res.chats, false); - final ArrayList messagesObj = new ArrayList<>(); - messagesObj.add(new MessageObject(res.message, users, true)); - TLRPC.Chat chat = res.chats.get(0); - updateInterfaceWithMessages(-chat.id, messagesObj); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_NAME); - } - }); - - final ArrayList messages = new ArrayList<>(); - messages.add(res.message); - MessagesStorage.getInstance().putMessages(messages, true, true, false, 0); - - if (res instanceof TLRPC.TL_messages_statedMessage) { - MessagesController.getInstance().processNewDifferenceParams(-1, res.pts, res.message.date, res.pts_count); - } else if (res instanceof TLRPC.TL_messages_statedMessageLink) { - MessagesController.getInstance().processNewDifferenceParams(res.seq, res.pts, res.message.date, res.pts_count); - } + processUpdates((TLRPC.Updates) response, false); } }); } else { @@ -2298,34 +2184,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter if (error != null) { return; } - final TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response; - MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true); - - final ArrayList messages = new ArrayList<>(); - messages.add(res.message); - ImageLoader.saveMessagesThumbs(messages); - - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - putUsers(res.users, false); - putChats(res.chats, false); - final ArrayList messagesObj = new ArrayList<>(); - messagesObj.add(new MessageObject(res.message, users, true)); - TLRPC.Chat chat = res.chats.get(0); - updateInterfaceWithMessages(-chat.id, messagesObj); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_AVATAR); - } - }); - - MessagesStorage.getInstance().putMessages(messages, true, true, false, 0); - - if (res instanceof TLRPC.TL_messages_statedMessage) { - MessagesController.getInstance().processNewDifferenceParams(-1, res.pts, res.message.date, res.pts_count); - } else if (res instanceof TLRPC.TL_messages_statedMessageLink) { - MessagesController.getInstance().processNewDifferenceParams(res.seq, res.pts, res.message.date, res.pts_count); - } + processUpdates((TLRPC.Updates) response, false); } }); } @@ -2617,6 +2476,9 @@ public class MessagesController implements NotificationCenter.NotificationCenter req.pts = MessagesStorage.lastPtsValue; req.date = MessagesStorage.lastDateValue; req.qts = MessagesStorage.lastQtsValue; + if (req.date == 0) { + req.date = ConnectionsManager.getInstance().getCurrentTime(); + } FileLog.e("tmessages", "start getDifference with date = " + MessagesStorage.lastDateValue + " pts = " + MessagesStorage.lastPtsValue + " seq = " + MessagesStorage.lastSeqValue); if (ConnectionsManager.getInstance().getConnectionState() == 0) { ConnectionsManager.getInstance().setConnectionState(3); @@ -2681,7 +2543,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter Integer oldId = entry.getKey(); SendMessagesHelper.getInstance().processSentMessage(oldId); Integer newId = entry.getValue(); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newId, null); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newId, null, false); } } }); @@ -2860,9 +2722,18 @@ public class MessagesController implements NotificationCenter.NotificationCenter TLRPC.User user = getUser(updates.user_id); TLRPC.User user2 = null; + if (user == null) { + user = MessagesStorage.getInstance().getUserSync(updates.user_id); + putUser(user, true); + } + boolean needFwdUser = false; if (updates.fwd_from_id != 0) { user2 = getUser(updates.fwd_from_id); + if (user2 == null) { + user2 = MessagesStorage.getInstance().getUserSync(updates.fwd_from_id); + putUser(user2, true); + } needFwdUser = true; } @@ -2870,7 +2741,12 @@ public class MessagesController implements NotificationCenter.NotificationCenter if (updates instanceof TLRPC.TL_updateShortMessage) { missingData = user == null || needFwdUser && user2 == null; } else { - missingData = getChat(updates.chat_id) == null || user == null || needFwdUser && user2 == null; + TLRPC.Chat chat = getChat(updates.chat_id); + if (chat == null) { + chat = MessagesStorage.getInstance().getChatSync(updates.chat_id); + putChat(chat, true); + } + missingData = chat == null || user == null || needFwdUser && user2 == null; } if (user != null && user.status != null && user.status.expires <= 0) { onlinePrivacy.put(user.id, ConnectionsManager.getInstance().getCurrentTime()); @@ -3036,7 +2912,9 @@ public class MessagesController implements NotificationCenter.NotificationCenter } if (processUpdate) { processUpdateArray(updates.updates, updates.users, updates.chats); - MessagesStorage.lastDateValue = updates.date; + if (updates.date != 0) { + MessagesStorage.lastDateValue = updates.date; + } if (updates.seq != 0) { MessagesStorage.lastSeqValue = updates.seq; } @@ -3113,6 +2991,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter long currentTime = System.currentTimeMillis(); final HashMap> messages = new HashMap<>(); + final HashMap webPages = new HashMap<>(); final ArrayList pushMessages = new ArrayList<>(); final ArrayList messagesArr = new ArrayList<>(); final HashMap markAsReadMessagesInbox = new HashMap<>(); @@ -3305,6 +3184,12 @@ public class MessagesController implements NotificationCenter.NotificationCenter } else if (update instanceof TLRPC.TL_updateActivation) { //DEPRECATED } else if (update instanceof TLRPC.TL_updateNewAuthorization) { + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + NotificationCenter.getInstance().postNotificationName(NotificationCenter.newSessionReceived); + } + }); TLRPC.TL_messageService newMessage = new TLRPC.TL_messageService(); newMessage.action = new TLRPC.TL_messageActionLoginUnknownLocation(); newMessage.action.title = update.device; @@ -3438,6 +3323,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter pushMessages.add(obj); } else if (update instanceof TLRPC.TL_updatePrivacy) { updatesOnMainThread.add(update); + } else if (update instanceof TLRPC.TL_updateWebPage) { + webPages.put(update.webpage.id, update.webpage); } } if (!messages.isEmpty()) { @@ -3612,6 +3499,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter MessagesStorage.getInstance().updateUsers(dbUsers, false, true, true); } + if (!webPages.isEmpty()) { + NotificationCenter.getInstance().postNotificationName(NotificationCenter.didReceivedWebpagesInUpdates, webPages); + } + if (!messages.isEmpty()) { for (HashMap.Entry> entry : messages.entrySet()) { Long key = entry.getKey(); @@ -3701,6 +3592,9 @@ public class MessagesController implements NotificationCenter.NotificationCenter } }); + if (!webPages.isEmpty()) { + MessagesStorage.getInstance().putWebPages(webPages); + } if (!markAsReadMessagesInbox.isEmpty() || !markAsReadMessagesOutbox.isEmpty() || !markAsReadEncrypted.isEmpty()) { if (!markAsReadMessagesInbox.isEmpty() || !markAsReadMessagesOutbox.isEmpty()) { MessagesStorage.getInstance().updateDialogsWithReadedMessages(markAsReadMessagesInbox, true); diff --git a/TMessagesProj/src/main/java/org/telegram/android/MessagesStorage.java b/TMessagesProj/src/main/java/org/telegram/android/MessagesStorage.java index 1f3962192..d2b7981df 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/MessagesStorage.java +++ b/TMessagesProj/src/main/java/org/telegram/android/MessagesStorage.java @@ -123,6 +123,7 @@ public class MessagesStorage { database.executeFast("CREATE TABLE web_recent_v3(id TEXT, type INTEGER, image_url TEXT, thumb_url TEXT, local_url TEXT, width INTEGER, height INTEGER, size INTEGER, date INTEGER, PRIMARY KEY (id, type));").stepThis().dispose(); database.executeFast("CREATE TABLE stickers(id INTEGER PRIMARY KEY, data BLOB, date INTEGER);").stepThis().dispose(); database.executeFast("CREATE TABLE hashtag_recent_v2(id TEXT PRIMARY KEY, date INTEGER);").stepThis().dispose(); + database.executeFast("CREATE TABLE webpage_pending(id INTEGER, mid INTEGER, PRIMARY KEY (id, mid));").stepThis().dispose(); database.executeFast("CREATE TABLE user_contacts_v6(uid INTEGER PRIMARY KEY, fname TEXT, sname TEXT)").stepThis().dispose(); database.executeFast("CREATE TABLE user_phones_v6(uid INTEGER, phone TEXT, sphone TEXT, deleted INTEGER, PRIMARY KEY (uid, phone))").stepThis().dispose(); @@ -163,7 +164,7 @@ public class MessagesStorage { database.executeFast("CREATE TABLE keyvalue(id TEXT PRIMARY KEY, value TEXT)").stepThis().dispose(); //version - database.executeFast("PRAGMA user_version = 15").stepThis().dispose(); + database.executeFast("PRAGMA user_version = 16").stepThis().dispose(); } else { try { SQLiteCursor cursor = database.queryFinalized("SELECT seq, pts, date, qts, lsv, sg, pbytes FROM params WHERE id = 1"); @@ -194,7 +195,7 @@ public class MessagesStorage { } } int version = database.executeInt("PRAGMA user_version"); - if (version < 15) { + if (version < 16) { updateDbToLastVersion(version); } } @@ -379,6 +380,11 @@ public class MessagesStorage { database.executeFast("PRAGMA user_version = 15").stepThis().dispose(); version = 15; } + if (version == 15 && version < 16) { + database.executeFast("CREATE TABLE IF NOT EXISTS webpage_pending(id INTEGER, mid INTEGER, PRIMARY KEY (id, mid));").stepThis().dispose(); + database.executeFast("PRAGMA user_version = 16").stepThis().dispose(); + version = 16; + } } catch (Exception e) { FileLog.e("tmessages", e); } @@ -2660,6 +2666,79 @@ public class MessagesStorage { return -1; } + public void putWebPages(final HashMap webPages) { + if (webPages == null || webPages.isEmpty()) { + return; + } + storageQueue.postRunnable(new Runnable() { + @Override + public void run() { + try { + String ids = TextUtils.join(",", webPages.keySet()); + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid FROM webpage_pending WHERE id IN (%s)", ids)); + ArrayList mids = new ArrayList<>(); + while (cursor.next()) { + mids.add(cursor.intValue(0)); + } + cursor.dispose(); + + if (mids.isEmpty()) { + return; + } + final ArrayList messages = new ArrayList<>(); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid, data FROM messages WHERE mid IN (%s)", TextUtils.join(",", mids))); + while (cursor.next()) { + int mid = cursor.intValue(0); + ByteBufferDesc data = buffersStorage.getFreeBuffer(cursor.byteArrayLength(1)); + if (data != null && cursor.byteBufferValue(1, data.buffer) != 0) { + TLRPC.Message message = (TLRPC.Message)TLClassStore.Instance().TLdeserialize(data, data.readInt32()); + if (message.media instanceof TLRPC.TL_messageMediaWebPage) { + message.id = mid; + message.media.webpage = webPages.get(message.media.webpage.id); + messages.add(message); + } + } + buffersStorage.reuseFreeBuffer(data); + } + cursor.dispose(); + + database.executeFast(String.format(Locale.US, "DELETE FROM webpage_pending WHERE id IN (%s)", ids)).stepThis().dispose(); + + if (messages.isEmpty()) { + return; + } + + database.beginTransaction(); + + SQLitePreparedStatement state = database.executeFast("UPDATE messages SET data = ? WHERE mid = ?"); + for (TLRPC.Message message : messages) { + ByteBufferDesc data = buffersStorage.getFreeBuffer(message.getObjectSize()); + message.serializeToStream(data); + + state.requery(); + state.bindByteBuffer(1, data.buffer); + state.bindInteger(2, message.id); + state.step(); + + buffersStorage.reuseFreeBuffer(data); + } + state.dispose(); + + database.commitTransaction(); + + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + NotificationCenter.getInstance().postNotificationName(NotificationCenter.didReceivedWebpages, messages); + } + }); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + }); + } + private void putMessagesInternal(final ArrayList messages, final boolean withTransaction, final boolean isBroadcast, final int downloadMask) { try { if (withTransaction) { @@ -2677,6 +2756,7 @@ public class MessagesStorage { SQLitePreparedStatement state2 = database.executeFast("REPLACE INTO media_v2 VALUES(?, ?, ?, ?, ?)"); SQLitePreparedStatement state3 = database.executeFast("REPLACE INTO randoms VALUES(?, ?)"); SQLitePreparedStatement state4 = database.executeFast("REPLACE INTO download_queue VALUES(?, ?, ?, ?)"); + SQLitePreparedStatement state5 = database.executeFast("REPLACE INTO webpage_pending VALUES(?, ?)"); for (TLRPC.Message message : messages) { long dialog_id = message.dialog_id; @@ -2810,15 +2890,23 @@ public class MessagesStorage { state2.bindByteBuffer(5, data.buffer); state2.step(); } + + if (message.media instanceof TLRPC.TL_messageMediaWebPage && message.media.webpage instanceof TLRPC.TL_webPagePending) { + state5.requery(); + state5.bindLong(1, message.media.webpage.id); + state5.bindInteger(2, message.id); + state5.step(); + } + buffersStorage.reuseFreeBuffer(data); - if (downloadMask != 0) { + if (message.date >= ConnectionsManager.getInstance().getCurrentTime() - 60 * 60 * 24 && downloadMask != 0) { if (message.media instanceof TLRPC.TL_messageMediaAudio || message.media instanceof TLRPC.TL_messageMediaPhoto || message.media instanceof TLRPC.TL_messageMediaVideo || message.media instanceof TLRPC.TL_messageMediaDocument) { int type = 0; long id = 0; TLObject object = null; if (message.media instanceof TLRPC.TL_messageMediaAudio) { - if ((downloadMask & MediaController.AUTODOWNLOAD_MASK_AUDIO) != 0) { + if ((downloadMask & MediaController.AUTODOWNLOAD_MASK_AUDIO) != 0 && message.media.audio.size < 1024 * 1024 * 5) { id = message.media.audio.id; type = MediaController.AUTODOWNLOAD_MASK_AUDIO; object = message.media.audio; @@ -2864,6 +2952,7 @@ public class MessagesStorage { state2.dispose(); state3.dispose(); state4.dispose(); + state5.dispose(); state = database.executeFast("REPLACE INTO dialogs(did, date, unread_count, last_mid) VALUES(?, ?, ?, ?)"); for (HashMap.Entry pair : messagesMap.entrySet()) { @@ -3543,11 +3632,19 @@ public class MessagesStorage { } private void fixUnsupportedMedia(TLRPC.Message message) { - if (message != null && message.media instanceof TLRPC.TL_messageMediaUnsupported && message.media.bytes != null) { + if (message == null) { + return; + } + boolean ok = false; + if (message.media instanceof TLRPC.TL_messageMediaUnsupported_old) { if (message.media.bytes.length == 0) { message.media.bytes = new byte[1]; message.media.bytes[0] = TLRPC.LAYER; } + } else if (message.media instanceof TLRPC.TL_messageMediaUnsupported) { + message.media = new TLRPC.TL_messageMediaUnsupported_old(); + message.media.bytes = new byte[1]; + message.media.bytes[0] = TLRPC.LAYER; } } @@ -3802,6 +3899,42 @@ public class MessagesStorage { }); } + public TLRPC.User getUserSync(final int user_id) { + final Semaphore semaphore = new Semaphore(0); + final TLRPC.User[] user = new TLRPC.User[1]; + MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() { + @Override + public void run() { + user[0] = getUser(user_id); + semaphore.release(); + } + }); + try { + semaphore.acquire(); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + return user[0]; + } + + public TLRPC.Chat getChatSync(final int user_id) { + final Semaphore semaphore = new Semaphore(0); + final TLRPC.Chat[] chat = new TLRPC.Chat[1]; + MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() { + @Override + public void run() { + chat[0] = getChat(user_id); + semaphore.release(); + } + }); + try { + semaphore.acquire(); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + return chat[0]; + } + public TLRPC.User getUser(final int user_id) { TLRPC.User user = null; try { diff --git a/TMessagesProj/src/main/java/org/telegram/android/NativeLoader.java b/TMessagesProj/src/main/java/org/telegram/android/NativeLoader.java index 17e55ea26..6eab0a11b 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/NativeLoader.java +++ b/TMessagesProj/src/main/java/org/telegram/android/NativeLoader.java @@ -23,7 +23,7 @@ import java.util.zip.ZipFile; public class NativeLoader { - private final static int LIB_VERSION = 6; + private final static int LIB_VERSION = 7; private final static String LIB_NAME = "tmessages." + LIB_VERSION; private final static String LIB_SO_NAME = "lib" + LIB_NAME + ".so"; private final static String LOCALE_LIB_SO_NAME = "lib" + LIB_NAME + "loc.so"; diff --git a/TMessagesProj/src/main/java/org/telegram/android/NotificationCenter.java b/TMessagesProj/src/main/java/org/telegram/android/NotificationCenter.java index b21a9fd2e..962de6977 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/NotificationCenter.java +++ b/TMessagesProj/src/main/java/org/telegram/android/NotificationCenter.java @@ -49,9 +49,13 @@ public class NotificationCenter { public static final int recentImagesDidLoaded = totalEvents++; public static final int replaceMessagesObjects = totalEvents++; public static final int didSetPasscode = totalEvents++; + public static final int didSetTwoStepPassword = totalEvents++; public static final int screenStateChanged = totalEvents++; public static final int appSwitchedToForeground = totalEvents++; public static final int didLoadedReplyMessages = totalEvents++; + public static final int newSessionReceived = totalEvents++; + public static final int didReceivedWebpages = totalEvents++; + public static final int didReceivedWebpagesInUpdates = totalEvents++; public static final int httpFileDidLoaded = totalEvents++; public static final int httpFileDidFailedLoad = totalEvents++; @@ -64,7 +68,6 @@ public class NotificationCenter { public static final int didReceiveSmsCode = totalEvents++; public static final int emojiDidLoaded = totalEvents++; public static final int appDidLogout = totalEvents++; - public static final int needPasswordEnter = totalEvents++; public static final int FileDidUpload = totalEvents++; public static final int FileDidFailUpload = totalEvents++; diff --git a/TMessagesProj/src/main/java/org/telegram/android/NotificationsController.java b/TMessagesProj/src/main/java/org/telegram/android/NotificationsController.java index 9395c0c4b..1f31a687b 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/NotificationsController.java +++ b/TMessagesProj/src/main/java/org/telegram/android/NotificationsController.java @@ -71,7 +71,7 @@ public class NotificationsController { private long lastSoundPlay; private MediaPlayer mediaPlayerIn; private MediaPlayer mediaPlayerOut; - private AudioManager audioManager; + protected AudioManager audioManager; private static volatile NotificationsController Instance = null; public static NotificationsController getInstance() { @@ -171,7 +171,7 @@ public class NotificationsController { msg = LocaleController.formatString("NotificationUnrecognizedDevice", R.string.NotificationUnrecognizedDevice, UserConfig.getCurrentUser().first_name, date, messageObject.messageOwner.action.title, messageObject.messageOwner.action.address); } } else { - if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty) { + if (messageObject.isMediaEmpty()) { if (!shortMessage) { if (messageObject.messageOwner.message != null && messageObject.messageOwner.message.length() != 0) { msg = LocaleController.formatString("NotificationMessageText", R.string.NotificationMessageText, ContactsController.formatName(user.first_name, user.last_name), messageObject.messageOwner.message); @@ -236,7 +236,7 @@ public class NotificationsController { msg = messageObject.messageText.toString(); } } else { - if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty) { + if (messageObject.isMediaEmpty()) { if (!shortMessage && messageObject.messageOwner.message != null && messageObject.messageOwner.message.length() != 0) { msg = LocaleController.formatString("NotificationMessageGroupText", R.string.NotificationMessageGroupText, ContactsController.formatName(user.first_name, user.last_name), chat.title, messageObject.messageOwner.message); } else { @@ -868,7 +868,7 @@ public class NotificationsController { AssetFileDescriptor assetFileDescriptor = ApplicationLoader.applicationContext.getResources().openRawResourceFd(R.raw.sound_in); if (assetFileDescriptor != null) { mediaPlayerIn = new MediaPlayer(); - mediaPlayerIn.setAudioStreamType(AudioManager.STREAM_NOTIFICATION); + mediaPlayerIn.setAudioStreamType(AudioManager.STREAM_SYSTEM); mediaPlayerIn.setDataSource(assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength()); mediaPlayerIn.setLooping(false); assetFileDescriptor.close(); @@ -938,7 +938,7 @@ public class NotificationsController { AssetFileDescriptor assetFileDescriptor = ApplicationLoader.applicationContext.getResources().openRawResourceFd(R.raw.sound_out); if (assetFileDescriptor != null) { mediaPlayerOut = new MediaPlayer(); - mediaPlayerOut.setAudioStreamType(AudioManager.STREAM_NOTIFICATION); + mediaPlayerOut.setAudioStreamType(AudioManager.STREAM_SYSTEM); mediaPlayerOut.setDataSource(assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength()); mediaPlayerOut.setLooping(false); assetFileDescriptor.close(); diff --git a/TMessagesProj/src/main/java/org/telegram/android/SecretChatHelper.java b/TMessagesProj/src/main/java/org/telegram/android/SecretChatHelper.java index e9d672fc0..6a34ea267 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/SecretChatHelper.java +++ b/TMessagesProj/src/main/java/org/telegram/android/SecretChatHelper.java @@ -119,7 +119,7 @@ public class SecretChatHelper { reqSend = new TLRPC.TL_decryptedMessageService(); } else { reqSend = new TLRPC.TL_decryptedMessageService_old(); - reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))]; + reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } @@ -224,7 +224,7 @@ public class SecretChatHelper { reqSend = new TLRPC.TL_decryptedMessageService(); } else { reqSend = new TLRPC.TL_decryptedMessageService_old(); - reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))]; + reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } @@ -252,7 +252,7 @@ public class SecretChatHelper { reqSend = new TLRPC.TL_decryptedMessageService(); } else { reqSend = new TLRPC.TL_decryptedMessageService_old(); - reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))]; + reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } @@ -283,7 +283,7 @@ public class SecretChatHelper { reqSend = new TLRPC.TL_decryptedMessageService(); } else { reqSend = new TLRPC.TL_decryptedMessageService_old(); - reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))]; + reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } @@ -312,7 +312,7 @@ public class SecretChatHelper { reqSend = new TLRPC.TL_decryptedMessageService(); } else { reqSend = new TLRPC.TL_decryptedMessageService_old(); - reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))]; + reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } @@ -343,7 +343,7 @@ public class SecretChatHelper { reqSend = new TLRPC.TL_decryptedMessageService(); } else { reqSend = new TLRPC.TL_decryptedMessageService_old(); - reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))]; + reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } @@ -375,7 +375,7 @@ public class SecretChatHelper { reqSend = new TLRPC.TL_decryptedMessageService(); } else { reqSend = new TLRPC.TL_decryptedMessageService_old(); - reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))]; + reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } @@ -406,7 +406,7 @@ public class SecretChatHelper { reqSend = new TLRPC.TL_decryptedMessageService(); } else { reqSend = new TLRPC.TL_decryptedMessageService_old(); - reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))]; + reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } @@ -436,7 +436,7 @@ public class SecretChatHelper { reqSend = new TLRPC.TL_decryptedMessageService(); } else { reqSend = new TLRPC.TL_decryptedMessageService_old(); - reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))]; + reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } @@ -464,7 +464,7 @@ public class SecretChatHelper { reqSend = new TLRPC.TL_decryptedMessageService(); } else { reqSend = new TLRPC.TL_decryptedMessageService_old(); - reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))]; + reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } @@ -500,7 +500,7 @@ public class SecretChatHelper { reqSend = new TLRPC.TL_decryptedMessageService(); } else { reqSend = new TLRPC.TL_decryptedMessageService_old(); - reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))]; + reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } @@ -659,7 +659,7 @@ public class SecretChatHelper { int myLayer = Math.max(17, AndroidUtilities.getMyLayerVersion(chat.layer)); layer.layer = Math.min(myLayer, AndroidUtilities.getPeerLayerVersion(chat.layer)); layer.message = req; - layer.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))]; + layer.random_bytes = new byte[15]; Utilities.random.nextBytes(layer.random_bytes); toEncryptObject = layer; @@ -795,7 +795,7 @@ public class SecretChatHelper { @Override public void run() { newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; - NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageReceivedByServer, newMsgObj.id, newMsgObj.id, newMsgObj); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageReceivedByServer, newMsgObj.id, newMsgObj.id, newMsgObj, false); SendMessagesHelper.getInstance().processSentMessage(newMsgObj.id); if (newMsgObj.media instanceof TLRPC.TL_messageMediaVideo) { SendMessagesHelper.getInstance().stopVideoService(attachPath); @@ -1104,10 +1104,7 @@ public class SecretChatHelper { } byte[] salt = new byte[256]; - for (int a = 0; a < 256; a++) { - salt[a] = (byte) (Utilities.random.nextDouble() * 256); - } - + Utilities.random.nextBytes(salt); BigInteger p = new BigInteger(1, MessagesStorage.secretPBytes); BigInteger g_b = BigInteger.valueOf(MessagesStorage.secretG); g_b = g_b.modPow(new BigInteger(1, salt), p); @@ -1409,9 +1406,7 @@ public class SecretChatHelper { return; } final byte[] salt = new byte[256]; - for (int a = 0; a < 256; a++) { - salt[a] = (byte) (Utilities.random.nextDouble() * 256); - } + Utilities.random.nextBytes(salt); BigInteger i_g_a = BigInteger.valueOf(MessagesStorage.secretG); i_g_a = i_g_a.modPow(new BigInteger(1, salt), new BigInteger(1, MessagesStorage.secretPBytes)); diff --git a/TMessagesProj/src/main/java/org/telegram/android/SendMessagesHelper.java b/TMessagesProj/src/main/java/org/telegram/android/SendMessagesHelper.java index 21639752d..35e6bedea 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/SendMessagesHelper.java +++ b/TMessagesProj/src/main/java/org/telegram/android/SendMessagesHelper.java @@ -447,7 +447,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter if (messageObject == null) { return; } - if (messageObject.messageOwner.media != null && !(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty)) { + if (messageObject.messageOwner.media != null && !(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty) && !(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage)) { if (messageObject.messageOwner.media.photo instanceof TLRPC.TL_photo) { sendMessage((TLRPC.TL_photo) messageObject.messageOwner.media.photo, null, null, did, messageObject.replyMessageObject); } else if (messageObject.messageOwner.media.audio instanceof TLRPC.TL_audio) { @@ -471,14 +471,18 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter sendMessage(messageObject, did); } } else if (messageObject.messageOwner.message != null) { - sendMessage(messageObject.messageOwner.message, did, messageObject.replyMessageObject); + TLRPC.WebPage webPage = null; + if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage) { + webPage = messageObject.messageOwner.media.webpage; + } + sendMessage(messageObject.messageOwner.message, did, messageObject.replyMessageObject, webPage, true); } else { sendMessage(messageObject, did); } } public void sendMessage(TLRPC.User user, long peer, MessageObject reply_to_msg) { - sendMessage(null, null, null, null, null, null, user, null, null, null, peer, false, null, reply_to_msg); + sendMessage(null, null, null, null, null, null, user, null, null, null, peer, false, null, reply_to_msg, null, true); } public void sendMessage(ArrayList messages, long peer) { @@ -567,67 +571,74 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter req.id = ids; final ArrayList newMsgObjArr = arr; + final HashMap messagesByRandomIdsFinal = messagesByRandomIds; ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { if (error == null) { - final TLRPC.messages_StatedMessages res = (TLRPC.messages_StatedMessages) response; - if (newMsgObjArr.size() != res.messages.size()) { - MessagesController.getInstance().getDifference(); - return; - } - if (res instanceof TLRPC.TL_messages_statedMessages) { - MessagesController.getInstance().processNewDifferenceParams(-1, res.pts, -1, res.pts_count); - } else if (res instanceof TLRPC.TL_messages_statedMessagesLinks) { - MessagesController.getInstance().processNewDifferenceParams(res.seq, res.pts, -1, res.pts_count); - } - for (int a = 0; a < res.messages.size(); a++) { - TLRPC.Message message = res.messages.get(a); - final TLRPC.Message newMsgObj = newMsgObjArr.get(a); - if (newMsgObj == null) { - continue; + HashMap newMessagesByIds = new HashMap<>(); + TLRPC.Updates updates = (TLRPC.Updates) response; + for (int a = 0; a < updates.updates.size(); a++) { + TLRPC.Update update = updates.updates.get(a); + if (update instanceof TLRPC.TL_updateMessageID) { + newMessagesByIds.put(update.id, update.random_id); + updates.updates.remove(a); + a--; } - final int oldId = newMsgObj.id; - final ArrayList sentMessages = new ArrayList<>(); - sentMessages.add(message); - newMsgObj.id = message.id; - processSentMessage(newMsgObj, message, null); - MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() { - @Override - public void run() { - MessagesStorage.getInstance().updateMessageStateAndId(newMsgObj.random_id, oldId, newMsgObj.id, 0, false); - MessagesStorage.getInstance().putMessages(sentMessages, true, false, false, 0); - AndroidUtilities.runOnUIThread(new Runnable() { + } + for (TLRPC.Update update : updates.updates) { + if (update instanceof TLRPC.TL_updateNewMessage) { + MessagesController.getInstance().processNewDifferenceParams(-1, update.pts, -1, update.pts_count); + TLRPC.Message message = ((TLRPC.TL_updateNewMessage) update).message; + Long random_id = newMessagesByIds.get(message.id); + if (random_id != null) { + final TLRPC.Message newMsgObj = messagesByRandomIdsFinal.get(random_id); + if (newMsgObj == null) { + continue; + } + newMsgObjArr.remove(newMsgObj); + final int oldId = newMsgObj.id; + final ArrayList sentMessages = new ArrayList<>(); + sentMessages.add(message); + newMsgObj.id = message.id; + processSentMessage(newMsgObj, message, null); + MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() { @Override public void run() { - newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; - NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newMsgObj.id, newMsgObj); - processSentMessage(oldId); - removeFromSendingMessages(oldId); + MessagesStorage.getInstance().updateMessageStateAndId(newMsgObj.random_id, oldId, newMsgObj.id, 0, false); + MessagesStorage.getInstance().putMessages(sentMessages, true, false, false, 0); + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; + NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newMsgObj.id, newMsgObj, false); + processSentMessage(oldId); + removeFromSendingMessages(oldId); + } + }); + if (newMsgObj.media instanceof TLRPC.TL_messageMediaVideo) { + stopVideoService(newMsgObj.attachPath); + } } }); - if (newMsgObj.media instanceof TLRPC.TL_messageMediaVideo) { - stopVideoService(newMsgObj.attachPath); - } } - }); + } } - } else { - for (final TLRPC.Message newMsgObj : newMsgObjArr) { - MessagesStorage.getInstance().markMessageAsSendError(newMsgObj.id); - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR; - NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageSendError, newMsgObj.id); - processSentMessage(newMsgObj.id); - if (newMsgObj.media instanceof TLRPC.TL_messageMediaVideo) { - stopVideoService(newMsgObj.attachPath); - } - removeFromSendingMessages(newMsgObj.id); + } + for (final TLRPC.Message newMsgObj : newMsgObjArr) { + MessagesStorage.getInstance().markMessageAsSendError(newMsgObj.id); + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR; + NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageSendError, newMsgObj.id); + processSentMessage(newMsgObj.id); + if (newMsgObj.media instanceof TLRPC.TL_messageMediaVideo) { + stopVideoService(newMsgObj.attachPath); } - }); - } + removeFromSendingMessages(newMsgObj.id); + } + }); } } }, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassCanCompress, ConnectionsManager.DEFAULT_DATACENTER_ID); @@ -644,38 +655,38 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter } public void sendMessage(MessageObject message) { - sendMessage(null, null, null, null, null, message, null, null, null, null, message.getDialogId(), true, message.messageOwner.attachPath, null); + sendMessage(null, null, null, null, null, message, null, null, null, null, message.getDialogId(), true, message.messageOwner.attachPath, null, null, true); } public void sendMessage(MessageObject message, long peer) { - sendMessage(null, null, null, null, null, message, null, null, null, null, peer, false, message.messageOwner.attachPath, null); + sendMessage(null, null, null, null, null, message, null, null, null, null, peer, false, message.messageOwner.attachPath, null, null, true); } public void sendMessage(TLRPC.TL_document document, String originalPath, String path, long peer, MessageObject reply_to_msg) { - sendMessage(null, null, null, null, null, null, null, document, null, originalPath, peer, false, path, reply_to_msg); + sendMessage(null, null, null, null, null, null, null, document, null, originalPath, peer, false, path, reply_to_msg, null, true); } - public void sendMessage(String message, long peer, MessageObject reply_to_msg) { - sendMessage(message, null, null, null, null, null, null, null, null, null, peer, false, null, reply_to_msg); + public void sendMessage(String message, long peer, MessageObject reply_to_msg, TLRPC.WebPage webPage, boolean searchLinks) { + sendMessage(message, null, null, null, null, null, null, null, null, null, peer, false, null, reply_to_msg, webPage, searchLinks); } public void sendMessage(double lat, double lon, long peer, MessageObject reply_to_msg) { - sendMessage(null, lat, lon, null, null, null, null, null, null, null, peer, false, null, reply_to_msg); + sendMessage(null, lat, lon, null, null, null, null, null, null, null, peer, false, null, reply_to_msg, null, true); } public void sendMessage(TLRPC.TL_photo photo, String originalPath, String path, long peer, MessageObject reply_to_msg) { - sendMessage(null, null, null, photo, null, null, null, null, null, originalPath, peer, false, path, reply_to_msg); + sendMessage(null, null, null, photo, null, null, null, null, null, originalPath, peer, false, path, reply_to_msg, null, true); } public void sendMessage(TLRPC.TL_video video, String originalPath, String path, long peer, MessageObject reply_to_msg) { - sendMessage(null, null, null, null, video, null, null, null, null, originalPath, peer, false, path, reply_to_msg); + sendMessage(null, null, null, null, video, null, null, null, null, originalPath, peer, false, path, reply_to_msg, null, true); } public void sendMessage(TLRPC.TL_audio audio, String path, long peer, MessageObject reply_to_msg) { - sendMessage(null, null, null, null, null, null, null, null, audio, null, peer, false, path, reply_to_msg); + sendMessage(null, null, null, null, null, null, null, null, audio, null, peer, false, path, reply_to_msg, null, true); } - private void sendMessage(String message, Double lat, Double lon, TLRPC.TL_photo photo, TLRPC.TL_video video, MessageObject msgObj, TLRPC.User user, TLRPC.TL_document document, TLRPC.TL_audio audio, String originalPath, long peer, boolean retry, String path, MessageObject reply_to_msg) { + private void sendMessage(String message, Double lat, Double lon, TLRPC.TL_photo photo, TLRPC.TL_video video, MessageObject msgObj, TLRPC.User user, TLRPC.TL_document document, TLRPC.TL_audio audio, String originalPath, long peer, boolean retry, String path, MessageObject reply_to_msg, TLRPC.WebPage webPage, boolean searchLinks) { if (peer == 0) { return; } @@ -741,7 +752,12 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter } else { newMsg = new TLRPC.TL_message(); } - newMsg.media = new TLRPC.TL_messageMediaEmpty(); + if (encryptedChat != null || webPage == null) { + newMsg.media = new TLRPC.TL_messageMediaEmpty(); + } else { + newMsg.media = new TLRPC.TL_messageMediaWebPage(); + newMsg.media.webpage = webPage; + } type = 0; newMsg.message = message; } else if (lat != null && lon != null) { @@ -860,6 +876,8 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter if (lower_id != 0) { if (high_id == 1) { if (currentChatInfo == null) { + MessagesStorage.getInstance().markMessageAsSendError(newMsg.id); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageSendError, newMsg.id); processSentMessage(newMsg.id); return; } @@ -932,9 +950,14 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter if (encryptedChat == null) { if (sendToPeers != null) { TLRPC.TL_messages_sendBroadcast reqSend = new TLRPC.TL_messages_sendBroadcast(); + ArrayList random_ids = new ArrayList<>(); + for (int a = 0; a < sendToPeers.size(); a++) { + random_ids.add(Utilities.random.nextLong()); + } reqSend.message = message; reqSend.contacts = sendToPeers; reqSend.media = new TLRPC.TL_inputMediaEmpty(); + reqSend.random_id = random_ids; performSendMessageRequest(reqSend, newMsgObj.messageOwner, null); } else { TLRPC.TL_messages_sendMessage reqSend = new TLRPC.TL_messages_sendMessage(); @@ -942,8 +965,12 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter reqSend.peer = sendToPeer; reqSend.random_id = newMsg.random_id; if (reply_to_msg != null) { + reqSend.flags |= 1; reqSend.reply_to_msg_id = reply_to_msg.getId(); } + if (!searchLinks) { + reqSend.flags |= 2; + } performSendMessageRequest(reqSend, newMsgObj.messageOwner, null); } } else { @@ -953,7 +980,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter reqSend.ttl = newMsg.ttl; } else { reqSend = new TLRPC.TL_decryptedMessage_old(); - reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))]; + reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } reqSend.random_id = newMsg.random_id; @@ -1065,8 +1092,13 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter if (sendToPeers != null) { TLRPC.TL_messages_sendBroadcast request = new TLRPC.TL_messages_sendBroadcast(); + ArrayList random_ids = new ArrayList<>(); + for (int a = 0; a < sendToPeers.size(); a++) { + random_ids.add(Utilities.random.nextLong()); + } request.contacts = sendToPeers; request.media = inputMedia; + request.random_id = random_ids; request.message = ""; if (delayedMessage != null) { delayedMessage.sendRequest = request; @@ -1078,6 +1110,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter request.random_id = newMsg.random_id; request.media = inputMedia; if (reply_to_msg != null) { + request.flags |= 1; request.reply_to_msg_id = reply_to_msg.getId(); } if (delayedMessage != null) { @@ -1121,7 +1154,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter reqSend.ttl = newMsg.ttl; } else { reqSend = new TLRPC.TL_decryptedMessage_old(); - reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))]; + reqSend.random_bytes = new byte[15]; Utilities.random.nextBytes(reqSend.random_bytes); } reqSend.random_id = newMsg.random_id; @@ -1424,82 +1457,82 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { + boolean isSentError = false; if (error == null) { final int oldId = newMsgObj.id; final boolean isBroadcast = req instanceof TLRPC.TL_messages_sendBroadcast; final ArrayList sentMessages = new ArrayList<>(); final String attachPath = newMsgObj.attachPath; - + final boolean mediaUpdated = response instanceof TLRPC.messages_SentMessage && !(((TLRPC.messages_SentMessage) response).media instanceof TLRPC.TL_messageMediaEmpty); if (response instanceof TLRPC.messages_SentMessage) { TLRPC.messages_SentMessage res = (TLRPC.messages_SentMessage) response; - newMsgObj.id = res.id; + newMsgObj.local_id = newMsgObj.id = res.id; newMsgObj.date = res.date; + newMsgObj.media = res.media; if (res instanceof TLRPC.TL_messages_sentMessage) { MessagesController.getInstance().processNewDifferenceParams(-1, res.pts, res.date, res.pts_count); } else if (res instanceof TLRPC.TL_messages_sentMessageLink) { MessagesController.getInstance().processNewDifferenceParams(res.seq, res.pts, res.date, res.pts_count); } - } else if (response instanceof TLRPC.messages_StatedMessage) { - TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response; - sentMessages.add(res.message); - newMsgObj.id = res.message.id; - processSentMessage(newMsgObj, res.message, originalPath); - if (res instanceof TLRPC.TL_messages_statedMessage) { - MessagesController.getInstance().processNewDifferenceParams(-1, res.pts, res.message.date, res.pts_count); - } else if (res instanceof TLRPC.TL_messages_statedMessageLink) { - MessagesController.getInstance().processNewDifferenceParams(res.seq, res.pts, res.message.date, res.pts_count); - } - } else if (response instanceof TLRPC.messages_StatedMessages) { - TLRPC.messages_StatedMessages res = (TLRPC.messages_StatedMessages) response; - if (!res.messages.isEmpty()) { - sentMessages.addAll(res.messages); - TLRPC.Message message = res.messages.get(0); - if (!isBroadcast) { - newMsgObj.id = message.id; + sentMessages.add(newMsgObj); + } else if (response instanceof TLRPC.Updates) { + TLRPC.TL_updateNewMessage newMessage = null; + for (TLRPC.Update update : ((TLRPC.Updates) response).updates) { + if (update instanceof TLRPC.TL_updateNewMessage) { + newMessage = (TLRPC.TL_updateNewMessage) update; + break; } - processSentMessage(newMsgObj, message, originalPath); } - if (res instanceof TLRPC.TL_messages_statedMessages) { - MessagesController.getInstance().processNewDifferenceParams(-1, res.pts, -1, res.pts_count); - } else if (res instanceof TLRPC.TL_messages_statedMessagesLinks) { - MessagesController.getInstance().processNewDifferenceParams(res.seq, res.pts, -1, res.pts_count); + if (newMessage != null) { + sentMessages.add(newMessage.message); + newMsgObj.id = newMessage.message.id; + processSentMessage(newMsgObj, newMessage.message, originalPath); + MessagesController.getInstance().processNewDifferenceParams(-1, newMessage.pts, -1, newMessage.pts_count); + } else { + isSentError = true; } } - MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() { - @Override - public void run() { - MessagesStorage.getInstance().updateMessageStateAndId(newMsgObj.random_id, oldId, (isBroadcast ? oldId : newMsgObj.id), 0, false); - MessagesStorage.getInstance().putMessages(sentMessages, true, false, isBroadcast, 0); - if (isBroadcast) { - ArrayList currentMessage = new ArrayList<>(); - currentMessage.add(newMsgObj); - newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; - MessagesStorage.getInstance().putMessages(currentMessage, true, false, false, 0); - } - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { + + if (!isSentError) { + MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() { + @Override + public void run() { + MessagesStorage.getInstance().updateMessageStateAndId(newMsgObj.random_id, oldId, (isBroadcast ? oldId : newMsgObj.id), 0, false); + MessagesStorage.getInstance().putMessages(sentMessages, true, false, isBroadcast, 0); + if (isBroadcast) { + ArrayList currentMessage = new ArrayList<>(); + currentMessage.add(newMsgObj); newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; - if (isBroadcast) { - for (TLRPC.Message message : sentMessages) { - ArrayList arr = new ArrayList<>(); - MessageObject messageObject = new MessageObject(message, null, false); - arr.add(messageObject); - MessagesController.getInstance().updateInterfaceWithMessages(messageObject.getDialogId(), arr, isBroadcast); - } - NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); - } - NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, (isBroadcast ? oldId : newMsgObj.id), newMsgObj); - processSentMessage(oldId); - removeFromSendingMessages(oldId); + MessagesStorage.getInstance().putMessages(currentMessage, true, false, false, 0); + } + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; + if (isBroadcast) { + for (TLRPC.Message message : sentMessages) { + ArrayList arr = new ArrayList<>(); + MessageObject messageObject = new MessageObject(message, null, false); + arr.add(messageObject); + MessagesController.getInstance().updateInterfaceWithMessages(messageObject.getDialogId(), arr, isBroadcast); + } + NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); + } + NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, (isBroadcast ? oldId : newMsgObj.id), newMsgObj, mediaUpdated); + processSentMessage(oldId); + removeFromSendingMessages(oldId); + } + }); + if (newMsgObj.media instanceof TLRPC.TL_messageMediaVideo) { + stopVideoService(attachPath); } - }); - if (newMsgObj.media instanceof TLRPC.TL_messageMediaVideo) { - stopVideoService(attachPath); } - } - }); + }); + } } else { + isSentError = true; + } + if (isSentError) { MessagesStorage.getInstance().markMessageAsSendError(newMsgObj.id); AndroidUtilities.runOnUIThread(new Runnable() { @Override diff --git a/TMessagesProj/src/main/java/org/telegram/android/WearReplyReceiver.java b/TMessagesProj/src/main/java/org/telegram/android/WearReplyReceiver.java index e94dc43c2..dfde54421 100644 --- a/TMessagesProj/src/main/java/org/telegram/android/WearReplyReceiver.java +++ b/TMessagesProj/src/main/java/org/telegram/android/WearReplyReceiver.java @@ -31,7 +31,7 @@ public class WearReplyReceiver extends BroadcastReceiver { if (dialog_id == 0 || max_id == 0) { return; } - SendMessagesHelper.getInstance().sendMessage(text.toString(), dialog_id, null); + SendMessagesHelper.getInstance().sendMessage(text.toString(), dialog_id, null, null, true); MessagesController.getInstance().markDialogAsRead(dialog_id, max_id, max_id, 0, 0, true, false); } } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/ConnectionsManager.java b/TMessagesProj/src/main/java/org/telegram/messenger/ConnectionsManager.java index 0149b8340..3d8fa2a10 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/ConnectionsManager.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/ConnectionsManager.java @@ -1037,11 +1037,6 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection. for (int i = 0; i < runningRequests.size(); i++) { RPCRequest request = runningRequests.get(i); - if (UserConfig.waitingForPasswordEnter && (request.flags & RPCRequest.RPCRequestClassWithoutLogin) == 0) { - FileLog.e("tmessages", "skip request " + request.rawRequest + ", need password enter"); - continue; - } - int datacenterId = request.runningDatacenterId; if (datacenterId == DEFAULT_DATACENTER_ID) { if (movingToDatacenterId != DEFAULT_DATACENTER_ID) { @@ -1244,11 +1239,6 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection. continue; } - if (UserConfig.waitingForPasswordEnter && (request.flags & RPCRequest.RPCRequestClassWithoutLogin) == 0) { - FileLog.e("tmessages", "skip request " + request.rawRequest + ", need password enter"); - continue; - } - int datacenterId = request.runningDatacenterId; if (datacenterId == DEFAULT_DATACENTER_ID) { if (movingToDatacenterId != DEFAULT_DATACENTER_ID && (request.flags & RPCRequest.RPCRequestClassEnableUnauthorized) == 0) { @@ -2183,10 +2173,6 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection. } }); } - if (request.rawRequest instanceof TLRPC.TL_auth_checkPassword) { - UserConfig.setWaitingForPasswordEnter(false); - UserConfig.saveConfig(false); - } request.completionBlock.run(resultContainer.result, null); } } @@ -2194,7 +2180,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection. if (implicitError != null && implicitError.code == 401) { isError = true; if (implicitError.text != null && implicitError.text.contains("SESSION_PASSWORD_NEEDED")) { - UserConfig.setWaitingForPasswordEnter(true); + /*UserConfig.setWaitingForPasswordEnter(true); TODO UserConfig.saveConfig(false); if (UserConfig.isClientActivated()) { discardResponse = true; @@ -2204,7 +2190,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection. NotificationCenter.getInstance().postNotificationName(NotificationCenter.needPasswordEnter); } }); - } + }*/ } else if (datacenter.datacenterId == currentDatacenterId || datacenter.datacenterId == movingToDatacenterId) { if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0 && UserConfig.isClientActivated()) { UserConfig.clearConfig(); diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/RPCRequest.java b/TMessagesProj/src/main/java/org/telegram/messenger/RPCRequest.java index 4e7454e07..180c9446b 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/RPCRequest.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/RPCRequest.java @@ -63,7 +63,7 @@ public class RPCRequest { boolean initRequest = false; - ArrayList respondsToMessageIds = new ArrayList(); + ArrayList respondsToMessageIds = new ArrayList<>(); public void addRespondMessageId(long messageId) { respondsToMessageIds.add(messageId); diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/TLClassStore.java b/TMessagesProj/src/main/java/org/telegram/messenger/TLClassStore.java index 016c62fe3..c3e862ad6 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/TLClassStore.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/TLClassStore.java @@ -124,8 +124,6 @@ public class TLClassStore { classStore.put(TLRPC.TL_boolTrue.constructor, TLRPC.TL_boolTrue.class); classStore.put(TLRPC.TL_boolFalse.constructor, TLRPC.TL_boolFalse.class); classStore.put(TLRPC.TL_auth_exportedAuthorization.constructor, TLRPC.TL_auth_exportedAuthorization.class); - classStore.put(TLRPC.TL_messages_statedMessagesLinks.constructor, TLRPC.TL_messages_statedMessagesLinks.class); - classStore.put(TLRPC.TL_messages_statedMessages.constructor, TLRPC.TL_messages_statedMessages.class); classStore.put(TLRPC.TL_inputNotifyChats.constructor, TLRPC.TL_inputNotifyChats.class); classStore.put(TLRPC.TL_inputNotifyPeer.constructor, TLRPC.TL_inputNotifyPeer.class); classStore.put(TLRPC.TL_inputNotifyUsers.constructor, TLRPC.TL_inputNotifyUsers.class); @@ -322,8 +320,6 @@ public class TLClassStore { classStore.put(TLRPC.TL_contactFound.constructor, TLRPC.TL_contactFound.class); classStore.put(TLRPC.TL_inputFileBig.constructor, TLRPC.TL_inputFileBig.class); classStore.put(TLRPC.TL_inputFile.constructor, TLRPC.TL_inputFile.class); - classStore.put(TLRPC.TL_messages_statedMessageLink.constructor, TLRPC.TL_messages_statedMessageLink.class); - classStore.put(TLRPC.TL_messages_statedMessage.constructor, TLRPC.TL_messages_statedMessage.class); classStore.put(TLRPC.TL_userFull.constructor, TLRPC.TL_userFull.class); classStore.put(TLRPC.TL_updates_state.constructor, TLRPC.TL_updates_state.class); classStore.put(TLRPC.TL_resPQ.constructor, TLRPC.TL_resPQ.class); @@ -377,6 +373,17 @@ public class TLClassStore { classStore.put(TLRPC.TL_contactLinkHasPhone.constructor, TLRPC.TL_contactLinkHasPhone.class); classStore.put(TLRPC.TL_contactLinkContact.constructor, TLRPC.TL_contactLinkContact.class); classStore.put(TLRPC.TL_messages_affectedMessages.constructor, TLRPC.TL_messages_affectedMessages.class); + classStore.put(TLRPC.TL_updateWebPage.constructor, TLRPC.TL_updateWebPage.class); + classStore.put(TLRPC.TL_webPagePending.constructor, TLRPC.TL_webPagePending.class); + classStore.put(TLRPC.TL_webPageEmpty.constructor, TLRPC.TL_webPageEmpty.class); + classStore.put(TLRPC.TL_webPage.constructor, TLRPC.TL_webPage.class); + classStore.put(TLRPC.TL_messageMediaWebPage.constructor, TLRPC.TL_messageMediaWebPage.class); + classStore.put(TLRPC.TL_authorization.constructor, TLRPC.TL_authorization.class); + classStore.put(TLRPC.TL_account_authorizations.constructor, TLRPC.TL_account_authorizations.class); + classStore.put(TLRPC.TL_account_passwordSettings.constructor, TLRPC.TL_account_passwordSettings.class); + classStore.put(TLRPC.TL_account_passwordInputSettings.constructor, TLRPC.TL_account_passwordInputSettings.class); + classStore.put(TLRPC.TL_auth_passwordRecovery.constructor, TLRPC.TL_auth_passwordRecovery.class); + classStore.put(TLRPC.TL_messages_getWebPagePreview.constructor, TLRPC.TL_messages_getWebPagePreview.class); classStore.put(TLRPC.TL_messageMediaUnsupported_old.constructor, TLRPC.TL_messageMediaUnsupported_old.class); classStore.put(TLRPC.TL_userSelf_old2.constructor, TLRPC.TL_userSelf_old2.class); diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/TLRPC.java b/TMessagesProj/src/main/java/org/telegram/messenger/TLRPC.java index cd766543f..0789e6cbe 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/TLRPC.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/TLRPC.java @@ -19,7 +19,7 @@ public class TLRPC { public static final int MESSAGE_FLAG_FWD = 4; public static final int MESSAGE_FLAG_REPLY = 8; public static final int MESSAGE_FLAG_MENTION = 16; - public static final int LAYER = 25; + public static final int LAYER = 27; public static class ChatPhoto extends TLObject { public FileLocation photo_small; @@ -272,6 +272,21 @@ public class TLRPC { } } + public static class TL_account_passwordSettings extends TLObject { + public static int constructor = 0xb7b72ab3; + + public String email; + + public void readParams(AbsSerializedData stream) { + email = stream.readString(); + } + + public void serializeToStream(AbsSerializedData stream) { + stream.writeInt32(constructor); + stream.writeString(email); + } + } + public static class DocumentAttribute extends TLObject { public int duration; public String file_name; @@ -653,6 +668,57 @@ public class TLRPC { } } + public static class TL_authorization extends TLObject { + public static int constructor = 0x7bf2e6f6; + + public long hash; + public int flags; + public String device_model; + public String platform; + public String system_version; + public int api_id; + public String app_name; + public String app_version; + public int date_created; + public int date_active; + public String ip; + public String country; + public String region; + + public void readParams(AbsSerializedData stream) { + hash = stream.readInt64(); + flags = stream.readInt32(); + device_model = stream.readString(); + platform = stream.readString(); + system_version = stream.readString(); + api_id = stream.readInt32(); + app_name = stream.readString(); + app_version = stream.readString(); + date_created = stream.readInt32(); + date_active = stream.readInt32(); + ip = stream.readString(); + country = stream.readString(); + region = stream.readString(); + } + + public void serializeToStream(AbsSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(hash); + stream.writeInt32(flags); + stream.writeString(device_model); + stream.writeString(platform); + stream.writeString(system_version); + stream.writeInt32(api_id); + stream.writeString(app_name); + stream.writeString(app_version); + stream.writeInt32(date_created); + stream.writeInt32(date_active); + stream.writeString(ip); + stream.writeString(country); + stream.writeString(region); + } + } + public static class DestroySessionRes extends TLObject { public long session_id; } @@ -1114,6 +1180,7 @@ public class TLRPC { public static class MessageMedia extends TLObject { public Video video; public Photo photo; + public WebPage webpage; public Document document; public GeoPoint geo; public Audio audio; @@ -1152,6 +1219,20 @@ public class TLRPC { } } + public static class TL_messageMediaWebPage extends MessageMedia { + public static int constructor = 0xa32dd600; + + + public void readParams(AbsSerializedData stream) { + webpage = (WebPage)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32()); + } + + public void serializeToStream(AbsSerializedData stream) { + stream.writeInt32(constructor); + webpage.serializeToStream(stream); + } + } + public static class TL_messageMediaDocument extends MessageMedia { public static int constructor = 0x2fda2204; @@ -2035,124 +2116,144 @@ public class TLRPC { } } - public static class messages_StatedMessages extends TLObject { - public ArrayList messages = new ArrayList<>(); - public ArrayList chats = new ArrayList<>(); - public ArrayList users = new ArrayList<>(); - public int pts; - public int pts_count; - public ArrayList links = new ArrayList<>(); - public int seq; + public static class WebPage extends TLObject { + public long id; + public int date; + public int flags; + public String url; + public String display_url; + public String type; + public String site_name; + public String title; + public String description; + public Photo photo; + public String embed_url; + public String embed_type; + public int embed_width; + public int embed_height; + public int duration; + public String author; } - public static class TL_messages_statedMessagesLinks extends messages_StatedMessages { - public static int constructor = 0x51be5d19; + public static class TL_webPagePending extends WebPage { + public static int constructor = 0xc586da1c; public void readParams(AbsSerializedData stream) { - stream.readInt32(); - int count = stream.readInt32(); - for (int a = 0; a < count; a++) { - messages.add((Message)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32())); - } - stream.readInt32(); - count = stream.readInt32(); - for (int a = 0; a < count; a++) { - chats.add((Chat)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32())); - } - stream.readInt32(); - count = stream.readInt32(); - for (int a = 0; a < count; a++) { - users.add((User)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32())); - } - pts = stream.readInt32(); - pts_count = stream.readInt32(); - stream.readInt32(); - count = stream.readInt32(); - for (int a = 0; a < count; a++) { - links.add((TL_contacts_link)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32())); - } - seq = stream.readInt32(); + id = stream.readInt64(); + date = stream.readInt32(); } public void serializeToStream(AbsSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(0x1cb5c415); - int count = messages.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - messages.get(a).serializeToStream(stream); - } - stream.writeInt32(0x1cb5c415); - count = chats.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - chats.get(a).serializeToStream(stream); - } - stream.writeInt32(0x1cb5c415); - count = users.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - users.get(a).serializeToStream(stream); - } - stream.writeInt32(pts); - stream.writeInt32(pts_count); - stream.writeInt32(0x1cb5c415); - count = links.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - links.get(a).serializeToStream(stream); - } - stream.writeInt32(seq); + stream.writeInt64(id); + stream.writeInt32(date); } } - public static class TL_messages_statedMessages extends messages_StatedMessages { - public static int constructor = 0x7d84b48; + public static class TL_webPageEmpty extends WebPage { + public static int constructor = 0xeb1477e8; public void readParams(AbsSerializedData stream) { - stream.readInt32(); - int count = stream.readInt32(); - for (int a = 0; a < count; a++) { - messages.add((Message)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32())); - } - stream.readInt32(); - count = stream.readInt32(); - for (int a = 0; a < count; a++) { - chats.add((Chat)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32())); - } - stream.readInt32(); - count = stream.readInt32(); - for (int a = 0; a < count; a++) { - users.add((User)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32())); - } - pts = stream.readInt32(); - pts_count = stream.readInt32(); + id = stream.readInt64(); } public void serializeToStream(AbsSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(0x1cb5c415); - int count = messages.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - messages.get(a).serializeToStream(stream); + stream.writeInt64(id); + } + } + + public static class TL_auth_passwordRecovery extends TLObject { + public static int constructor = 0x137948a5; + + public String email_pattern; + + public void readParams(AbsSerializedData stream) { + email_pattern = stream.readString(); + } + + public void serializeToStream(AbsSerializedData stream) { + stream.writeInt32(constructor); + stream.writeString(email_pattern); + } + } + + public static class TL_webPage extends WebPage { + public static int constructor = 0xa31ea0b5; + + public void readParams(AbsSerializedData stream) { + flags = stream.readInt32(); + id = stream.readInt64(); + url = stream.readString(); + display_url = stream.readString(); + if ((flags & 1) != 0) { + type = stream.readString(); } - stream.writeInt32(0x1cb5c415); - count = chats.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - chats.get(a).serializeToStream(stream); + if ((flags & 2) != 0) { + site_name = stream.readString(); } - stream.writeInt32(0x1cb5c415); - count = users.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - users.get(a).serializeToStream(stream); + if ((flags & 4) != 0) { + title = stream.readString(); + } + if ((flags & 8) != 0) { + description = stream.readString(); + } + if ((flags & 16) != 0) { + photo = (Photo) TLClassStore.Instance().TLdeserialize(stream, stream.readInt32()); + } + if ((flags & 32) != 0) { + embed_url = stream.readString(); + embed_type = stream.readString(); + } + if ((flags & 64) != 0) { + embed_width = stream.readInt32(); + embed_height = stream.readInt32(); + } + if ((flags & 128) != 0) { + duration = stream.readInt32(); + } + if ((flags & 256) != 0) { + author = stream.readString(); + } + } + + public void serializeToStream(AbsSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32(flags); + stream.writeInt64(id); + stream.writeString(url); + stream.writeString(display_url); + if ((flags & 1) != 0) { + stream.writeString(type); + } + if ((flags & 2) != 0) { + stream.writeString(site_name); + } + if ((flags & 4) != 0) { + stream.writeString(title); + } + if ((flags & 8) != 0) { + stream.writeString(description); + } + if ((flags & 16) != 0) { + photo.serializeToStream(stream); + } + if ((flags & 32) != 0) { + stream.writeString(embed_url); + stream.writeString(embed_type); + } + if ((flags & 64) != 0) { + stream.writeInt32(embed_width); + stream.writeInt32(embed_height); + } + if ((flags & 128) != 0) { + stream.writeInt32(duration); + } + if ((flags & 256) != 0) { + stream.writeString(author); } - stream.writeInt32(pts); - stream.writeInt32(pts_count); } } @@ -2317,7 +2418,7 @@ public class TLRPC { stream.readInt32(); int count = stream.readInt32(); for (int a = 0; a < count; a++) { - users.add((User)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32())); + users.add((User) TLClassStore.Instance().TLdeserialize(stream, stream.readInt32())); } } @@ -3536,6 +3637,7 @@ public class TLRPC { public static class messages_SentMessage extends TLObject { public int id; public int date; + public MessageMedia media; public int pts; public int pts_count; public ArrayList links = new ArrayList<>(); @@ -3543,12 +3645,13 @@ public class TLRPC { } public static class TL_messages_sentMessage extends messages_SentMessage { - public static int constructor = 0x900eac40; + public static int constructor = 0x4c3d47f3; public void readParams(AbsSerializedData stream) { id = stream.readInt32(); date = stream.readInt32(); + media = (MessageMedia)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32()); pts = stream.readInt32(); pts_count = stream.readInt32(); } @@ -3557,18 +3660,20 @@ public class TLRPC { stream.writeInt32(constructor); stream.writeInt32(id); stream.writeInt32(date); + media.serializeToStream(stream); stream.writeInt32(pts); stream.writeInt32(pts_count); } } public static class TL_messages_sentMessageLink extends messages_SentMessage { - public static int constructor = 0xe923400d; + public static int constructor = 0x35a1a663; public void readParams(AbsSerializedData stream) { id = stream.readInt32(); date = stream.readInt32(); + media = (MessageMedia)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32()); pts = stream.readInt32(); pts_count = stream.readInt32(); stream.readInt32(); @@ -3583,6 +3688,7 @@ public class TLRPC { stream.writeInt32(constructor); stream.writeInt32(id); stream.writeInt32(date); + media.serializeToStream(stream); stream.writeInt32(pts); stream.writeInt32(pts_count); stream.writeInt32(0x1cb5c415); @@ -3820,6 +3926,7 @@ public class TLRPC { public int pts_count; public int max_id; public int version; + public WebPage webpage; public String type; public MessageMedia media; public boolean popup; @@ -3971,6 +4078,20 @@ public class TLRPC { } } + public static class TL_updateWebPage extends Update { + public static int constructor = 0x2cc36971; + + + public void readParams(AbsSerializedData stream) { + webpage = (WebPage)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32()); + } + + public void serializeToStream(AbsSerializedData stream) { + stream.writeInt32(constructor); + webpage.serializeToStream(stream); + } + } + public static class TL_updateServiceNotification extends Update { public static int constructor = 0x382dd3e4; @@ -4765,16 +4886,20 @@ public class TLRPC { public byte[] current_salt; public byte[] new_salt; public String hint; + public boolean has_recovery; + public String email_unconfirmed_pattern; } public static class TL_account_password extends account_Password { - public static int constructor = 0x739e5f72; + public static int constructor = 0x7c18141c; public void readParams(AbsSerializedData stream) { current_salt = stream.readByteArray(); new_salt = stream.readByteArray(); hint = stream.readString(); + has_recovery = stream.readBool(); + email_unconfirmed_pattern = stream.readString(); } public void serializeToStream(AbsSerializedData stream) { @@ -4782,20 +4907,24 @@ public class TLRPC { stream.writeByteArray(current_salt); stream.writeByteArray(new_salt); stream.writeString(hint); + stream.writeBool(has_recovery); + stream.writeString(email_unconfirmed_pattern); } } public static class TL_account_noPassword extends account_Password { - public static int constructor = 0x5770e7a9; + public static int constructor = 0x96dabc18; public void readParams(AbsSerializedData stream) { new_salt = stream.readByteArray(); + email_unconfirmed_pattern = stream.readString(); } public void serializeToStream(AbsSerializedData stream) { stream.writeInt32(constructor); stream.writeByteArray(new_salt); + stream.writeString(email_unconfirmed_pattern); } } @@ -5055,7 +5184,7 @@ public class TLRPC { } public static class TL_config extends TLObject { - public static int constructor = 0x3e6f732a; + public static int constructor = 0x68bac247; public int date; public int expires; @@ -5064,6 +5193,7 @@ public class TLRPC { public ArrayList dc_options = new ArrayList<>(); public int chat_size_max; public int broadcast_size_max; + public int forwarded_count_max; public int online_update_period_ms; public int offline_blur_timeout_ms; public int offline_idle_timeout_ms; @@ -5085,6 +5215,7 @@ public class TLRPC { } chat_size_max = stream.readInt32(); broadcast_size_max = stream.readInt32(); + forwarded_count_max = stream.readInt32(); online_update_period_ms = stream.readInt32(); offline_blur_timeout_ms = stream.readInt32(); offline_idle_timeout_ms = stream.readInt32(); @@ -5113,6 +5244,7 @@ public class TLRPC { } stream.writeInt32(chat_size_max); stream.writeInt32(broadcast_size_max); + stream.writeInt32(forwarded_count_max); stream.writeInt32(online_update_period_ms); stream.writeInt32(offline_blur_timeout_ms); stream.writeInt32(offline_idle_timeout_ms); @@ -5315,7 +5447,7 @@ public class TLRPC { public String phone_number; - public Class responseClass () { + public Class responseClass() { return TL_account_sentChangePhoneCode.class; } @@ -5354,66 +5486,6 @@ public class TLRPC { } } - public static class TL_account_getPassword extends TLObject { - public static int constructor = 0x548a30f5; - - - public Class responseClass () { - return account_Password.class; - } - - public void serializeToStream(AbsSerializedData stream) { - stream.writeInt32(constructor); - } - } - - public static class TL_account_setPassword extends TLObject { - public static int constructor = 0xdd2a4d8f; - - public byte[] current_password_hash; - public byte[] new_salt; - public byte[] new_password_hash; - public String hint; - - public Class responseClass () { - return Bool.class; - } - - public void readParams(AbsSerializedData stream) { - current_password_hash = stream.readByteArray(); - new_salt = stream.readByteArray(); - new_password_hash = stream.readByteArray(); - hint = stream.readString(); - } - - public void serializeToStream(AbsSerializedData stream) { - stream.writeInt32(constructor); - stream.writeByteArray(current_password_hash); - stream.writeByteArray(new_salt); - stream.writeByteArray(new_password_hash); - stream.writeString(hint); - } - } - - public static class TL_auth_checkPassword extends TLObject { - public static int constructor = 0xa63011e; - - public byte[] password_hash; - - public Class responseClass () { - return TL_auth_authorization.class; - } - - public void readParams(AbsSerializedData stream) { - password_hash = stream.readByteArray(); - } - - public void serializeToStream(AbsSerializedData stream) { - stream.writeInt32(constructor); - stream.writeByteArray(password_hash); - } - } - public static class TL_account_updateDeviceLocked extends TLObject { public static int constructor = 0x38df3532; @@ -5433,6 +5505,38 @@ public class TLRPC { } } + public static class TL_account_getAuthorizations extends TLObject { + public static int constructor = 0xe320c158; + + + public Class responseClass () { + return TL_account_authorizations.class; + } + + public void serializeToStream(AbsSerializedData stream) { + stream.writeInt32(constructor); + } + } + + public static class TL_account_resetAuthorization extends TLObject { + public static int constructor = 0xdf77f3bc; + + public long hash; + + public Class responseClass () { + return Bool.class; + } + + public void readParams(AbsSerializedData stream) { + hash = stream.readInt64(); + } + + public void serializeToStream(AbsSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(hash); + } + } + public static class TL_messages_getAllStickers extends TLObject { public static int constructor = 0xaa3bc868; @@ -5452,6 +5556,25 @@ public class TLRPC { } } + public static class TL_messages_getWebPagePreview extends TLObject { + public static int constructor = 0x25223e24; + + public String message; + + public Class responseClass () { + return MessageMedia.class; + } + + public void readParams(AbsSerializedData stream) { + message = stream.readString(); + } + + public void serializeToStream(AbsSerializedData stream) { + stream.writeInt32(constructor); + stream.writeString(message); + } + } + public static class TL_account_checkUsername extends TLObject { public static int constructor = 0x2714d86c; @@ -6483,109 +6606,6 @@ public class TLRPC { } } - public static class messages_StatedMessage extends TLObject { - public Message message; - public ArrayList chats = new ArrayList<>(); - public ArrayList users = new ArrayList<>(); - public int pts; - public int pts_count; - public ArrayList links = new ArrayList<>(); - public int seq; - } - - public static class TL_messages_statedMessageLink extends messages_StatedMessage { - public static int constructor = 0x948a288; - - - public void readParams(AbsSerializedData stream) { - message = (Message)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32()); - stream.readInt32(); - int count = stream.readInt32(); - for (int a = 0; a < count; a++) { - chats.add((Chat)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32())); - } - stream.readInt32(); - count = stream.readInt32(); - for (int a = 0; a < count; a++) { - users.add((User)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32())); - } - pts = stream.readInt32(); - pts_count = stream.readInt32(); - stream.readInt32(); - count = stream.readInt32(); - for (int a = 0; a < count; a++) { - links.add((TL_contacts_link)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32())); - } - seq = stream.readInt32(); - } - - public void serializeToStream(AbsSerializedData stream) { - stream.writeInt32(constructor); - message.serializeToStream(stream); - stream.writeInt32(0x1cb5c415); - int count = chats.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - chats.get(a).serializeToStream(stream); - } - stream.writeInt32(0x1cb5c415); - count = users.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - users.get(a).serializeToStream(stream); - } - stream.writeInt32(pts); - stream.writeInt32(pts_count); - stream.writeInt32(0x1cb5c415); - count = links.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - links.get(a).serializeToStream(stream); - } - stream.writeInt32(seq); - } - } - - public static class TL_messages_statedMessage extends messages_StatedMessage { - public static int constructor = 0x96240c6a; - - - public void readParams(AbsSerializedData stream) { - message = (Message)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32()); - stream.readInt32(); - int count = stream.readInt32(); - for (int a = 0; a < count; a++) { - chats.add((Chat)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32())); - } - stream.readInt32(); - count = stream.readInt32(); - for (int a = 0; a < count; a++) { - users.add((User)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32())); - } - pts = stream.readInt32(); - pts_count = stream.readInt32(); - } - - public void serializeToStream(AbsSerializedData stream) { - stream.writeInt32(constructor); - message.serializeToStream(stream); - stream.writeInt32(0x1cb5c415); - int count = chats.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - chats.get(a).serializeToStream(stream); - } - stream.writeInt32(0x1cb5c415); - count = users.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - users.get(a).serializeToStream(stream); - } - stream.writeInt32(pts); - stream.writeInt32(pts_count); - } - } - public static class TL_userFull extends TLObject { public static int constructor = 0x771095da; @@ -7283,6 +7303,41 @@ public class TLRPC { } } + public static class TL_account_passwordInputSettings extends TLObject { + public static int constructor = 0xbcfc532c; + + public int flags; + public byte[] new_salt; + public byte[] new_password_hash; + public String hint; + public String email; + + public void readParams(AbsSerializedData stream) { + flags = stream.readInt32(); + if ((flags & 1) != 0) { + new_salt = stream.readByteArray(); + new_password_hash = stream.readByteArray(); + hint = stream.readString(); + } + if ((flags & 2) != 0) { + email = stream.readString(); + } + } + + public void serializeToStream(AbsSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32(flags); + if ((flags & 1) != 0) { + stream.writeByteArray(new_salt); + stream.writeByteArray(new_password_hash); + stream.writeString(hint); + } + if ((flags & 2) != 0) { + stream.writeString(email); + } + } + } + public static class TL_dcOption extends TLObject { public static int constructor = 0x2ec2a43c; @@ -7489,6 +7544,30 @@ public class TLRPC { } } + public static class TL_account_authorizations extends TLObject { + public static int constructor = 0x1250abde; + + public ArrayList authorizations = new ArrayList<>(); + + public void readParams(AbsSerializedData stream) { + stream.readInt32(); + int count = stream.readInt32(); + for (int a = 0; a < count; a++) { + authorizations.add((TL_authorization)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32())); + } + } + + public void serializeToStream(AbsSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32(0x1cb5c415); + int count = authorizations.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + authorizations.get(a).serializeToStream(stream); + } + } + } + public static class TL_req_pq extends TLObject { public static int constructor = 0x60469778; @@ -8375,8 +8454,9 @@ public class TLRPC { } public static class TL_messages_sendMessage extends TLObject { - public static int constructor = 0x1ca852a1; + public static int constructor = 0x9add8f26; + public int flags; public InputPeer peer; public int reply_to_msg_id; public String message; @@ -8387,58 +8467,71 @@ public class TLRPC { } public void readParams(AbsSerializedData stream) { + flags = stream.readInt32(); peer = (InputPeer)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32()); - reply_to_msg_id = stream.readInt32(); + if ((flags & 1) != 0) { + reply_to_msg_id = stream.readInt32(); + } message = stream.readString(); random_id = stream.readInt64(); } public void serializeToStream(AbsSerializedData stream) { stream.writeInt32(constructor); + stream.writeInt32(flags); peer.serializeToStream(stream); - stream.writeInt32(reply_to_msg_id); + if ((flags & 1) != 0) { + stream.writeInt32(reply_to_msg_id); + } stream.writeString(message); stream.writeInt64(random_id); } } public static class TL_messages_sendMedia extends TLObject { - public static int constructor = 0xfcee7fc0; + public static int constructor = 0x2d7923b1; + public int flags; public InputPeer peer; public int reply_to_msg_id; public InputMedia media; public long random_id; public Class responseClass () { - return messages_StatedMessage.class; + return Updates.class; } public void readParams(AbsSerializedData stream) { + flags = stream.readInt32(); peer = (InputPeer)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32()); - reply_to_msg_id = stream.readInt32(); + if ((flags & 1) != 0) { + reply_to_msg_id = stream.readInt32(); + } media = (InputMedia)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32()); random_id = stream.readInt64(); } public void serializeToStream(AbsSerializedData stream) { stream.writeInt32(constructor); + stream.writeInt32(flags); peer.serializeToStream(stream); - stream.writeInt32(reply_to_msg_id); + if ((flags & 1) != 0) { + stream.writeInt32(reply_to_msg_id); + } media.serializeToStream(stream); stream.writeInt64(random_id); } } public static class TL_messages_forwardMessages extends TLObject { - public static int constructor = 0xded42045; + public static int constructor = 0x55e1728d; public InputPeer peer; public ArrayList id = new ArrayList<>(); public ArrayList random_id = new ArrayList<>(); public Class responseClass () { - return messages_StatedMessages.class; + return Updates.class; } public void readParams(AbsSerializedData stream) { @@ -8521,13 +8614,13 @@ public class TLRPC { } public static class TL_messages_editChatTitle extends TLObject { - public static int constructor = 0xb4bc68b5; + public static int constructor = 0xdc452855; public int chat_id; public String title; public Class responseClass () { - return messages_StatedMessage.class; + return Updates.class; } public void readParams(AbsSerializedData stream) { @@ -8543,13 +8636,13 @@ public class TLRPC { } public static class TL_messages_editChatPhoto extends TLObject { - public static int constructor = 0xd881821d; + public static int constructor = 0xca4c79d8; public int chat_id; public InputChatPhoto photo; public Class responseClass () { - return messages_StatedMessage.class; + return Updates.class; } public void readParams(AbsSerializedData stream) { @@ -8565,14 +8658,14 @@ public class TLRPC { } public static class TL_messages_addChatUser extends TLObject { - public static int constructor = 0x2ee9ee9e; + public static int constructor = 0xf9a0aa09; public int chat_id; public InputUser user_id; public int fwd_limit; public Class responseClass () { - return messages_StatedMessage.class; + return Updates.class; } public void readParams(AbsSerializedData stream) { @@ -8590,13 +8683,13 @@ public class TLRPC { } public static class TL_messages_deleteChatUser extends TLObject { - public static int constructor = 0xc3c5cd23; + public static int constructor = 0xe0611f16; public int chat_id; public InputUser user_id; public Class responseClass () { - return messages_StatedMessage.class; + return Updates.class; } public void readParams(AbsSerializedData stream) { @@ -8612,13 +8705,13 @@ public class TLRPC { } public static class TL_messages_createChat extends TLObject { - public static int constructor = 0x419d9aee; + public static int constructor = 0x9cb126e; public ArrayList users = new ArrayList<>(); public String title; public Class responseClass () { - return messages_StatedMessage.class; + return Updates.class; } public void readParams(AbsSerializedData stream) { @@ -8635,8 +8728,8 @@ public class TLRPC { stream.writeInt32(0x1cb5c415); int count = users.size(); stream.writeInt32(count); - for (InputUser user : users) { - user.serializeToStream(stream); + for (int a = 0; a < count; a++) { + users.get(a).serializeToStream(stream); } stream.writeString(title); } @@ -8911,14 +9004,14 @@ public class TLRPC { } public static class TL_messages_forwardMessage extends TLObject { - public static int constructor = 0x3f3f4f2; + public static int constructor = 0x33963bf9; public InputPeer peer; public int id; public long random_id; - public Class responseClass() { - return messages_StatedMessage.class; + public Class responseClass () { + return Updates.class; } public void readParams(AbsSerializedData stream) { @@ -8936,14 +9029,15 @@ public class TLRPC { } public static class TL_messages_sendBroadcast extends TLObject { - public static int constructor = 0x41bb0972; + public static int constructor = 0xbf73f4da; public ArrayList contacts = new ArrayList<>(); + public ArrayList random_id = new ArrayList<>(); public String message; public InputMedia media; public Class responseClass () { - return messages_StatedMessages.class; + return Updates.class; } public void readParams(AbsSerializedData stream) { @@ -8952,6 +9046,11 @@ public class TLRPC { for (int a = 0; a < count; a++) { contacts.add((InputUser)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32())); } + stream.readInt32(); + count = stream.readInt32(); + for (int a = 0; a < count; a++) { + random_id.add(stream.readInt64()); + } message = stream.readString(); media = (InputMedia)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32()); } @@ -8961,8 +9060,14 @@ public class TLRPC { stream.writeInt32(0x1cb5c415); int count = contacts.size(); stream.writeInt32(count); - for (InputUser contact : contacts) { - contact.serializeToStream(stream); + for (int a = 0; a < count; a++) { + contacts.get(a).serializeToStream(stream); + } + stream.writeInt32(0x1cb5c415); + count = random_id.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + stream.writeInt64(random_id.get(a)); } stream.writeString(message); media.serializeToStream(stream); @@ -9432,6 +9537,111 @@ public class TLRPC { } } + public static class TL_account_getPassword extends TLObject { + public static int constructor = 0x548a30f5; + + + public Class responseClass () { + return account_Password.class; + } + + public void serializeToStream(AbsSerializedData stream) { + stream.writeInt32(constructor); + } + } + + public static class TL_account_getPasswordSettings extends TLObject { + public static int constructor = 0xbc8d11bb; + + public byte[] current_password_hash; + + public Class responseClass () { + return TL_account_passwordSettings.class; + } + + public void readParams(AbsSerializedData stream) { + current_password_hash = stream.readByteArray(); + } + + public void serializeToStream(AbsSerializedData stream) { + stream.writeInt32(constructor); + stream.writeByteArray(current_password_hash); + } + } + + public static class TL_account_updatePasswordSettings extends TLObject { + public static int constructor = 0xfa7c4b86; + + public byte[] current_password_hash; + public TL_account_passwordInputSettings new_settings; + + public Class responseClass () { + return Bool.class; + } + + public void readParams(AbsSerializedData stream) { + current_password_hash = stream.readByteArray(); + new_settings = (TL_account_passwordInputSettings)TLClassStore.Instance().TLdeserialize(stream, stream.readInt32()); + } + + public void serializeToStream(AbsSerializedData stream) { + stream.writeInt32(constructor); + stream.writeByteArray(current_password_hash); + new_settings.serializeToStream(stream); + } + } + + public static class TL_auth_checkPassword extends TLObject { + public static int constructor = 0xa63011e; + + public byte[] password_hash; + + public Class responseClass () { + return TL_auth_authorization.class; + } + + public void readParams(AbsSerializedData stream) { + password_hash = stream.readByteArray(); + } + + public void serializeToStream(AbsSerializedData stream) { + stream.writeInt32(constructor); + stream.writeByteArray(password_hash); + } + } + + public static class TL_auth_requestPasswordRecovery extends TLObject { + public static int constructor = 0xd897bc66; + + + public Class responseClass () { + return TL_auth_passwordRecovery.class; + } + + public void serializeToStream(AbsSerializedData stream) { + stream.writeInt32(constructor); + } + } + + public static class TL_auth_recoverPassword extends TLObject { + public static int constructor = 0x4ea56e92; + + public String code; + + public Class responseClass () { + return TL_auth_authorization.class; + } + + public void readParams(AbsSerializedData stream) { + code = stream.readString(); + } + + public void serializeToStream(AbsSerializedData stream) { + stream.writeInt32(constructor); + stream.writeString(code); + } + } + //manually created public static class TL_documentAttributeSticker_old extends TL_documentAttributeSticker { diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/UserConfig.java b/TMessagesProj/src/main/java/org/telegram/messenger/UserConfig.java index 6974ca94c..42e44a7ca 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/UserConfig.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/UserConfig.java @@ -30,7 +30,6 @@ public class UserConfig { private final static Object sync = new Object(); public static boolean saveIncomingPhotos = false; public static int contactsVersion = 1; - public static boolean waitingForPasswordEnter = false; public static String passcodeHash = ""; public static boolean appLocked = false; public static int passcodeType = 0; @@ -67,7 +66,6 @@ public class UserConfig { editor.putInt("lastBroadcastId", lastBroadcastId); editor.putBoolean("registeredForInternalPush", registeredForInternalPush); editor.putBoolean("blockedUsersLoaded", blockedUsersLoaded); - editor.putBoolean("waitingForPasswordEnter", waitingForPasswordEnter); editor.putString("passcodeHash1", passcodeHash); editor.putBoolean("appLocked", appLocked); editor.putInt("passcodeType", passcodeType); @@ -101,18 +99,6 @@ public class UserConfig { } } - public static boolean isWaitingForPasswordEnter() { - synchronized (sync) { - return waitingForPasswordEnter; - } - } - - public static void setWaitingForPasswordEnter(boolean value) { - synchronized (sync) { - waitingForPasswordEnter = value; - } - } - public static int getClientUserId() { synchronized (sync) { return currentUser != null ? currentUser.id : 0; @@ -208,7 +194,6 @@ public class UserConfig { lastBroadcastId = preferences.getInt("lastBroadcastId", -1); registeredForInternalPush = preferences.getBoolean("registeredForInternalPush", false); blockedUsersLoaded = preferences.getBoolean("blockedUsersLoaded", false); - waitingForPasswordEnter = preferences.getBoolean("waitingForPasswordEnter", false); passcodeHash = preferences.getString("passcodeHash1", ""); appLocked = preferences.getBoolean("appLocked", false); passcodeType = preferences.getInt("passcodeType", 0); @@ -231,7 +216,6 @@ public class UserConfig { currentUser = null; registeredForInternalPush = false; registeredForPush = false; - waitingForPasswordEnter = false; contactsHash = ""; importHash = ""; lastSendMessageId = -210000; diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java b/TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java index 47e2c951b..3a42f6c6f 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java @@ -21,7 +21,6 @@ import android.os.Build; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; -import android.text.Html; import android.text.SpannableStringBuilder; import android.util.Base64; @@ -29,6 +28,8 @@ import net.hockeyapp.android.CrashManager; import net.hockeyapp.android.CrashManagerListener; import net.hockeyapp.android.UpdateManager; +import org.telegram.android.AndroidUtilities; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -108,6 +109,7 @@ public class Utilities { public native static long doPQNative(long _what); public native static void loadBitmap(String path, Bitmap bitmap, int scale, int width, int height, int stride); + public native static int pinBitmap(Bitmap bitmap); public native static void blurBitmap(Object bitmap, int radius); public native static void calcCDT(ByteBuffer hsvBuffer, int width, int height, ByteBuffer buffer); public native static Bitmap loadWebpImage(ByteBuffer buffer, int len, BitmapFactory.Options options); @@ -145,6 +147,9 @@ public class Utilities { } public static String bytesToHex(byte[] bytes) { + if (bytes == null) { + return ""; + } char[] hexChars = new char[bytes.length * 2]; int v; for (int j = 0; j < bytes.length; j++) { @@ -156,6 +161,9 @@ public class Utilities { } public static byte[] hexToBytes(String hex) { + if (hex == null) { + return null; + } int len = hex.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { @@ -685,7 +693,7 @@ public class Utilities { builder.append(" "); } query.trim(); - builder.append(Html.fromHtml("" + query + "")); + builder.append(AndroidUtilities.replaceTags("" + query + "")); lastIndex = end; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/AccountPasswordActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/AccountPasswordActivity.java deleted file mode 100644 index a7c4f6b2c..000000000 --- a/TMessagesProj/src/main/java/org/telegram/ui/AccountPasswordActivity.java +++ /dev/null @@ -1,629 +0,0 @@ -/* - * This is the source code of Telegram for Android v. 2.0.x. - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2013-2014. - */ - -package org.telegram.ui; - -import android.app.Activity; -import android.app.AlertDialog; -import android.app.ProgressDialog; -import android.content.Context; -import android.content.DialogInterface; -import android.content.SharedPreferences; -import android.view.Gravity; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.FrameLayout; -import android.widget.ListView; -import android.widget.ProgressBar; - -import org.telegram.android.AndroidUtilities; -import org.telegram.android.ContactsController; -import org.telegram.android.LocaleController; -import org.telegram.android.MessagesController; -import org.telegram.android.MessagesStorage; -import org.telegram.android.NotificationCenter; -import org.telegram.messenger.ApplicationLoader; -import org.telegram.messenger.ConnectionsManager; -import org.telegram.messenger.FileLog; -import org.telegram.messenger.R; -import org.telegram.messenger.RPCRequest; -import org.telegram.messenger.TLObject; -import org.telegram.messenger.TLRPC; -import org.telegram.messenger.UserConfig; -import org.telegram.messenger.Utilities; -import org.telegram.ui.ActionBar.ActionBar; -import org.telegram.ui.ActionBar.ActionBarMenu; -import org.telegram.ui.ActionBar.BaseFragment; -import org.telegram.ui.Adapters.BaseFragmentAdapter; -import org.telegram.ui.Cells.HeaderCell; -import org.telegram.ui.Cells.TextFieldCell; -import org.telegram.ui.Cells.TextInfoPrivacyCell; -import org.telegram.ui.Cells.TextSettingsCell; - -import java.util.ArrayList; - -public class AccountPasswordActivity extends BaseFragment { - - private ListAdapter listAdapter; - private TextFieldCell oldPasswordCell; - private TextFieldCell newPasswordCell; - private TextFieldCell verifyPasswordCell; - private TextFieldCell hintPasswordCell; - private View doneButton; - private ProgressDialog progressDialog; - - private int type; - private boolean hasPassword; - private boolean loading; - private byte[] new_salt; - private String hint; - private byte[] current_salt; - - private int changePasswordSectionRow; - private int oldPasswordRow; - private int newPasswordRow; - private int verifyPasswordRow; - private int hintRow; - private int passwordDetailRow; - private int deleteAccountSection; - private int deleteAccountRow; - private int deleteAccountDetailRow; - private int rowCount; - - private final static int done_button = 1; - - public AccountPasswordActivity(int type) { - super(); - this.type = type; - } - - @Override - public boolean onFragmentCreate() { - super.onFragmentCreate(); - - getCurrentPassword(); - - return true; - } - - @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - if (type == 0) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - } - actionBar.setAllowOverlayTitle(true); - actionBar.setTitle(LocaleController.getString("Password", R.string.Password)); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } else if (id == done_button) { - doneWithPassword(); - } - } - }); - - ActionBarMenu menu = actionBar.createMenu(); - doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); - doneButton.setVisibility(loading ? View.GONE : View.VISIBLE); - - if (type == 0) { - oldPasswordCell = new TextFieldCell(getParentActivity()); - oldPasswordCell.setFieldTitleAndHint(LocaleController.getString("OldPassword", R.string.OldPassword), LocaleController.getString("EnterOldPassword", R.string.EnterOldPassword), AndroidUtilities.dp(10), true); - oldPasswordCell.setBackgroundColor(0xffffffff); - newPasswordCell = new TextFieldCell(getParentActivity()); - newPasswordCell.setFieldTitleAndHint(LocaleController.getString("NewPassword", R.string.NewPassword), LocaleController.getString("EnterNewPassword", R.string.EnterNewPassword), 0, true); - newPasswordCell.setBackgroundColor(0xffffffff); - verifyPasswordCell = new TextFieldCell(getParentActivity()); - verifyPasswordCell.setFieldTitleAndHint(null, LocaleController.getString("VerifyNewPassword", R.string.VerifyNewPassword), AndroidUtilities.dp(10), true); - verifyPasswordCell.setBackgroundColor(0xffffffff); - hintPasswordCell = new TextFieldCell(getParentActivity()); - hintPasswordCell.setFieldTitleAndHint(LocaleController.getString("PasswordHint", R.string.PasswordHint), LocaleController.getString("EnterHint", R.string.EnterHint), AndroidUtilities.dp(22), false); - hintPasswordCell.setBackgroundColor(0xffffffff); - if (hint != null) { - hintPasswordCell.setFieldText(hint); - } - } else if (type == 1) { - oldPasswordCell = new TextFieldCell(getParentActivity()); - oldPasswordCell.setFieldTitleAndHint(null, LocaleController.getString("EnterYourPassword", R.string.EnterYourPassword), AndroidUtilities.dp(22), true); - oldPasswordCell.setBackgroundColor(0xffffffff); - } - - listAdapter = new ListAdapter(getParentActivity()); - - fragmentView = new FrameLayout(getParentActivity()); - FrameLayout frameLayout = (FrameLayout) fragmentView; - frameLayout.setBackgroundColor(0xfff0f0f0); - - FrameLayout progressView = new FrameLayout(getParentActivity()); - frameLayout.addView(progressView); - FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - progressView.setLayoutParams(layoutParams); - - ProgressBar progressBar = new ProgressBar(getParentActivity()); - progressView.addView(progressBar); - layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.gravity = Gravity.CENTER; - progressView.setLayoutParams(layoutParams); - - ListView listView = new ListView(getParentActivity()); - listView.setDivider(null); - listView.setDividerHeight(0); - listView.setVerticalScrollBarEnabled(false); - listView.setDrawSelectorOnTop(true); - listView.setEmptyView(progressView); - frameLayout.addView(listView); - layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.gravity = Gravity.TOP; - listView.setLayoutParams(layoutParams); - listView.setAdapter(listAdapter); - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, final int i, long l) { - if (i == deleteAccountRow) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setMessage(LocaleController.getString("AreYouSureDeleteAccount", R.string.AreYouSureDeleteAccount)); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setMessage(LocaleController.getString("AreYouSureDeleteAccount2", R.string.AreYouSureDeleteAccount2)); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - TLRPC.TL_account_deleteAccount req = new TLRPC.TL_account_deleteAccount(); - req.reason = "Forgot password"; - ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { - @Override - public void run(TLObject response, TLRPC.TL_error error) { - if (error == null) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - editor.clear().commit(); - MessagesController.getInstance().unregistedPush(); - MessagesController.getInstance().logOut(); - UserConfig.clearConfig(); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.appDidLogout); - MessagesStorage.getInstance().cleanUp(false); - MessagesController.getInstance().cleanUp(); - ContactsController.getInstance().deleteAllAppAccounts(); - } - }); - } - } - }, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassWithoutLogin); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } - } - }); - - updateRows(); - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); - } - } - return fragmentView; - } - - @Override - public void onResume() { - super.onResume(); - if (listAdapter != null) { - listAdapter.notifyDataSetChanged(); - } - } - - private void updateRows() { - rowCount = 0; - if (!loading) { - if (type == 0) { - changePasswordSectionRow = rowCount++; - oldPasswordRow = hasPassword ? rowCount++ : -1; - newPasswordRow = rowCount++; - verifyPasswordRow = rowCount++; - hintRow = rowCount++; - passwordDetailRow = rowCount++; - deleteAccountSection = -1; - deleteAccountRow = -1; - deleteAccountDetailRow = -1; - } else if (type == 1) { - changePasswordSectionRow = rowCount++; - oldPasswordRow = rowCount++; - passwordDetailRow = rowCount++; - deleteAccountSection = rowCount++; - deleteAccountDetailRow = rowCount++; - verifyPasswordRow = -1; - newPasswordRow = -1; - hintRow = -1; - deleteAccountRow = -1; - } - doneButton.setVisibility(View.VISIBLE); - } - listAdapter.notifyDataSetChanged(); - } - - private void ShowAlert(final String text) { - if (text == null || getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setMessage(text); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); - showAlertDialog(builder); - } - - private void needShowProgress() { - if (getParentActivity() == null || getParentActivity().isFinishing() || progressDialog != null) { - return; - } - progressDialog = new ProgressDialog(getParentActivity()); - progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading)); - progressDialog.setCanceledOnTouchOutside(false); - progressDialog.setCancelable(false); - progressDialog.show(); - } - - private void needHideProgress() { - if (progressDialog == null) { - return; - } - try { - progressDialog.dismiss(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - progressDialog = null; - } - - private void getCurrentPassword() { - loading = true; - TLRPC.TL_account_getPassword req = new TLRPC.TL_account_getPassword(); - ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { - @Override - public void run(final TLObject response, final TLRPC.TL_error error) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - loading = false; - TLRPC.account_Password res = (TLRPC.account_Password) response; - if (res instanceof TLRPC.TL_account_noPassword) { - hasPassword = false; - new_salt = res.new_salt; - hint = null; - current_salt = null; - } else if (res instanceof TLRPC.TL_account_password) { - hasPassword = true; - new_salt = res.new_salt; - hint = res.hint; - current_salt = res.current_salt; - } else { - new_salt = null; - hint = null; - current_salt = null; - } - if (new_salt != null) { - byte[] salt = new byte[new_salt.length + 16]; - Utilities.random.nextBytes(salt); - System.arraycopy(new_salt, 0, salt, 0, new_salt.length); - new_salt = salt; - } - if (type == 0 && hintPasswordCell != null && hint != null) { - hintPasswordCell.setFieldText(hint); - } - updateRows(); - } - }); - } - }, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassWithoutLogin); - } - - private void doneWithPassword() { - if (type == 0) { - String oldPassword = oldPasswordCell.getFieldText(); - String newPassword = newPasswordCell.getFieldText(); - String verifyPasswrod = verifyPasswordCell.getFieldText(); - String hint = hintPasswordCell.getFieldText(); - if (hasPassword) { - if (oldPassword.length() == 0) { - ShowAlert(LocaleController.getString("PasswordOldIncorrect", R.string.PasswordOldIncorrect)); - return; - } - } - if (newPassword.length() == 0) { - ShowAlert(LocaleController.getString("PasswordNewIncorrect", R.string.PasswordNewIncorrect)); - return; - } - if (!newPassword.equals(verifyPasswrod)) { - ShowAlert(LocaleController.getString("PasswordDoNotMatch", R.string.PasswordDoNotMatch)); - return; - } - if (hint.toLowerCase().contains(newPassword.toLowerCase())) { - ShowAlert(LocaleController.getString("HintIncorrect", R.string.HintIncorrect)); - return; - } - byte[] oldPasswordBytes = null; - byte[] newPasswordBytes = null; - try { - oldPasswordBytes = oldPassword.getBytes("UTF-8"); - newPasswordBytes = newPassword.getBytes("UTF-8"); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - - TLRPC.TL_account_setPassword req = new TLRPC.TL_account_setPassword(); - req.hint = hintPasswordCell.getFieldText(); - if (req.hint == null) { - req.hint = ""; - } - if (hasPassword) { - byte[] hash = new byte[current_salt.length * 2 + oldPasswordBytes.length]; - System.arraycopy(current_salt, 0, hash, 0, current_salt.length); - System.arraycopy(oldPasswordBytes, 0, hash, oldPasswordBytes.length, oldPasswordBytes.length); - System.arraycopy(current_salt, 0, hash, hash.length - current_salt.length, current_salt.length); - req.current_password_hash = Utilities.computeSHA256(hash, 0, hash.length); - } else { - req.current_password_hash = new byte[0]; - } - - needShowProgress(); - byte[] hash = new byte[new_salt.length * 2 + newPasswordBytes.length]; - System.arraycopy(new_salt, 0, hash, 0, new_salt.length); - System.arraycopy(newPasswordBytes, 0, hash, newPasswordBytes.length, newPasswordBytes.length); - System.arraycopy(new_salt, 0, hash, hash.length - new_salt.length, new_salt.length); - req.new_password_hash = Utilities.computeSHA256(hash, 0, hash.length); - req.new_salt = new_salt; - ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { - @Override - public void run(final TLObject response, final TLRPC.TL_error error) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - needHideProgress(); - if (error == null) { - UserConfig.registeredForPush = false; - UserConfig.registeredForInternalPush = false; - UserConfig.saveConfig(false); - MessagesController.getInstance().registerForPush(UserConfig.pushString); - ConnectionsManager.getInstance().initPushConnection(); - finishFragment(); - } else { - if (error.text.contains("PASSWORD_HASH_INVALID")) { - ShowAlert(LocaleController.getString("PasswordOldIncorrect", R.string.PasswordOldIncorrect)); - } else if (error.text.contains("NEW_PASSWORD_BAD")) { - ShowAlert(LocaleController.getString("PasswordNewIncorrect", R.string.PasswordNewIncorrect)); - } else if (error.text.startsWith("FLOOD_WAIT")) { - ShowAlert(LocaleController.getString("FloodWait", R.string.FloodWait)); - } else { - ShowAlert(error.text); - } - } - } - }); - } - }, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors); - } else if (type == 1) { - String oldPassword = oldPasswordCell.getFieldText(); - if (oldPassword.length() == 0) { - ShowAlert(LocaleController.getString("PasswordIncorrect", R.string.PasswordIncorrect)); - return; - } - byte[] oldPasswordBytes = null; - try { - oldPasswordBytes = oldPassword.getBytes("UTF-8"); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - - needShowProgress(); - byte[] hash = new byte[current_salt.length * 2 + oldPasswordBytes.length]; - System.arraycopy(current_salt, 0, hash, 0, current_salt.length); - System.arraycopy(oldPasswordBytes, 0, hash, oldPasswordBytes.length, oldPasswordBytes.length); - System.arraycopy(current_salt, 0, hash, hash.length - current_salt.length, current_salt.length); - - TLRPC.TL_auth_checkPassword req = new TLRPC.TL_auth_checkPassword(); - req.password_hash = Utilities.computeSHA256(hash, 0, hash.length); - ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { - @Override - public void run(final TLObject response, final TLRPC.TL_error error) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - needHideProgress(); - if (error == null) { - if (UserConfig.isClientActivated()) { - presentFragment(new MessagesActivity(null), true); - UserConfig.registeredForPush = false; - UserConfig.registeredForInternalPush = false; - UserConfig.saveConfig(false); - MessagesController.getInstance().registerForPush(UserConfig.pushString); - ConnectionsManager.getInstance().initPushConnection(); - } else { - TLRPC.TL_auth_authorization res = (TLRPC.TL_auth_authorization)response; - UserConfig.clearConfig(); - MessagesController.getInstance().cleanUp(); - UserConfig.setCurrentUser(res.user); - UserConfig.saveConfig(true); - MessagesStorage.getInstance().cleanUp(true); - ArrayList users = new ArrayList<>(); - users.add(res.user); - MessagesStorage.getInstance().putUsersAndChats(users, null, true, true); - MessagesController.getInstance().putUser(res.user, false); - ContactsController.getInstance().checkAppAccount(); - MessagesController.getInstance().getBlockedUsers(true); - presentFragment(new MessagesActivity(null), true); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.mainUserInfoChanged); - ConnectionsManager.getInstance().initPushConnection(); - } - } else { - if (error.text.contains("PASSWORD_HASH_INVALID")) { - ShowAlert(LocaleController.getString("PasswordOldIncorrect", R.string.PasswordOldIncorrect)); - } else if (error.text.startsWith("FLOOD_WAIT")) { - ShowAlert(LocaleController.getString("FloodWait", R.string.FloodWait)); - } else { - ShowAlert(error.text); - } - } - } - }); - } - }, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassWithoutLogin); - } - } - - private class ListAdapter extends BaseFragmentAdapter { - private Context mContext; - - public ListAdapter(Context context) { - mContext = context; - } - - @Override - public boolean areAllItemsEnabled() { - return false; - } - - @Override - public boolean isEnabled(int i) { - return i == deleteAccountRow; - } - - @Override - public int getCount() { - return rowCount; - } - - @Override - public Object getItem(int i) { - return null; - } - - @Override - public long getItemId(int i) { - return i; - } - - @Override - public boolean hasStableIds() { - return false; - } - - @Override - public View getView(int i, View view, ViewGroup viewGroup) { - int viewType = getItemViewType(i); - if (viewType == 0) { - if (view == null) { - view = new TextInfoPrivacyCell(mContext); - } - if (i == passwordDetailRow) { - if (type == 0) { - ((TextInfoPrivacyCell) view).setText(LocaleController.getString("PasswordImportant", R.string.PasswordImportant)); - } else if (type == 1) { - ((TextInfoPrivacyCell) view).setText(hint == null || hint.length() == 0 ? "" : LocaleController.formatString("PasswordHintDetail", R.string.PasswordHintDetail, hint)); - } - ((TextInfoPrivacyCell) view).setTextColor(0xffcf3030); - if (deleteAccountDetailRow != -1) { - view.setBackgroundResource(R.drawable.greydivider); - } else { - view.setBackgroundResource(R.drawable.greydivider_bottom); - } - } else if (i == deleteAccountDetailRow) { - ((TextInfoPrivacyCell) view).setText(LocaleController.getString("DeleteAccountImportant", R.string.DeleteAccountImportant)); - ((TextInfoPrivacyCell) view).setTextColor(0xffcf3030); - view.setBackgroundResource(R.drawable.greydivider_bottom); - } - } else if (viewType == 1) { - if (view == null) { - view = new HeaderCell(mContext); - view.setBackgroundColor(0xffffffff); - } - if (i == changePasswordSectionRow) { - if (type == 0) { - ((HeaderCell) view).setText(LocaleController.getString("ChangePassword", R.string.ChangePassword)); - } else if (type == 1) { - ((HeaderCell) view).setText(LocaleController.getString("EnterPassword", R.string.EnterPassword)); - } - } else if (i == deleteAccountSection) { - ((HeaderCell) view).setText(LocaleController.getString("PasswordDeleteAccountTitle", R.string.PasswordDeleteAccountTitle)); - } - } else if (viewType == 2) { - return newPasswordCell; - } else if (viewType == 3) { - return oldPasswordCell; - } else if (viewType == 4) { - return verifyPasswordCell; - } else if (viewType == 5) { - return hintPasswordCell; - } else if (viewType == 6) { - if (view == null) { - view = new TextSettingsCell(mContext); - view.setBackgroundColor(0xffffffff); - } - TextSettingsCell textCell = (TextSettingsCell) view; - if (i == deleteAccountRow) { - textCell.setText(LocaleController.getString("PasswordDeleteAccount", R.string.PasswordDeleteAccount), false); - } - } - return view; - } - - @Override - public int getItemViewType(int i) { - if (i == passwordDetailRow || i == deleteAccountDetailRow) { - return 0; - } else if (i == changePasswordSectionRow || i == deleteAccountSection) { - return 1; - } else if (i == newPasswordRow) { - return 2; - } else if (i == oldPasswordRow) { - return 3; - } else if (i == verifyPasswordRow) { - return 4; - } else if (i == hintRow) { - return 5; - } else if (i == deleteAccountRow) { - return 6; - } - return 0; - } - - @Override - public int getViewTypeCount() { - return 7; - } - - @Override - public boolean isEmpty() { - return rowCount == 0; - } - } -} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBar.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBar.java index a04d43228..8c94548bf 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBar.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBar.java @@ -121,18 +121,10 @@ public class ActionBar extends FrameLayout { } int x = 0; - if (backButtonImageView != null) { - if (AndroidUtilities.isTablet()) { - x = AndroidUtilities.dp(80); - } else { - x = AndroidUtilities.dp(72); - } + if (backButtonImageView != null && backButtonImageView.getVisibility() == VISIBLE) { + x = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 80 : 72); } else { - if (AndroidUtilities.isTablet()) { - x = AndroidUtilities.dp(26); - } else { - x = AndroidUtilities.dp(18); - } + x = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 26 : 18); } if (menu != null) { @@ -202,17 +194,31 @@ public class ActionBar extends FrameLayout { } public void setBackButtonDrawable(Drawable drawable) { + boolean reposition = false; if (backButtonImageView == null) { createBackButtonImage(); + } else { + reposition = true; } + backButtonImageView.setVisibility(drawable == null ? GONE : VISIBLE); backButtonImageView.setImageDrawable(drawable); + if (reposition) { + positionTitle(getMeasuredWidth(), getMeasuredHeight()); + } } public void setBackButtonImage(int resource) { + boolean reposition = false; if (backButtonImageView == null) { createBackButtonImage(); + } else { + reposition = true; } + backButtonImageView.setVisibility(resource == 0 ? GONE : VISIBLE); backButtonImageView.setImageResource(resource); + if (reposition) { + positionTitle(getMeasuredWidth(), getMeasuredHeight()); + } } private void createSubtitleTextView() { @@ -234,7 +240,7 @@ public class ActionBar extends FrameLayout { createSubtitleTextView(); } if (subTitleTextView != null) { - subTitleTextView.setVisibility(value != null && !isSearchFieldVisible ? VISIBLE : GONE); + subTitleTextView.setVisibility(value != null && !isSearchFieldVisible ? VISIBLE : INVISIBLE); subTitleTextView.setText(value); positionTitle(getMeasuredWidth(), getMeasuredHeight()); } @@ -276,7 +282,7 @@ public class ActionBar extends FrameLayout { } if (titleTextView != null) { lastTitle = value; - titleTextView.setVisibility(value != null && !isSearchFieldVisible ? VISIBLE : GONE); + titleTextView.setVisibility(value != null && !isSearchFieldVisible ? VISIBLE : INVISIBLE); titleTextView.setText(value); positionTitle(getMeasuredWidth(), getMeasuredHeight()); } @@ -344,7 +350,7 @@ public class ActionBar extends FrameLayout { layoutParams.width = LayoutParams.FILL_PARENT; layoutParams.gravity = Gravity.RIGHT; actionMode.setLayoutParams(layoutParams); - actionMode.setVisibility(GONE); + actionMode.setVisibility(INVISIBLE); if (occupyStatusBar) { actionModeTop = new View(getContext()); @@ -355,7 +361,7 @@ public class ActionBar extends FrameLayout { layoutParams.width = LayoutParams.FILL_PARENT; layoutParams.gravity = Gravity.TOP | Gravity.LEFT; actionModeTop.setLayoutParams(layoutParams); - actionModeTop.setVisibility(GONE); + actionModeTop.setVisibility(INVISIBLE); } return actionMode; @@ -381,9 +387,9 @@ public class ActionBar extends FrameLayout { if (actionMode == null) { return; } - actionMode.setVisibility(GONE); + actionMode.setVisibility(INVISIBLE); if (occupyStatusBar && actionModeTop != null) { - actionModeTop.setVisibility(GONE); + actionModeTop.setVisibility(INVISIBLE); } if (titleFrameLayout != null) { titleFrameLayout.setVisibility(VISIBLE); @@ -400,10 +406,10 @@ public class ActionBar extends FrameLayout { protected void onSearchFieldVisibilityChanged(boolean visible) { isSearchFieldVisible = visible; if (titleTextView != null) { - titleTextView.setVisibility(visible ? GONE : VISIBLE); + titleTextView.setVisibility(visible ? INVISIBLE : VISIBLE); } if (subTitleTextView != null) { - subTitleTextView.setVisibility(visible ? GONE : VISIBLE); + subTitleTextView.setVisibility(visible ? INVISIBLE : VISIBLE); } Drawable drawable = backButtonImageView.getDrawable(); if (drawable != null && drawable instanceof MenuDrawable) { @@ -460,7 +466,7 @@ public class ActionBar extends FrameLayout { createTitleTextView(); } if (titleTextView != null) { - titleTextView.setVisibility(textToSet != null && !isSearchFieldVisible ? VISIBLE : GONE); + titleTextView.setVisibility(textToSet != null && !isSearchFieldVisible ? VISIBLE : INVISIBLE); titleTextView.setText(textToSet); positionTitle(getMeasuredWidth(), getMeasuredHeight()); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarLayout.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarLayout.java index 16fb026d2..c49768f8a 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarLayout.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarLayout.java @@ -303,7 +303,7 @@ public class ActionBarLayout extends FrameLayout { } } } - containerViewBack.setVisibility(View.GONE); + containerViewBack.setVisibility(View.INVISIBLE); //AndroidUtilities.unlockOrientation(parentActivity); startedTracking = false; animationInProgress = false; @@ -321,7 +321,15 @@ public class ActionBarLayout extends FrameLayout { beginTrackingSent = false; BaseFragment lastFragment = fragmentsStack.get(fragmentsStack.size() - 2); - View fragmentView = lastFragment.createView(parentActivity.getLayoutInflater()); + View fragmentView = lastFragment.fragmentView; + if (fragmentView == null) { + fragmentView = lastFragment.createView(parentActivity, parentActivity.getLayoutInflater()); + } else { + ViewGroup parent = (ViewGroup) fragmentView.getParent(); + if (parent != null) { + parent.removeView(fragmentView); + } + } ViewGroup parent = (ViewGroup) fragmentView.getParent(); if (parent != null) { parent.removeView(fragmentView); @@ -342,7 +350,7 @@ public class ActionBarLayout extends FrameLayout { layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; fragmentView.setLayoutParams(layoutParams); - if (fragmentView.getBackground() == null) { + if (!lastFragment.hasOwnBackground && fragmentView.getBackground() == null) { fragmentView.setBackgroundColor(0xffffffff); } lastFragment.onResume(); @@ -372,7 +380,7 @@ public class ActionBarLayout extends FrameLayout { int dx = Math.max(0, (int) (ev.getX() - startedTrackingX)); int dy = Math.abs((int) ev.getY() - startedTrackingY); velocityTracker.addMovement(ev); - if (maybeStartTracking && !startedTracking && dx >= AndroidUtilities.dp(10) && Math.abs(dx) / 3 > dy) { + if (maybeStartTracking && !startedTracking && dx >= AndroidUtilities.getPixelsInCM(0.3f, true) && Math.abs(dx) / 3 > dy) { prepareForMoving(ev); } else if (startedTracking) { if (!beginTrackingSent) { @@ -531,7 +539,7 @@ public class ActionBarLayout extends FrameLayout { } } } - containerViewBack.setVisibility(View.GONE); + containerViewBack.setVisibility(View.INVISIBLE); } public boolean presentFragment(BaseFragment fragment) { @@ -555,7 +563,15 @@ public class ActionBarLayout extends FrameLayout { final BaseFragment currentFragment = !fragmentsStack.isEmpty() ? fragmentsStack.get(fragmentsStack.size() - 1) : null; fragment.setParentLayout(this); - View fragmentView = fragment.createView(parentActivity.getLayoutInflater()); + View fragmentView = fragment.fragmentView; + if (fragmentView == null) { + fragmentView = fragment.createView(parentActivity, parentActivity.getLayoutInflater()); + } else { + ViewGroup parent = (ViewGroup) fragmentView.getParent(); + if (parent != null) { + parent.removeView(fragmentView); + } + } if (fragment.needAddActionBar() && fragment.actionBar != null) { if (removeActionBarExtraHeight) { fragment.actionBar.setOccupyStatusBar(false); @@ -576,7 +592,7 @@ public class ActionBarLayout extends FrameLayout { fragmentsStack.add(fragment); fragment.onResume(); currentActionBar = fragment.actionBar; - if (fragmentView.getBackground() == null) { + if (!fragment.hasOwnBackground && fragmentView.getBackground() == null) { fragmentView.setBackgroundColor(0xffffffff); } @@ -707,7 +723,7 @@ public class ActionBarLayout extends FrameLayout { fragment.onFragmentDestroy(); fragment.setParentLayout(null); fragmentsStack.remove(fragment); - containerViewBack.setVisibility(View.GONE); + containerViewBack.setVisibility(View.INVISIBLE); bringChildToFront(containerView); } @@ -733,7 +749,15 @@ public class ActionBarLayout extends FrameLayout { containerView.setVisibility(View.VISIBLE); previousFragment.setParentLayout(this); - View fragmentView = previousFragment.createView(parentActivity.getLayoutInflater()); + View fragmentView = previousFragment.fragmentView; + if (fragmentView == null) { + fragmentView = previousFragment.createView(parentActivity, parentActivity.getLayoutInflater()); + } else { + ViewGroup parent = (ViewGroup) fragmentView.getParent(); + if (parent != null) { + parent.removeView(fragmentView); + } + } if (previousFragment.needAddActionBar() && previousFragment.actionBar != null) { if (removeActionBarExtraHeight) { previousFragment.actionBar.setOccupyStatusBar(false); @@ -752,7 +776,7 @@ public class ActionBarLayout extends FrameLayout { fragmentView.setLayoutParams(layoutParams); previousFragment.onResume(); currentActionBar = previousFragment.actionBar; - if (fragmentView.getBackground() == null) { + if (!previousFragment.hasOwnBackground && fragmentView.getBackground() == null) { fragmentView.setBackgroundColor(0xffffffff); } @@ -804,9 +828,9 @@ public class ActionBarLayout extends FrameLayout { @Override public void run() { removeFragmentFromStack(currentFragment); - setVisibility(GONE); + setVisibility(INVISIBLE); if (backgroundView != null) { - backgroundView.setVisibility(GONE); + backgroundView.setVisibility(INVISIBLE); } if (drawerLayoutContainer != null) { drawerLayoutContainer.setAllowOpenDrawer(true, false); @@ -843,9 +867,9 @@ public class ActionBarLayout extends FrameLayout { currentAnimation.start(); } else { removeFragmentFromStack(currentFragment); - setVisibility(GONE); + setVisibility(INVISIBLE); if (backgroundView != null) { - backgroundView.setVisibility(GONE); + backgroundView.setVisibility(INVISIBLE); } } } @@ -857,7 +881,15 @@ public class ActionBarLayout extends FrameLayout { } BaseFragment previousFragment = fragmentsStack.get(fragmentsStack.size() - 1); previousFragment.setParentLayout(this); - View fragmentView = previousFragment.createView(parentActivity.getLayoutInflater()); + View fragmentView = previousFragment.fragmentView; + if (fragmentView == null) { + fragmentView = previousFragment.createView(parentActivity, parentActivity.getLayoutInflater()); + } else { + ViewGroup parent = (ViewGroup) fragmentView.getParent(); + if (parent != null) { + parent.removeView(fragmentView); + } + } if (previousFragment.needAddActionBar() && previousFragment.actionBar != null) { if (removeActionBarExtraHeight) { previousFragment.actionBar.setOccupyStatusBar(false); @@ -876,7 +908,7 @@ public class ActionBarLayout extends FrameLayout { fragmentView.setLayoutParams(layoutParams); previousFragment.onResume(); currentActionBar = previousFragment.actionBar; - if (fragmentView.getBackground() == null) { + if (!previousFragment.hasOwnBackground && fragmentView.getBackground() == null) { fragmentView.setBackgroundColor(0xffffffff); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BaseFragment.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BaseFragment.java index 1fdf62d77..b6592a2d9 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BaseFragment.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BaseFragment.java @@ -10,6 +10,7 @@ package org.telegram.ui.ActionBar; import android.app.Activity; import android.app.AlertDialog; +import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; @@ -31,6 +32,7 @@ public class BaseFragment { protected int classGuid = 0; protected Bundle arguments; protected boolean swipeBackEnabled = true; + protected boolean hasOwnBackground = false; public BaseFragment() { classGuid = ConnectionsManager.getInstance().generateClassGuid(); @@ -41,7 +43,7 @@ public class BaseFragment { classGuid = ConnectionsManager.getInstance().generateClassGuid(); } - public View createView(LayoutInflater inflater) { + public View createView(Context context, LayoutInflater inflater) { return null; } @@ -201,9 +203,9 @@ public class BaseFragment { return true; } - public void showAlertDialog(AlertDialog.Builder builder) { + public AlertDialog showAlertDialog(AlertDialog.Builder builder) { if (parentLayout == null || parentLayout.checkTransitionAnimation() || parentLayout.animationInProgress || parentLayout.startedTracking) { - return; + return null; } try { if (visibleDialog != null) { @@ -223,9 +225,11 @@ public class BaseFragment { onDialogDismiss(); } }); + return visibleDialog; } catch (Exception e) { FileLog.e("tmessages", e); } + return null; } protected void onDialogDismiss() { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/DrawerLayoutContainer.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/DrawerLayoutContainer.java index bbed0a058..aa136bf16 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/DrawerLayoutContainer.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/DrawerLayoutContainer.java @@ -301,7 +301,7 @@ public class DrawerLayoutContainer extends FrameLayout { float dx = (int) (ev.getX() - startedTrackingX); float dy = Math.abs((int) ev.getY() - startedTrackingY); velocityTracker.addMovement(ev); - if (maybeStartTracking && !startedTracking && (dx > 0 && dx / 3.0f > Math.abs(dy) || dx < 0 && Math.abs(dx) >= Math.abs(dy) && Math.abs(dx) >= AndroidUtilities.dp(10))) { + if (maybeStartTracking && !startedTracking && (dx > 0 && dx / 3.0f > Math.abs(dy) && Math.abs(dx) >= AndroidUtilities.getPixelsInCM(0.2f, true) || dx < 0 && Math.abs(dx) >= Math.abs(dy) && Math.abs(dx) >= AndroidUtilities.getPixelsInCM(0.3f, true))) { prepareForDrawerOpen(ev); startedTrackingX = (int) ev.getX(); requestDisallowInterceptTouchEvent(true); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/CountrySearchAdapter.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/CountrySearchAdapter.java index 8414dd5bd..8c39b844a 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/CountrySearchAdapter.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/CountrySearchAdapter.java @@ -73,7 +73,7 @@ public class CountrySearchAdapter extends BaseFragmentAdapter { return; } long time = System.currentTimeMillis(); - ArrayList resultArray = new ArrayList(); + ArrayList resultArray = new ArrayList<>(); String n = query.substring(0, 1); ArrayList arr = countries.get(n.toUpperCase()); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/DialogsSearchAdapter.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/DialogsSearchAdapter.java index 452d09d17..9a426aeb2 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/DialogsSearchAdapter.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/DialogsSearchAdapter.java @@ -9,7 +9,6 @@ package org.telegram.ui.Adapters; import android.content.Context; -import android.text.Html; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; @@ -348,7 +347,7 @@ public class DialogsSearchAdapter extends BaseSearchAdapter { user.status.expires = cursor.intValue(7); } if (found == 1) { - dialogSearchResult.name = Html.fromHtml("" + ContactsController.formatName(user.first_name, user.last_name) + ""); + dialogSearchResult.name = AndroidUtilities.replaceTags("" + ContactsController.formatName(user.first_name, user.last_name) + ""); } else { dialogSearchResult.name = Utilities.generateSearchName("@" + user.username, null, "@" + q); } @@ -534,6 +533,7 @@ public class DialogsSearchAdapter extends BaseSearchAdapter { notifyDataSetChanged(); return; } + searchResultMessages.clear(); searchResultHashtags.clear(); for (HashtagObject hashtagObject : hashtags) { searchResultHashtags.add(hashtagObject.hashtag); @@ -670,10 +670,11 @@ public class DialogsSearchAdapter extends BaseSearchAdapter { ((ProfileSearchCell) view).useSeparator = (i != getCount() - 1 && i != localCount - 1 && i != localCount + globalCount - 1); Object obj = getItem(i); if (obj instanceof TLRPC.User) { - user = MessagesController.getInstance().getUser(((TLRPC.User) obj).id); + /*user = MessagesController.getInstance().getUser(((TLRPC.User) obj).id); if (user == null) { user = (TLRPC.User) obj; - } + }*/ + user = (TLRPC.User) obj; } else if (obj instanceof TLRPC.Chat) { chat = MessagesController.getInstance().getChat(((TLRPC.Chat) obj).id); } else if (obj instanceof TLRPC.EncryptedChat) { @@ -697,7 +698,7 @@ public class DialogsSearchAdapter extends BaseSearchAdapter { foundUserName = foundUserName.substring(1); } try { - username = Html.fromHtml(String.format("@%s%s", user.username.substring(0, foundUserName.length()), user.username.substring(foundUserName.length()))); + username = AndroidUtilities.replaceTags(String.format("@%s%s", user.username.substring(0, foundUserName.length()), user.username.substring(foundUserName.length()))); } catch (Exception e) { username = user.username; FileLog.e("tmessages", e); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/SearchAdapter.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/SearchAdapter.java index 5a114dfdc..cf7ce7c1f 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/SearchAdapter.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/SearchAdapter.java @@ -9,7 +9,6 @@ package org.telegram.ui.Adapters; import android.content.Context; -import android.text.Html; import android.view.View; import android.view.ViewGroup; @@ -257,7 +256,7 @@ public class SearchAdapter extends BaseSearchAdapter { foundUserName = foundUserName.substring(1); } try { - username = Html.fromHtml(String.format("@%s%s", user.username.substring(0, foundUserName.length()), user.username.substring(foundUserName.length()))); + username = AndroidUtilities.replaceTags(String.format("@%s%s", user.username.substring(0, foundUserName.length()), user.username.substring(foundUserName.length()))); } catch (Exception e) { username = user.username; FileLog.e("tmessages", e); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/BlockedUsersActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/BlockedUsersActivity.java index ef1e5475f..5982e413b 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/BlockedUsersActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/BlockedUsersActivity.java @@ -64,131 +64,124 @@ public class BlockedUsersActivity extends BaseFragment implements NotificationCe } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - actionBar.setTitle(LocaleController.getString("BlockedUsers", R.string.BlockedUsers)); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } else if (id == block_user) { - Bundle args = new Bundle(); - args.putBoolean("onlyUsers", true); - args.putBoolean("destroyAfterSelect", true); - args.putBoolean("returnAsResult", true); - ContactsActivity fragment = new ContactsActivity(args); - fragment.setDelegate(BlockedUsersActivity.this); - presentFragment(fragment); - } + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setAllowOverlayTitle(true); + actionBar.setTitle(LocaleController.getString("BlockedUsers", R.string.BlockedUsers)); + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); + } else if (id == block_user) { + Bundle args = new Bundle(); + args.putBoolean("onlyUsers", true); + args.putBoolean("destroyAfterSelect", true); + args.putBoolean("returnAsResult", true); + ContactsActivity fragment = new ContactsActivity(args); + fragment.setDelegate(BlockedUsersActivity.this); + presentFragment(fragment); } - }); + } + }); - ActionBarMenu menu = actionBar.createMenu(); - menu.addItem(block_user, R.drawable.plus); + ActionBarMenu menu = actionBar.createMenu(); + menu.addItem(block_user, R.drawable.plus); - fragmentView = new FrameLayout(getParentActivity()); - FrameLayout frameLayout = (FrameLayout) fragmentView; + fragmentView = new FrameLayout(context); + FrameLayout frameLayout = (FrameLayout) fragmentView; - emptyTextView = new TextView(getParentActivity()); - emptyTextView.setTextColor(0xff808080); - emptyTextView.setTextSize(20); - emptyTextView.setGravity(Gravity.CENTER); - emptyTextView.setVisibility(View.INVISIBLE); - emptyTextView.setText(LocaleController.getString("NoBlocked", R.string.NoBlocked)); - frameLayout.addView(emptyTextView); - FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) emptyTextView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.gravity = Gravity.TOP; - emptyTextView.setLayoutParams(layoutParams); - emptyTextView.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { + emptyTextView = new TextView(context); + emptyTextView.setTextColor(0xff808080); + emptyTextView.setTextSize(20); + emptyTextView.setGravity(Gravity.CENTER); + emptyTextView.setVisibility(View.INVISIBLE); + emptyTextView.setText(LocaleController.getString("NoBlocked", R.string.NoBlocked)); + frameLayout.addView(emptyTextView); + FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) emptyTextView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.gravity = Gravity.TOP; + emptyTextView.setLayoutParams(layoutParams); + emptyTextView.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + + progressView = new FrameLayout(context); + frameLayout.addView(progressView); + layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + progressView.setLayoutParams(layoutParams); + + ProgressBar progressBar = new ProgressBar(context); + progressView.addView(progressBar); + layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.gravity = Gravity.CENTER; + progressView.setLayoutParams(layoutParams); + + listView = new ListView(context); + listView.setEmptyView(emptyTextView); + listView.setVerticalScrollBarEnabled(false); + listView.setDivider(null); + listView.setDividerHeight(0); + listView.setAdapter(listViewAdapter = new ListAdapter(context)); + if (Build.VERSION.SDK_INT >= 11) { + listView.setVerticalScrollbarPosition(LocaleController.isRTL ? ListView.SCROLLBAR_POSITION_LEFT : ListView.SCROLLBAR_POSITION_RIGHT); + } + frameLayout.addView(listView); + layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + listView.setLayoutParams(layoutParams); + + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, int i, long l) { + if (i < MessagesController.getInstance().blockedUsers.size()) { + Bundle args = new Bundle(); + args.putInt("user_id", MessagesController.getInstance().blockedUsers.get(i)); + presentFragment(new ProfileActivity(args)); + } + } + }); + + listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { + @Override + public boolean onItemLongClick(AdapterView adapterView, View view, int i, long l) { + if (i < 0 || i >= MessagesController.getInstance().blockedUsers.size() || getParentActivity() == null) { return true; } - }); + selectedUserId = MessagesController.getInstance().blockedUsers.get(i); - progressView = new FrameLayout(getParentActivity()); - frameLayout.addView(progressView); - layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - progressView.setLayoutParams(layoutParams); - - ProgressBar progressBar = new ProgressBar(getParentActivity()); - progressView.addView(progressBar); - layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.gravity = Gravity.CENTER; - progressView.setLayoutParams(layoutParams); - - listView = new ListView(getParentActivity()); - listView.setEmptyView(emptyTextView); - listView.setVerticalScrollBarEnabled(false); - listView.setDivider(null); - listView.setDividerHeight(0); - listView.setAdapter(listViewAdapter = new ListAdapter(getParentActivity())); - if (Build.VERSION.SDK_INT >= 11) { - listView.setVerticalScrollbarPosition(LocaleController.isRTL ? ListView.SCROLLBAR_POSITION_LEFT : ListView.SCROLLBAR_POSITION_RIGHT); - } - frameLayout.addView(listView); - layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - listView.setLayoutParams(layoutParams); - - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, int i, long l) { - if (i < MessagesController.getInstance().blockedUsers.size()) { - Bundle args = new Bundle(); - args.putInt("user_id", MessagesController.getInstance().blockedUsers.get(i)); - presentFragment(new ProfileActivity(args)); - } - } - }); - - listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { - @Override - public boolean onItemLongClick(AdapterView adapterView, View view, int i, long l) { - if (i < 0 || i >= MessagesController.getInstance().blockedUsers.size() || getParentActivity() == null) { - return true; - } - selectedUserId = MessagesController.getInstance().blockedUsers.get(i); - - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - CharSequence[] items = new CharSequence[] {LocaleController.getString("Unblock", R.string.Unblock)}; - builder.setItems(items, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - if (i == 0) { - MessagesController.getInstance().unblockUser(selectedUserId); - } + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + CharSequence[] items = new CharSequence[]{LocaleController.getString("Unblock", R.string.Unblock)}; + builder.setItems(items, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + if (i == 0) { + MessagesController.getInstance().unblockUser(selectedUserId); } - }); - showAlertDialog(builder); + } + }); + showAlertDialog(builder); - return true; - } - }); - - if (MessagesController.getInstance().loadingBlockedUsers) { - progressView.setVisibility(View.VISIBLE); - emptyTextView.setVisibility(View.GONE); - listView.setEmptyView(null); - } else { - progressView.setVisibility(View.GONE); - listView.setEmptyView(emptyTextView); + return true; } + }); + + if (MessagesController.getInstance().loadingBlockedUsers) { + progressView.setVisibility(View.VISIBLE); + emptyTextView.setVisibility(View.GONE); + listView.setEmptyView(null); } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); - } + progressView.setVisibility(View.GONE); + listView.setEmptyView(emptyTextView); } return fragmentView; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatBaseCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatBaseCell.java index 3fb3d1105..a56e53678 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatBaseCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatBaseCell.java @@ -14,7 +14,6 @@ import android.content.res.Configuration; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.drawable.Drawable; -import android.text.Html; import android.text.Layout; import android.text.StaticLayout; import android.text.TextPaint; @@ -83,9 +82,9 @@ public class ChatBaseCell extends BaseCell { private static TextPaint timeMediaPaint; private static TextPaint namePaint; private static TextPaint forwardNamePaint; - private static TextPaint replyNamePaint; - private static TextPaint replyTextPaint; - private static Paint replyLinePaint; + protected static TextPaint replyNamePaint; + protected static TextPaint replyTextPaint; + protected static Paint replyLinePaint; protected int backgroundWidth = 100; @@ -191,6 +190,7 @@ public class ChatBaseCell extends BaseCell { replyTextPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG); replyTextPaint.setTextSize(AndroidUtilities.dp(14)); + replyTextPaint.linkColor = 0xff316f9f; replyLinePaint = new Paint(); } @@ -362,7 +362,7 @@ public class ChatBaseCell extends BaseCell { forwardedNameWidth = getMaxNameWidth(); CharSequence str = TextUtils.ellipsize(currentForwardNameString.replace("\n", " "), forwardNamePaint, forwardedNameWidth - AndroidUtilities.dp(40), TextUtils.TruncateAt.END); - str = Html.fromHtml(String.format("%s
%s %s", LocaleController.getString("ForwardedMessage", R.string.ForwardedMessage), LocaleController.getString("From", R.string.From), str)); + str = AndroidUtilities.replaceTags(String.format("%s\n%s %s", LocaleController.getString("ForwardedMessage", R.string.ForwardedMessage), LocaleController.getString("From", R.string.From), str)); forwardedNameLayout = new StaticLayout(str, forwardNamePaint, forwardedNameWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); if (forwardedNameLayout.getLineCount() > 1) { forwardedNameWidth = Math.max((int) Math.ceil(forwardedNameLayout.getLineWidth(0)), (int) Math.ceil(forwardedNameLayout.getLineWidth(1))); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMessageCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMessageCell.java index f1f324e61..9098aaf1d 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMessageCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMessageCell.java @@ -9,35 +9,128 @@ package org.telegram.ui.Cells; import android.content.Context; +import android.content.Intent; import android.graphics.Canvas; +import android.graphics.Paint; +import android.graphics.Path; +import android.graphics.drawable.Drawable; +import android.net.Uri; +import android.provider.Browser; +import android.text.Layout; import android.text.Spannable; +import android.text.SpannableStringBuilder; +import android.text.StaticLayout; +import android.text.TextPaint; +import android.text.TextUtils; import android.text.style.ClickableSpan; import android.view.MotionEvent; import org.telegram.android.AndroidUtilities; +import org.telegram.android.ImageReceiver; +import org.telegram.android.MediaController; +import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.android.MessageObject; +import org.telegram.messenger.R; +import org.telegram.messenger.TLRPC; +import org.telegram.ui.Components.StaticLayoutEx; import org.telegram.ui.Components.URLSpanNoUnderline; +import java.util.Locale; + public class ChatMessageCell extends ChatBaseCell { private int textX, textY; private int totalHeight = 0; private ClickableSpan pressedLink; + private int linkBlockNum; + private MyPath urlPath = new MyPath(); + private boolean linkPreviewPressed; + private static Paint urlPaint; private int lastVisibleBlockNum = 0; private int firstVisibleBlockNum = 0; private int totalVisibleBlocksCount = 0; + private ImageReceiver linkImageView; + private boolean isSmallImage; + private boolean drawLinkImageView; + private boolean hasLinkPreview; + private int linkPreviewHeight; + private boolean isInstagram; + private int smallImageX; + private int descriptionY; + private int durationWidth; + private StaticLayout siteNameLayout; + private StaticLayout titleLayout; + private StaticLayout descriptionLayout; + private StaticLayout durationLayout; + private StaticLayout authorLayout; + private static TextPaint durationPaint; + private TLRPC.PhotoSize currentPhotoObject; + private TLRPC.PhotoSize currentPhotoObjectThumb; + private boolean imageCleared; + + private static Drawable igvideoDrawable; + + private class MyPath extends Path { + + private StaticLayout currentLayout; + private int currentLine; + private float lastTop = -1; + + public void setCurrentLayout(StaticLayout layout, int start) { + currentLayout = layout; + currentLine = layout.getLineForOffset(start); + lastTop = -1; + } + + @Override + public void addRect(float left, float top, float right, float bottom, Direction dir) { + if (lastTop == -1) { + lastTop = top; + } else if (lastTop != top) { + lastTop = top; + currentLine++; + } + float lineRight = currentLayout.getLineRight(currentLine); + float lineLeft = currentLayout.getLineLeft(currentLine); + if (left >= lineRight) { + return; + } + if (right > lineRight) { + right = lineRight; + } + if (left < lineLeft) { + left = lineLeft; + } + super.addRect(left, top, right, bottom, dir); + } + } + public ChatMessageCell(Context context) { super(context); drawForwardedName = true; + linkImageView = new ImageReceiver(this); + if (urlPaint == null) { + urlPaint = new Paint(); + urlPaint.setColor(0x33316f9f); + } + } + + private void resetPressedLink() { + if (pressedLink != null) { + pressedLink = null; + } + linkPreviewPressed = false; + invalidate(); } @Override public boolean onTouchEvent(MotionEvent event) { + boolean result = false; if (currentMessageObject != null && currentMessageObject.textLayoutBlocks != null && !currentMessageObject.textLayoutBlocks.isEmpty() && currentMessageObject.messageText instanceof Spannable && !isPressed) { - if (event.getAction() == MotionEvent.ACTION_DOWN || pressedLink != null && event.getAction() == MotionEvent.ACTION_UP) { + if (event.getAction() == MotionEvent.ACTION_DOWN || (linkPreviewPressed || pressedLink != null) && event.getAction() == MotionEvent.ACTION_UP) { int x = (int)event.getX(); int y = (int)event.getY(); if (x >= textX && y >= textY && x <= textX + currentMessageObject.textWidth && y <= textY + currentMessageObject.textHeight) { @@ -55,11 +148,19 @@ public class ChatMessageCell extends ChatBaseCell { if (left <= x && left + block.textLayout.getLineWidth(line) >= x) { Spannable buffer = (Spannable)currentMessageObject.messageText; ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class); - if (link.length != 0) { if (event.getAction() == MotionEvent.ACTION_DOWN) { + resetPressedLink(); pressedLink = link[0]; - return true; + linkBlockNum = blockNum; + try { + int start = buffer.getSpanStart(pressedLink) - block.charactersOffset; + urlPath.setCurrentLayout(block.textLayout, start); + block.textLayout.getSelectionPath(start, buffer.getSpanEnd(pressedLink) - block.charactersOffset, urlPath); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + result = true; } else { if (link[0] == pressedLink) { try { @@ -76,30 +177,98 @@ public class ChatMessageCell extends ChatBaseCell { } catch (Exception e) { FileLog.e("tmessages", e); } - return true; + resetPressedLink(); + result = true; } } } else { - pressedLink = null; + resetPressedLink(); } } else { - pressedLink = null; + resetPressedLink(); } } catch (Exception e) { - pressedLink = null; + resetPressedLink(); FileLog.e("tmessages", e); } } else { - pressedLink = null; + resetPressedLink(); + } + } else if (hasLinkPreview && x >= textX && x <= textX + backgroundWidth && y >= textY + currentMessageObject.textHeight && y <= textY + currentMessageObject.textHeight + linkPreviewHeight + AndroidUtilities.dp(8)) { + if (event.getAction() == MotionEvent.ACTION_DOWN) { + resetPressedLink(); + if (drawLinkImageView && linkImageView.isInsideImage(x, y)) { + linkPreviewPressed = true; + result = true; + } else { + if (descriptionLayout != null && y >= descriptionY) { + try { + x -= textX + AndroidUtilities.dp(10); + y -= descriptionY; + final int line = descriptionLayout.getLineForVertical(y); + final int off = descriptionLayout.getOffsetForHorizontal(line, x); + + final float left = descriptionLayout.getLineLeft(line); + if (left <= x && left + descriptionLayout.getLineWidth(line) >= x) { + Spannable buffer = (Spannable) currentMessageObject.linkDescription; + ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class); + if (link.length != 0) { + resetPressedLink(); + pressedLink = link[0]; + linkPreviewPressed = true; + linkBlockNum = -10; + result = true; + try { + int start = buffer.getSpanStart(pressedLink); + urlPath.setCurrentLayout(descriptionLayout, start); + descriptionLayout.getSelectionPath(start, buffer.getSpanEnd(pressedLink), urlPath); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } else { + resetPressedLink(); + } + } else { + resetPressedLink(); + } + } catch (Exception e) { + resetPressedLink(); + FileLog.e("tmessages", e); + } + } + } + } else if (linkPreviewPressed) { + try { + if (pressedLink != null) { + pressedLink.onClick(this); + } else { + Uri uri = Uri.parse(currentMessageObject.messageOwner.media.webpage.url); + Intent intent = new Intent(Intent.ACTION_VIEW, uri); + intent.putExtra(Browser.EXTRA_APPLICATION_ID, getContext().getPackageName()); + getContext().startActivity(intent); + } + } catch (Exception e) { + FileLog.e("tmessages", e); + } + resetPressedLink(); + result = true; } } else { - pressedLink = null; + resetPressedLink(); } + } else if (event.getAction() == MotionEvent.ACTION_CANCEL) { + resetPressedLink(); } } else { - pressedLink = null; + resetPressedLink(); } - return super.onTouchEvent(event); + if (result && event.getAction() == MotionEvent.ACTION_DOWN) { + startCheckLongPress(); + } + if (event.getAction() != MotionEvent.ACTION_DOWN && event.getAction() != MotionEvent.ACTION_MOVE) { + cancelCheckLongPress(); + } + return result || super.onTouchEvent(event); } public void setVisiblePart(int position, int height) { @@ -137,6 +306,51 @@ public class ChatMessageCell extends ChatBaseCell { return left1 <= right2; } + private StaticLayout generateStaticLayout(CharSequence text, TextPaint paint, int maxWidth, int smallWidth, int linesCount, int maxLines) { + SpannableStringBuilder stringBuilder = new SpannableStringBuilder(text); + int addedChars = 0; + StaticLayout layout = new StaticLayout(text, paint, smallWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); + for (int a = 0; a < linesCount; a++) { + int pos = layout.getLineEnd(a); + if (pos == text.length()) { + break; + } + pos--; + if (stringBuilder.charAt(pos + addedChars) == ' ') { + stringBuilder.replace(pos + addedChars, pos + addedChars + 1, "\n"); + } else { + stringBuilder.insert(pos + addedChars, "\n"); + addedChars++; + } + if (a == layout.getLineCount() - 1 || a == maxLines - 1) { + break; + } + } + return StaticLayoutEx.createStaticLayout(stringBuilder, paint, maxWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, AndroidUtilities.dp(1), false, TextUtils.TruncateAt.END, maxWidth, maxLines); + } + + @Override + protected boolean isUserDataChanged() { + if (imageCleared || !hasLinkPreview && currentMessageObject.messageOwner.media != null && currentMessageObject.messageOwner.media.webpage instanceof TLRPC.TL_webPage) { + return true; + } + //suppress warning + return super.isUserDataChanged(); + } + + @Override + protected void onDetachedFromWindow() { + super.onDetachedFromWindow(); + if (linkImageView != null) { + linkImageView.clearImage(); + if (currentPhotoObject != null) { + imageCleared = true; + currentPhotoObject = null; + currentPhotoObjectThumb = null; + } + } + } + @Override public void setMessageObject(MessageObject messageObject) { if (currentMessageObject != messageObject || isUserDataChanged()) { @@ -144,7 +358,21 @@ public class ChatMessageCell extends ChatBaseCell { firstVisibleBlockNum = 0; lastVisibleBlockNum = 0; } - pressedLink = null; + drawLinkImageView = false; + hasLinkPreview = false; + resetPressedLink(); + linkPreviewPressed = false; + linkPreviewHeight = 0; + smallImageX = 0; + isInstagram = false; + durationLayout = null; + descriptionLayout = null; + titleLayout = null; + siteNameLayout = null; + authorLayout = null; + currentPhotoObject = null; + imageCleared = false; + currentPhotoObjectThumb = null; int maxWidth; if (AndroidUtilities.isTablet()) { @@ -182,7 +410,215 @@ public class ChatMessageCell extends ChatBaseCell { timeMore += AndroidUtilities.dp(20.5f); } - if (maxWidth - messageObject.lastLineWidth < timeMore) { + if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage && messageObject.messageOwner.media.webpage instanceof TLRPC.TL_webPage) { + int linkPreviewMaxWidth; + if (AndroidUtilities.isTablet()) { + if (currentMessageObject.messageOwner.to_id.chat_id != 0 && !currentMessageObject.isOut()) { + linkPreviewMaxWidth = AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(122); + } else { + linkPreviewMaxWidth = AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(80); + } + } else { + if (currentMessageObject.messageOwner.to_id.chat_id != 0 && !currentMessageObject.isOut()) { + linkPreviewMaxWidth = Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) - AndroidUtilities.dp(122); + } else { + linkPreviewMaxWidth = Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) - AndroidUtilities.dp(80); + } + } + int additinalWidth = AndroidUtilities.dp(10); + int restLinesCount = 3; + int additionalHeight = 0; + linkPreviewMaxWidth -= additinalWidth; + + hasLinkPreview = true; + TLRPC.TL_webPage webPage = (TLRPC.TL_webPage) messageObject.messageOwner.media.webpage; + + if (currentMessageObject.photoThumbs == null && webPage.photo != null) { + currentMessageObject.generateThumbs(true); + } + + if (MediaController.getInstance().canDownloadMedia(MediaController.AUTODOWNLOAD_MASK_PHOTO)) { + isSmallImage = webPage.description != null && webPage.type != null && (webPage.type.equals("app") || webPage.type.equals("profile") || webPage.type.equals("article")) && currentMessageObject.photoThumbs != null; + } + + if (webPage.site_name != null) { + try { + int width = (int) Math.ceil(replyNamePaint.measureText(webPage.site_name)); + siteNameLayout = new StaticLayout(webPage.site_name, replyNamePaint, Math.min(width, linkPreviewMaxWidth), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); + int height = siteNameLayout.getLineBottom(siteNameLayout.getLineCount() - 1); + linkPreviewHeight += height; + totalHeight += height; + additionalHeight += height; + maxChildWidth = Math.max(maxChildWidth, width + additinalWidth); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + + if (webPage.title != null) { + try { + if (linkPreviewHeight != 0) { + linkPreviewHeight += AndroidUtilities.dp(2); + totalHeight += AndroidUtilities.dp(2); + } + int restLines = 0; + if (!isSmallImage || webPage.description == null) { + titleLayout = StaticLayoutEx.createStaticLayout(webPage.title, replyNamePaint, linkPreviewMaxWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, AndroidUtilities.dp(1), false, TextUtils.TruncateAt.END, linkPreviewMaxWidth, 2); + } else { + restLines = restLinesCount; + titleLayout = generateStaticLayout(webPage.title, replyNamePaint, linkPreviewMaxWidth, linkPreviewMaxWidth - AndroidUtilities.dp(48 + 2), restLinesCount, 2); + restLinesCount -= titleLayout.getLineCount(); + } + int height = titleLayout.getLineBottom(titleLayout.getLineCount() - 1); + linkPreviewHeight += height; + totalHeight += height; + for (int a = 0; a < titleLayout.getLineCount(); a++) { + int width = (int) Math.ceil(titleLayout.getLineWidth(a)); + if (a < restLines) { + smallImageX = Math.max(smallImageX, width); + width += AndroidUtilities.dp(48 + 2); + } + maxChildWidth = Math.max(maxChildWidth, width + additinalWidth); + } + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + + if (webPage.author != null) { + try { + if (linkPreviewHeight != 0) { + linkPreviewHeight += AndroidUtilities.dp(2); + totalHeight += AndroidUtilities.dp(2); + } + int width = Math.min((int) Math.ceil(replyNamePaint.measureText(webPage.author)), linkPreviewMaxWidth); + if (restLinesCount == 3 && (!isSmallImage || webPage.description == null)) { + authorLayout = new StaticLayout(webPage.author, replyNamePaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); + } else { + authorLayout = generateStaticLayout(webPage.author, replyNamePaint, width, linkPreviewMaxWidth - AndroidUtilities.dp(48 + 2), restLinesCount, 1); + restLinesCount -= authorLayout.getLineCount(); + } + int height = authorLayout.getLineBottom(authorLayout.getLineCount() - 1); + linkPreviewHeight += height; + totalHeight += height; + maxChildWidth = Math.max(maxChildWidth, width + additinalWidth); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + + if (webPage.description != null) { + try { + currentMessageObject.generateLinkDescription(); + if (linkPreviewHeight != 0) { + linkPreviewHeight += AndroidUtilities.dp(2); + totalHeight += AndroidUtilities.dp(2); + } + int restLines = 0; + if (restLinesCount == 3 && !isSmallImage) { + descriptionLayout = StaticLayoutEx.createStaticLayout(messageObject.linkDescription, replyTextPaint, linkPreviewMaxWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, AndroidUtilities.dp(1), false, TextUtils.TruncateAt.END, linkPreviewMaxWidth, 6); + } else { + restLines = restLinesCount; + descriptionLayout = generateStaticLayout(messageObject.linkDescription, replyTextPaint, linkPreviewMaxWidth, linkPreviewMaxWidth - AndroidUtilities.dp(48 + 2), restLinesCount, 6); + } + int height = descriptionLayout.getLineBottom(descriptionLayout.getLineCount() - 1); + linkPreviewHeight += height; + totalHeight += height; + for (int a = 0; a < descriptionLayout.getLineCount(); a++) { + int width = (int) Math.ceil(descriptionLayout.getLineWidth(a)); + if (a < restLines) { + smallImageX = Math.max(smallImageX, width); + width += AndroidUtilities.dp(48 + 2); + } + maxChildWidth = Math.max(maxChildWidth, width + additinalWidth); + } + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + + if (webPage.photo != null && MediaController.getInstance().canDownloadMedia(MediaController.AUTODOWNLOAD_MASK_PHOTO)) { + boolean smallImage = webPage.type != null && (webPage.type.equals("app") || webPage.type.equals("profile") || webPage.type.equals("article")); + if (smallImage && descriptionLayout != null && descriptionLayout.getLineCount() == 1) { + smallImage = false; + isSmallImage = false; + } + int maxPhotoWidth = smallImage ? AndroidUtilities.dp(48) : linkPreviewMaxWidth; + currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, maxPhotoWidth); + currentPhotoObjectThumb = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, 80); + if (currentPhotoObjectThumb == currentPhotoObject) { + currentPhotoObjectThumb = null; + } + if (currentPhotoObject != null) { + if (linkPreviewHeight != 0) { + linkPreviewHeight += AndroidUtilities.dp(2); + totalHeight += AndroidUtilities.dp(2); + } + + maxChildWidth = Math.max(maxChildWidth, maxPhotoWidth + additinalWidth); + currentPhotoObject.size = -1; + if (currentPhotoObjectThumb != null) { + currentPhotoObjectThumb.size = -1; + } + + int width; + int height; + if (smallImage) { + width = height = maxPhotoWidth; + } else { + width = currentPhotoObject.w; + height = currentPhotoObject.h; + float scale = width / (float) maxPhotoWidth; + width /= scale; + height /= scale; + if (height > AndroidUtilities.displaySize.y / 3) { + height = AndroidUtilities.displaySize.y / 3; + } + } + if (isSmallImage) { + if (AndroidUtilities.dp(50) + additionalHeight > linkPreviewHeight) { + totalHeight += AndroidUtilities.dp(50) + additionalHeight - linkPreviewHeight + AndroidUtilities.dp(8); + linkPreviewHeight = AndroidUtilities.dp(50) + additionalHeight; + } + linkPreviewHeight -= AndroidUtilities.dp(8); + } else { + totalHeight += height + AndroidUtilities.dp(12); + linkPreviewHeight += height; + } + + linkImageView.setImageCoords(0, 0, width, height); + linkImageView.setImage(currentPhotoObject.location, String.format(Locale.US, "%d_%d", width, height), currentPhotoObjectThumb != null ? currentPhotoObjectThumb.location : null, String.format(Locale.US, "%d_%d_b", width, height), 0, false); + drawLinkImageView = true; + + if (webPage.site_name != null) { + if (webPage.site_name.toLowerCase().equals("instagram") && webPage.type != null && webPage.type.equals("video")) { + isInstagram = true; + if (igvideoDrawable == null) { + igvideoDrawable = getResources().getDrawable(R.drawable.igvideo); + } + } + } + } + + if (webPage.duration != 0) { + if (durationPaint == null) { + durationPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); + durationPaint.setTextSize(AndroidUtilities.dp(12)); + durationPaint.setColor(0xffffffff); + } + int minutes = webPage.duration / 60; + int seconds = webPage.duration - minutes * 60; + String str = String.format("%d:%02d", minutes, seconds); + durationWidth = (int) Math.ceil(durationPaint.measureText(str)); + durationLayout = new StaticLayout(str, durationPaint, durationWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); + } + } else { + linkPreviewHeight -= AndroidUtilities.dp(6); + totalHeight += AndroidUtilities.dp(4); + } + } + + if (hasLinkPreview || maxWidth - messageObject.lastLineWidth < timeMore) { totalHeight += AndroidUtilities.dp(14); backgroundWidth = Math.max(maxChildWidth, messageObject.lastLineWidth) + AndroidUtilities.dp(29); } else { @@ -217,7 +653,7 @@ public class ChatMessageCell extends ChatBaseCell { @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); - if (currentMessageObject == null || currentMessageObject.textLayoutBlocks == null || currentMessageObject.textLayoutBlocks.isEmpty() || firstVisibleBlockNum < 0) { + if (currentMessageObject == null || currentMessageObject.textLayoutBlocks == null || currentMessageObject.textLayoutBlocks.isEmpty()) { return; } @@ -229,19 +665,121 @@ public class ChatMessageCell extends ChatBaseCell { textY = AndroidUtilities.dp(10) + namesOffset; } - for (int a = firstVisibleBlockNum; a <= lastVisibleBlockNum; a++) { - if (a >= currentMessageObject.textLayoutBlocks.size()) { - break; + if (firstVisibleBlockNum >= 0) { + for (int a = firstVisibleBlockNum; a <= lastVisibleBlockNum; a++) { + if (a >= currentMessageObject.textLayoutBlocks.size()) { + break; + } + MessageObject.TextLayoutBlock block = currentMessageObject.textLayoutBlocks.get(a); + canvas.save(); + canvas.translate(textX - (int) Math.ceil(block.textXOffset), textY + block.textYOffset); + if (pressedLink != null && a == linkBlockNum) { + canvas.drawPath(urlPath, urlPaint); + } + try { + block.textLayout.draw(canvas); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + canvas.restore(); } - MessageObject.TextLayoutBlock block = currentMessageObject.textLayoutBlocks.get(a); - canvas.save(); - canvas.translate(textX - (int)Math.ceil(block.textXOffset), textY + block.textYOffset); - try { - block.textLayout.draw(canvas); - } catch (Exception e) { - FileLog.e("tmessages", e); + } + + if (hasLinkPreview) { + int startY = textY + currentMessageObject.textHeight + AndroidUtilities.dp(8); + int linkPreviewY = startY; + int smallImageStartY = 0; + replyLinePaint.setColor(currentMessageObject.isOut() ? 0xff8dc97a : 0xff6c9fd2); + + canvas.drawRect(textX, linkPreviewY - AndroidUtilities.dp(3), textX + AndroidUtilities.dp(2), linkPreviewY + linkPreviewHeight + AndroidUtilities.dp(3), replyLinePaint); + + if (siteNameLayout != null) { + replyNamePaint.setColor(currentMessageObject.isOut() ? 0xff70b15c : 0xff4b91cf); + canvas.save(); + canvas.translate(textX + AndroidUtilities.dp(10), linkPreviewY - AndroidUtilities.dp(3)); + siteNameLayout.draw(canvas); + canvas.restore(); + linkPreviewY += siteNameLayout.getLineBottom(siteNameLayout.getLineCount() - 1); + } + + if (titleLayout != null) { + if (linkPreviewY != startY) { + linkPreviewY += AndroidUtilities.dp(2); + } + replyNamePaint.setColor(0xff000000); + smallImageStartY = linkPreviewY - AndroidUtilities.dp(1); + canvas.save(); + canvas.translate(textX + AndroidUtilities.dp(10), linkPreviewY - AndroidUtilities.dp(3)); + titleLayout.draw(canvas); + canvas.restore(); + linkPreviewY += titleLayout.getLineBottom(titleLayout.getLineCount() - 1); + } + + if (authorLayout != null) { + if (linkPreviewY != startY) { + linkPreviewY += AndroidUtilities.dp(2); + } + if (smallImageStartY == 0) { + smallImageStartY = linkPreviewY - AndroidUtilities.dp(1); + } + replyNamePaint.setColor(0xff000000); + canvas.save(); + canvas.translate(textX + AndroidUtilities.dp(10), linkPreviewY - AndroidUtilities.dp(3)); + authorLayout.draw(canvas); + canvas.restore(); + linkPreviewY += authorLayout.getLineBottom(authorLayout.getLineCount() - 1); + } + + if (descriptionLayout != null) { + if (linkPreviewY != startY) { + linkPreviewY += AndroidUtilities.dp(2); + } + if (smallImageStartY == 0) { + smallImageStartY = linkPreviewY - AndroidUtilities.dp(1); + } + replyTextPaint.setColor(0xff000000); + descriptionY = linkPreviewY - AndroidUtilities.dp(3); + canvas.save(); + canvas.translate(textX + AndroidUtilities.dp(10), descriptionY); + if (pressedLink != null && linkBlockNum == -10) { + canvas.drawPath(urlPath, urlPaint); + } + descriptionLayout.draw(canvas); + canvas.restore(); + linkPreviewY += descriptionLayout.getLineBottom(descriptionLayout.getLineCount() - 1); + } + + if (drawLinkImageView) { + if (linkPreviewY != startY) { + linkPreviewY += AndroidUtilities.dp(2); + } + + if (isSmallImage) { + linkImageView.setImageCoords(textX + smallImageX + AndroidUtilities.dp(12), smallImageStartY, linkImageView.getImageWidth(), linkImageView.getImageHeight()); + } else { + linkImageView.setImageCoords(textX + AndroidUtilities.dp(10), linkPreviewY, linkImageView.getImageWidth(), linkImageView.getImageHeight()); + } + linkImageView.draw(canvas); + + if (isInstagram && igvideoDrawable != null) { + int x = linkImageView.getImageX() + linkImageView.getImageWidth() - igvideoDrawable.getIntrinsicWidth() - AndroidUtilities.dp(4); + int y = linkImageView.getImageY() + AndroidUtilities.dp(4); + igvideoDrawable.setBounds(x, y, x + igvideoDrawable.getIntrinsicWidth(), y + igvideoDrawable.getIntrinsicHeight()); + igvideoDrawable.draw(canvas); + } + + if (durationLayout != null) { + int x = linkImageView.getImageX() + linkImageView.getImageWidth() - AndroidUtilities.dp(8) - durationWidth; + int y = linkImageView.getImageY() + linkImageView.getImageHeight() - AndroidUtilities.dp(19); + mediaBackgroundDrawable.setBounds(x - AndroidUtilities.dp(4), y - AndroidUtilities.dp(1.5f), x + durationWidth + AndroidUtilities.dp(4), y + AndroidUtilities.dp(14.5f)); + mediaBackgroundDrawable.draw(canvas); + + canvas.save(); + canvas.translate(x, y); + durationLayout.draw(canvas); + canvas.restore(); + } } - canvas.restore(); } } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/DialogCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/DialogCell.java index cc8828f2d..85f79f6bf 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/DialogCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/DialogCell.java @@ -12,7 +12,6 @@ import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.drawable.Drawable; -import android.text.Html; import android.text.Layout; import android.text.StaticLayout; import android.text.TextPaint; @@ -132,6 +131,7 @@ public class DialogCell extends BaseCell { messagePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG); messagePaint.setTextSize(AndroidUtilities.dp(16)); messagePaint.setColor(0xff8f8f8f); + messagePaint.linkColor = 0xff8f8f8f; linePaint = new Paint(); linePaint.setColor(0xffdcdcdc); @@ -341,9 +341,9 @@ public class DialogCell extends BaseCell { } } checkMessage = false; - if (message.messageOwner.media != null && !(message.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty)) { + if (message.messageOwner.media != null && !message.isMediaEmpty()) { currentMessagePaint = messagePrintingPaint; - messageString = Emoji.replaceEmoji(Html.fromHtml(String.format("%s: %s", name, message.messageText)), messagePaint.getFontMetricsInt(), AndroidUtilities.dp(20)); + messageString = Emoji.replaceEmoji(AndroidUtilities.replaceTags(String.format("%s: %s", name, message.messageText)), messagePaint.getFontMetricsInt(), AndroidUtilities.dp(20)); } else { if (message.messageOwner.message != null) { String mess = message.messageOwner.message; @@ -351,12 +351,12 @@ public class DialogCell extends BaseCell { mess = mess.substring(0, 150); } mess = mess.replace("\n", " "); - messageString = Emoji.replaceEmoji(Html.fromHtml(String.format("%s: %s", name, mess.replace("<", "<").replace(">", ">"))), messagePaint.getFontMetricsInt(), AndroidUtilities.dp(20)); + messageString = Emoji.replaceEmoji(AndroidUtilities.replaceTags(String.format("%s: %s", name, mess.replace("<", "<").replace(">", ">"))), messagePaint.getFontMetricsInt(), AndroidUtilities.dp(20)); } } } else { messageString = message.messageText; - if (message.messageOwner.media != null && !(message.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty)) { + if (message.messageOwner.media != null && !message.isMediaEmpty()) { currentMessagePaint = messagePrintingPaint; } } @@ -370,7 +370,7 @@ public class DialogCell extends BaseCell { drawCount = false; } - if (message.isOut() && message.isOut()) { + if (message.isOut()) { if (message.isSending()) { drawCheck1 = false; drawCheck2 = false; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/DrawerProfileCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/DrawerProfileCell.java index 74ee0a85b..706323fd6 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/DrawerProfileCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/DrawerProfileCell.java @@ -58,7 +58,7 @@ public class DrawerProfileCell extends FrameLayout { shadowView.setLayoutParams(layoutParams); avatarImageView = new BackupImageView(context); - avatarImageView.imageReceiver.setRoundRadius(AndroidUtilities.dp(32)); + avatarImageView.getImageReceiver().setRoundRadius(AndroidUtilities.dp(32)); addView(avatarImageView); layoutParams = (LayoutParams) avatarImageView.getLayoutParams(); layoutParams.width = AndroidUtilities.dp(64); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/MentionCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/MentionCell.java index 5ad6e43ef..67111a811 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/MentionCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/MentionCell.java @@ -37,7 +37,7 @@ public class MentionCell extends LinearLayout { avatarDrawable.setSmallStyle(true); imageView = new BackupImageView(context); - imageView.imageReceiver.setRoundRadius(AndroidUtilities.dp(14)); + imageView.setRoundRadius(AndroidUtilities.dp(14)); addView(imageView); LayoutParams layoutParams = (LayoutParams) imageView.getLayoutParams(); layoutParams.leftMargin = AndroidUtilities.dp(12); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoPickerAlbumsCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoPickerAlbumsCell.java index b20ed7c78..16540b5da 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoPickerAlbumsCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoPickerAlbumsCell.java @@ -117,7 +117,7 @@ public class PhotoPickerAlbumsCell extends FrameLayoutFixed { for (int a = 0; a < 4; a++) { albumViews[a] = new AlbumView(context); addView(albumViews[a]); - albumViews[a].setVisibility(GONE); + albumViews[a].setVisibility(INVISIBLE); albumViews[a].setTag(a); albumViews[a].setOnClickListener(new OnClickListener() { @Override @@ -132,7 +132,7 @@ public class PhotoPickerAlbumsCell extends FrameLayoutFixed { public void setAlbumsCount(int count) { for (int a = 0; a < albumViews.length; a++) { - albumViews[a].setVisibility(a < count ? VISIBLE : GONE); + albumViews[a].setVisibility(a < count ? VISIBLE : INVISIBLE); } albumsCount = count; } @@ -156,7 +156,7 @@ public class PhotoPickerAlbumsCell extends FrameLayoutFixed { albumView.nameTextView.setText(albumEntry.bucketName); albumView.countTextView.setText(String.format("%d", albumEntry.photos.size())); } else { - albumViews[a].setVisibility(GONE); + albumViews[a].setVisibility(INVISIBLE); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ProfileSearchCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ProfileSearchCell.java index a44ea6906..b6ce6a2f8 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ProfileSearchCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ProfileSearchCell.java @@ -30,6 +30,7 @@ import org.telegram.messenger.UserConfig; import org.telegram.ui.Components.AvatarDrawable; public class ProfileSearchCell extends BaseCell { + private static TextPaint namePaint; private static TextPaint nameEncryptedPaint; private static TextPaint onlinePaint; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/SessionCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/SessionCell.java new file mode 100644 index 000000000..924a851f7 --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/SessionCell.java @@ -0,0 +1,205 @@ +/* + * This is the source code of Telegram for Android v. 2.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-2015. + */ + +package org.telegram.ui.Cells; + +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Paint; +import android.text.TextUtils; +import android.util.TypedValue; +import android.view.Gravity; +import android.widget.FrameLayout; +import android.widget.LinearLayout; +import android.widget.TextView; + +import org.telegram.android.AndroidUtilities; +import org.telegram.android.LocaleController; +import org.telegram.messenger.R; +import org.telegram.messenger.TLRPC; + +import java.util.Locale; + +public class SessionCell extends FrameLayout { + + private TextView nameTextView; + private TextView onlineTextView; + private TextView detailTextView; + private TextView detailExTextView; + boolean needDivider; + private static Paint paint; + + public SessionCell(Context context) { + super(context); + + if (paint == null) { + paint = new Paint(); + paint.setColor(0xffd9d9d9); + paint.setStrokeWidth(1); + } + + LinearLayout linearLayout = new LinearLayout(context); + linearLayout.setOrientation(LinearLayout.HORIZONTAL); + linearLayout.setWeightSum(1); + addView(linearLayout); + LayoutParams layoutParams = (LayoutParams) linearLayout.getLayoutParams(); + layoutParams.width = LayoutParams.MATCH_PARENT; + layoutParams.height = AndroidUtilities.dp(30); + layoutParams.leftMargin = AndroidUtilities.dp(17); + layoutParams.rightMargin = AndroidUtilities.dp(17); + layoutParams.topMargin = AndroidUtilities.dp(11); + layoutParams.gravity = LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT; + linearLayout.setLayoutParams(layoutParams); + + nameTextView = new TextView(context); + nameTextView.setTextColor(0xff212121); + nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); + nameTextView.setLines(1); + nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); + nameTextView.setMaxLines(1); + nameTextView.setSingleLine(true); + nameTextView.setEllipsize(TextUtils.TruncateAt.END); + nameTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); + + onlineTextView = new TextView(context); + onlineTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + onlineTextView.setGravity((LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.TOP); + + if (LocaleController.isRTL) { + linearLayout.addView(onlineTextView); + linearLayout.addView(nameTextView); + } else { + linearLayout.addView(nameTextView); + linearLayout.addView(onlineTextView); + } + + LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) nameTextView.getLayoutParams(); + layoutParams2.width = 0; + layoutParams2.height = LayoutParams.MATCH_PARENT; + layoutParams2.weight = 1; + if (LocaleController.isRTL) { + layoutParams2.leftMargin = AndroidUtilities.dp(10); + } else { + layoutParams2.rightMargin = AndroidUtilities.dp(10); + } + layoutParams2.gravity = LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT; + nameTextView.setLayoutParams(layoutParams2); + + layoutParams2 = (LinearLayout.LayoutParams) onlineTextView.getLayoutParams(); + layoutParams2.width = LayoutParams.WRAP_CONTENT; + layoutParams2.height = LayoutParams.MATCH_PARENT; + layoutParams2.topMargin = AndroidUtilities.dp(2); + layoutParams2.gravity = (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.TOP; + onlineTextView.setLayoutParams(layoutParams2); + + detailTextView = new TextView(context); + detailTextView.setTextColor(0xff212121); + detailTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + detailTextView.setLines(1); + detailTextView.setMaxLines(1); + detailTextView.setSingleLine(true); + detailTextView.setEllipsize(TextUtils.TruncateAt.END); + detailTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); + addView(detailTextView); + layoutParams = (LayoutParams) detailTextView.getLayoutParams(); + layoutParams.width = LayoutParams.MATCH_PARENT; + layoutParams.height = LayoutParams.WRAP_CONTENT; + layoutParams.leftMargin = AndroidUtilities.dp(17); + layoutParams.rightMargin = AndroidUtilities.dp(17); + layoutParams.topMargin = AndroidUtilities.dp(36); + layoutParams.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP; + detailTextView.setLayoutParams(layoutParams); + + detailExTextView = new TextView(context); + detailExTextView.setTextColor(0xff999999); + detailExTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + detailExTextView.setLines(1); + detailExTextView.setMaxLines(1); + detailExTextView.setSingleLine(true); + detailExTextView.setEllipsize(TextUtils.TruncateAt.END); + detailExTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); + addView(detailExTextView); + layoutParams = (LayoutParams) detailExTextView.getLayoutParams(); + layoutParams.width = LayoutParams.MATCH_PARENT; + layoutParams.height = LayoutParams.WRAP_CONTENT; + layoutParams.leftMargin = AndroidUtilities.dp(17); + layoutParams.rightMargin = AndroidUtilities.dp(17); + layoutParams.topMargin = AndroidUtilities.dp(59); + layoutParams.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP; + detailExTextView.setLayoutParams(layoutParams); + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(90) + (needDivider ? 1 : 0), MeasureSpec.EXACTLY)); + } + + public void setSession(TLRPC.TL_authorization session, boolean divider) { + needDivider = divider; + + nameTextView.setText(String.format(Locale.US, "%s %s", session.app_name, session.app_version)); + if ((session.flags & 1) != 0) { + onlineTextView.setText(LocaleController.getString("Online", R.string.Online)); + onlineTextView.setTextColor(0xff2f8cc9); + } else { + onlineTextView.setText(LocaleController.stringForMessageListDate(session.date_active)); + onlineTextView.setTextColor(0xff999999); + } + + StringBuilder stringBuilder = new StringBuilder(); + if (session.ip.length() != 0) { + stringBuilder.append(session.ip); + } + if (session.country.length() != 0) { + if (stringBuilder.length() != 0) { + stringBuilder.append(" "); + } + stringBuilder.append("— "); + stringBuilder.append(session.country); + } + detailExTextView.setText(stringBuilder); + + stringBuilder = new StringBuilder(); + if (session.device_model.length() != 0) { + stringBuilder.append(session.device_model); + } + if (session.system_version.length() != 0 || session.platform.length() != 0) { + if (stringBuilder.length() != 0) { + stringBuilder.append(", "); + } + if (session.platform.length() != 0) { + stringBuilder.append(session.platform); + } + if (session.system_version.length() != 0) { + if (session.platform.length() != 0) { + stringBuilder.append(" "); + } + stringBuilder.append(session.system_version); + } + } + + if ((session.flags & 2) == 0) { + if (stringBuilder.length() != 0) { + stringBuilder.append(", "); + } + stringBuilder.append(LocaleController.getString("UnofficialApp", R.string.UnofficialApp)); + stringBuilder.append(" (ID: "); + stringBuilder.append(session.api_id); + stringBuilder.append(")"); + } + + detailTextView.setText(stringBuilder); + } + + @Override + protected void onDraw(Canvas canvas) { + if (needDivider) { + canvas.drawLine(getPaddingLeft(), getHeight() - 1, getWidth() - getPaddingRight(), getHeight() - 1, paint); + } + } +} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedDocumentCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedDocumentCell.java index 1938fea35..a41172b06 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedDocumentCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedDocumentCell.java @@ -36,7 +36,7 @@ import org.telegram.ui.Components.LineProgressView; import java.io.File; import java.util.Date; -public class SharedDocumentCell extends FrameLayout implements MediaController.FileDownloadProgressListener { +public class SharedDocumentCell extends FrameLayout implements MediaController.FileDownloadProgressListener { private ImageView placeholderImabeView; private BackupImageView thumbImageView; @@ -106,11 +106,11 @@ public class SharedDocumentCell extends FrameLayout implements MediaController. extTextView.setLayoutParams(layoutParams); thumbImageView = new BackupImageView(context); - thumbImageView.imageReceiver.setDelegate(new ImageReceiver.ImageReceiverDelegate() { + thumbImageView.getImageReceiver().setDelegate(new ImageReceiver.ImageReceiverDelegate() { @Override public void didSetImage(ImageReceiver imageReceiver, boolean set, boolean thumb) { - extTextView.setVisibility(set ? GONE : VISIBLE); - placeholderImabeView.setVisibility(set ? GONE : VISIBLE); + extTextView.setVisibility(set ? INVISIBLE : VISIBLE); + placeholderImabeView.setVisibility(set ? INVISIBLE : VISIBLE); } }); addView(thumbImageView); @@ -143,7 +143,7 @@ public class SharedDocumentCell extends FrameLayout implements MediaController. nameTextView.setLayoutParams(layoutParams); statusImageView = new ImageView(context); - statusImageView.setVisibility(GONE); + statusImageView.setVisibility(INVISIBLE); addView(statusImageView); layoutParams = (LayoutParams) statusImageView.getLayoutParams(); layoutParams.width = LayoutParams.WRAP_CONTENT; @@ -184,7 +184,7 @@ public class SharedDocumentCell extends FrameLayout implements MediaController. progressView.setLayoutParams(layoutParams); checkBox = new CheckBox(context, R.drawable.round_check2); - checkBox.setVisibility(GONE); + checkBox.setVisibility(INVISIBLE); addView(checkBox); layoutParams = (LayoutParams) checkBox.getLayoutParams(); layoutParams.width = AndroidUtilities.dp(22); @@ -229,13 +229,13 @@ public class SharedDocumentCell extends FrameLayout implements MediaController. extTextView.setVisibility(VISIBLE); extTextView.setText(type); } else { - extTextView.setVisibility(GONE); + extTextView.setVisibility(INVISIBLE); } if (resId == 0) { placeholderImabeView.setImageResource(getThumbForNameOrMime(text, type)); placeholderImabeView.setVisibility(VISIBLE); } else { - placeholderImabeView.setVisibility(GONE); + placeholderImabeView.setVisibility(INVISIBLE); } if (thumb != null || resId != 0) { if (thumb != null) { @@ -245,7 +245,7 @@ public class SharedDocumentCell extends FrameLayout implements MediaController. } thumbImageView.setVisibility(VISIBLE); } else { - thumbImageView.setVisibility(GONE); + thumbImageView.setVisibility(INVISIBLE); } } @@ -277,7 +277,7 @@ public class SharedDocumentCell extends FrameLayout implements MediaController. nameTextView.setText(name); extTextView.setText((idx = name.lastIndexOf(".")) == -1 ? "" : name.substring(idx + 1).toLowerCase()); if (document.messageOwner.media.document.thumb instanceof TLRPC.TL_photoSizeEmpty) { - thumbImageView.setVisibility(GONE); + thumbImageView.setVisibility(INVISIBLE); thumbImageView.setImageBitmap(null); } else { thumbImageView.setVisibility(VISIBLE); @@ -291,7 +291,7 @@ public class SharedDocumentCell extends FrameLayout implements MediaController. dateTextView.setText(""); placeholderImabeView.setVisibility(VISIBLE); extTextView.setVisibility(VISIBLE); - thumbImageView.setVisibility(GONE); + thumbImageView.setVisibility(INVISIBLE); thumbImageView.setImageBitmap(null); } @@ -312,7 +312,7 @@ public class SharedDocumentCell extends FrameLayout implements MediaController. } loaded = false; if (fileName == null) { - statusImageView.setVisibility(GONE); + statusImageView.setVisibility(INVISIBLE); dateTextView.setPadding(0, 0, 0, 0); loading = false; loaded = true; @@ -331,15 +331,15 @@ public class SharedDocumentCell extends FrameLayout implements MediaController. } progressView.setProgress(progress, false); } else { - progressView.setVisibility(GONE); + progressView.setVisibility(INVISIBLE); } } } else { loading = false; loaded = true; - progressView.setVisibility(GONE); + progressView.setVisibility(INVISIBLE); progressView.setProgress(0, false); - statusImageView.setVisibility(GONE); + statusImageView.setVisibility(INVISIBLE); dateTextView.setPadding(0, 0, 0, 0); MediaController.getInstance().removeLoadingFileObserver(this); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedPhotoVideoCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedPhotoVideoCell.java index 32719d2a3..7b6085d45 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedPhotoVideoCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedPhotoVideoCell.java @@ -55,8 +55,8 @@ public class SharedPhotoVideoCell extends FrameLayoutFixed { super(context); imageView = new BackupImageView(context); - imageView.imageReceiver.setNeedsQualityThumb(true); - imageView.imageReceiver.setShouldGenerateQualityThumb(true); + imageView.getImageReceiver().setNeedsQualityThumb(true); + imageView.getImageReceiver().setShouldGenerateQualityThumb(true); addView(imageView); LayoutParams layoutParams = (LayoutParams) imageView.getLayoutParams(); layoutParams.width = LayoutParams.MATCH_PARENT; @@ -105,7 +105,7 @@ public class SharedPhotoVideoCell extends FrameLayoutFixed { selector.setLayoutParams(layoutParams); checkBox = new CheckBox(context, R.drawable.round_check2); - checkBox.setVisibility(GONE); + checkBox.setVisibility(INVISIBLE); addView(checkBox); layoutParams = (LayoutParams) checkBox.getLayoutParams(); layoutParams.width = AndroidUtilities.dp(22); @@ -134,7 +134,7 @@ public class SharedPhotoVideoCell extends FrameLayoutFixed { for (int a = 0; a < 6; a++) { photoVideoViews[a] = new PhotoVideoView(context); addView(photoVideoViews[a]); - photoVideoViews[a].setVisibility(GONE); + photoVideoViews[a].setVisibility(INVISIBLE); photoVideoViews[a].setTag(a); photoVideoViews[a].setOnClickListener(new OnClickListener() { @Override @@ -164,7 +164,7 @@ public class SharedPhotoVideoCell extends FrameLayoutFixed { public void setItemsCount(int count) { for (int a = 0; a < photoVideoViews.length; a++) { - photoVideoViews[a].setVisibility(a < count ? VISIBLE : GONE); + photoVideoViews[a].setVisibility(a < count ? VISIBLE : INVISIBLE); } itemsCount = count; } @@ -202,8 +202,8 @@ public class SharedPhotoVideoCell extends FrameLayoutFixed { photoVideoViews[a].setVisibility(VISIBLE); PhotoVideoView photoVideoView = photoVideoViews[a]; - photoVideoView.imageView.imageReceiver.setParentMessageObject(messageObject); - photoVideoView.imageView.imageReceiver.setVisible(!PhotoViewer.getInstance().isShowingImage(messageObject), false); + photoVideoView.imageView.getImageReceiver().setParentMessageObject(messageObject); + photoVideoView.imageView.getImageReceiver().setVisible(!PhotoViewer.getInstance().isShowingImage(messageObject), false); if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVideo && messageObject.messageOwner.media.video != null) { photoVideoView.videoInfoContainer.setVisibility(VISIBLE); int duration = messageObject.messageOwner.media.video.duration; @@ -217,15 +217,15 @@ public class SharedPhotoVideoCell extends FrameLayoutFixed { photoVideoView.imageView.setImageResource(R.drawable.photo_placeholder_in); } } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto && messageObject.messageOwner.media.photo != null && !messageObject.photoThumbs.isEmpty()) { - photoVideoView.videoInfoContainer.setVisibility(GONE); + photoVideoView.videoInfoContainer.setVisibility(INVISIBLE); TLRPC.PhotoSize photoSize = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, 80); photoVideoView.imageView.setImage(null, null, null, ApplicationLoader.applicationContext.getResources().getDrawable(R.drawable.photo_placeholder_in), null, photoSize.location, "b", 0); } else { - photoVideoView.videoInfoContainer.setVisibility(GONE); + photoVideoView.videoInfoContainer.setVisibility(INVISIBLE); photoVideoView.imageView.setImageResource(R.drawable.photo_placeholder_in); } } else { - photoVideoViews[a].setVisibility(GONE); + photoVideoViews[a].setVisibility(INVISIBLE); messageObjects[a] = null; } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/StickerCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/StickerCell.java index 59b9c4ddf..34e04c69b 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/StickerCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/StickerCell.java @@ -26,9 +26,7 @@ public class StickerCell extends FrameLayoutFixed { super(context); imageView = new BackupImageView(context); - imageView.imageReceiver.setAspectFit(true); - imageView.imageReceiver.setDisableRecycle(true); - imageView.processDetach = false; + imageView.setAspectFit(true); addView(imageView); LayoutParams layoutParams = (LayoutParams) imageView.getLayoutParams(); layoutParams.width = AndroidUtilities.dp(66); @@ -45,8 +43,8 @@ public class StickerCell extends FrameLayoutFixed { @Override public void setPressed(boolean pressed) { - if (imageView.imageReceiver.getPressed() != pressed) { - imageView.imageReceiver.setPressed(pressed); + if (imageView.getImageReceiver().getPressed() != pressed) { + imageView.getImageReceiver().setPressed(pressed); imageView.invalidate(); } super.setPressed(pressed); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextCell.java index 0c05b6e53..d86331002 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextCell.java @@ -97,32 +97,32 @@ public class TextCell extends FrameLayout { public void setText(String text) { textView.setText(text); - imageView.setVisibility(GONE); - valueTextView.setVisibility(GONE); - valueImageView.setVisibility(GONE); + imageView.setVisibility(INVISIBLE); + valueTextView.setVisibility(INVISIBLE); + valueImageView.setVisibility(INVISIBLE); } public void setTextAndIcon(String text, int resId) { textView.setText(text); imageView.setImageResource(resId); imageView.setVisibility(VISIBLE); - valueTextView.setVisibility(GONE); - valueImageView.setVisibility(GONE); + valueTextView.setVisibility(INVISIBLE); + valueImageView.setVisibility(INVISIBLE); } public void setTextAndValue(String text, String value) { textView.setText(text); valueTextView.setText(value); valueTextView.setVisibility(VISIBLE); - imageView.setVisibility(GONE); - valueImageView.setVisibility(GONE); + imageView.setVisibility(INVISIBLE); + valueImageView.setVisibility(INVISIBLE); } public void setTextAndValueDrawable(String text, Drawable drawable) { textView.setText(text); valueImageView.setVisibility(VISIBLE); valueImageView.setImageDrawable(drawable); - valueTextView.setVisibility(GONE); - imageView.setVisibility(GONE); + valueTextView.setVisibility(INVISIBLE); + imageView.setVisibility(INVISIBLE); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextDetailCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextDetailCell.java index 86afa6085..513daf871 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextDetailCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextDetailCell.java @@ -82,7 +82,7 @@ public class TextDetailCell extends FrameLayout { public void setTextAndValue(String text, String value) { textView.setText(text); valueTextView.setText(value); - imageView.setVisibility(GONE); + imageView.setVisibility(INVISIBLE); } public void setTextAndValueAndIcon(String text, String value, int resId) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextFieldCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextFieldCell.java deleted file mode 100644 index 3d8cb7cde..000000000 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextFieldCell.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * This is the source code of Telegram for Android v. 2.0.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.Cells; - -import android.content.Context; -import android.graphics.Typeface; -import android.text.InputType; -import android.util.TypedValue; -import android.view.Gravity; -import android.view.KeyEvent; -import android.view.inputmethod.EditorInfo; -import android.widget.EditText; -import android.widget.LinearLayout; -import android.widget.TextView; - -import org.telegram.android.AndroidUtilities; -import org.telegram.android.LocaleController; - -public class TextFieldCell extends LinearLayout { - - private TextView textView; - private EditText editText; - - public TextFieldCell(Context context) { - super(context); - setOrientation(VERTICAL); - - textView = new TextView(context); - textView.setTextColor(0xff505050); - textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12); - addView(textView); - LayoutParams layoutParams = (LayoutParams) textView.getLayoutParams(); - layoutParams.topMargin = AndroidUtilities.dp(17); - layoutParams.height = LayoutParams.WRAP_CONTENT; - layoutParams.leftMargin = AndroidUtilities.dp(17); - layoutParams.rightMargin = AndroidUtilities.dp(17); - layoutParams.width = LayoutParams.MATCH_PARENT; - textView.setLayoutParams(layoutParams); - - editText = new EditText(context); - editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - editText.setHintTextColor(0xffbebebe); - editText.setTextColor(0xff212121); - editText.setMaxLines(1); - editText.setLines(1); - editText.setSingleLine(true); - editText.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); - editText.setImeOptions(EditorInfo.IME_ACTION_DONE); - AndroidUtilities.clearCursorDrawable(editText); - addView(editText); - layoutParams = (LayoutParams) editText.getLayoutParams(); - layoutParams.topMargin = AndroidUtilities.dp(10); - layoutParams.bottomMargin = AndroidUtilities.dp(17); - layoutParams.height = AndroidUtilities.dp(30); - layoutParams.leftMargin = AndroidUtilities.dp(17); - layoutParams.rightMargin = AndroidUtilities.dp(17); - layoutParams.width = LayoutParams.MATCH_PARENT; - editText.setLayoutParams(layoutParams); - editText.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { - if (i == EditorInfo.IME_ACTION_DONE) { - textView.clearFocus(); - AndroidUtilities.hideKeyboard(textView); - return true; - } - return false; - } - }); - } - - public void setFieldText(String text) { - editText.setText(text); - } - - public String getFieldText() { - return editText.getText().toString(); - } - - public void setFieldTitleAndHint(String title, String hint, int bottom, boolean password) { - editText.setHint(hint); - LayoutParams layoutParams = (LayoutParams) editText.getLayoutParams(); - layoutParams.bottomMargin = bottom; - editText.setLayoutParams(layoutParams); - if (password) { - editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); - editText.setTypeface(Typeface.DEFAULT); - } else { - editText.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); - } - if (title != null) { - textView.setText(title); - textView.setVisibility(VISIBLE); - } else { - textView.setVisibility(GONE); - } - } -} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextInfoPrivacyCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextInfoPrivacyCell.java index b16c84c70..6c8bcffa6 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextInfoPrivacyCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextInfoPrivacyCell.java @@ -25,10 +25,10 @@ public class TextInfoPrivacyCell extends FrameLayout { super(context); textView = new TextView(context); - textView.setTextColor(0xffa3a3a3); - textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13); + textView.setTextColor(0xff808080); + textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); textView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); - textView.setPadding(0, AndroidUtilities.dp(6), 0, AndroidUtilities.dp(16)); + textView.setPadding(0, AndroidUtilities.dp(10), 0, AndroidUtilities.dp(17)); addView(textView); LayoutParams layoutParams = (LayoutParams) textView.getLayoutParams(); layoutParams.width = LayoutParams.WRAP_CONTENT; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextSettingsCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextSettingsCell.java index e6c0414c2..e3c3ffb58 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextSettingsCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextSettingsCell.java @@ -74,7 +74,7 @@ public class TextSettingsCell extends FrameLayout { valueImageView = new ImageView(context); valueImageView.setScaleType(ImageView.ScaleType.CENTER); - valueImageView.setVisibility(GONE); + valueImageView.setVisibility(INVISIBLE); addView(valueImageView); layoutParams = (LayoutParams) valueImageView.getLayoutParams(); layoutParams.width = LayoutParams.WRAP_CONTENT; @@ -109,20 +109,20 @@ public class TextSettingsCell extends FrameLayout { public void setText(String text, boolean divider) { textView.setText(text); - valueTextView.setVisibility(GONE); - valueImageView.setVisibility(GONE); + valueTextView.setVisibility(INVISIBLE); + valueImageView.setVisibility(INVISIBLE); needDivider = divider; setWillNotDraw(!divider); } public void setTextAndValue(String text, String value, boolean divider) { textView.setText(text); - valueImageView.setVisibility(GONE); + valueImageView.setVisibility(INVISIBLE); if (value != null) { valueTextView.setText(value); valueTextView.setVisibility(VISIBLE); } else { - valueTextView.setVisibility(GONE); + valueTextView.setVisibility(INVISIBLE); } needDivider = divider; setWillNotDraw(!divider); @@ -130,12 +130,12 @@ public class TextSettingsCell extends FrameLayout { public void setTextAndIcon(String text, int resId, boolean divider) { textView.setText(text); - valueTextView.setVisibility(GONE); + valueTextView.setVisibility(INVISIBLE); if (resId != 0) { valueImageView.setVisibility(VISIBLE); valueImageView.setImageResource(resId); } else { - valueImageView.setVisibility(GONE); + valueImageView.setVisibility(INVISIBLE); } needDivider = divider; setWillNotDraw(!divider); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/UserCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/UserCell.java index c5bda3824..909be3b41 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/UserCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/UserCell.java @@ -54,7 +54,7 @@ public class UserCell extends FrameLayout { super(context); avatarImageView = new BackupImageView(context); - avatarImageView.imageReceiver.setRoundRadius(AndroidUtilities.dp(24)); + avatarImageView.setRoundRadius(AndroidUtilities.dp(24)); addView(avatarImageView); LayoutParams layoutParams = (LayoutParams) avatarImageView.getLayoutParams(); layoutParams.width = AndroidUtilities.dp(48); @@ -113,7 +113,7 @@ public class UserCell extends FrameLayout { imageView.setLayoutParams(layoutParams); checkBox = new CheckBox(context, R.drawable.round_check2); - checkBox.setVisibility(GONE); + checkBox.setVisibility(INVISIBLE); addView(checkBox); layoutParams = (LayoutParams) checkBox.getLayoutParams(); layoutParams.width = AndroidUtilities.dp(22); @@ -228,7 +228,7 @@ public class UserCell extends FrameLayout { } } - imageView.setVisibility(currentDrawable == 0 ? GONE : VISIBLE); + imageView.setVisibility(currentDrawable == 0 ? INVISIBLE : VISIBLE); imageView.setImageResource(currentDrawable); avatarImageView.setImage(photo, "50_50", avatarDrawable); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChangeChatNameActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChangeChatNameActivity.java index 5213e61c9..eb94acb69 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChangeChatNameActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChangeChatNameActivity.java @@ -9,6 +9,7 @@ package org.telegram.ui; import android.app.Activity; +import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.text.InputType; @@ -55,85 +56,78 @@ public class ChangeChatNameActivity extends BaseFragment { } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - actionBar.setTitle(LocaleController.getString("EditName", R.string.EditName)); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setAllowOverlayTitle(true); + actionBar.setTitle(LocaleController.getString("EditName", R.string.EditName)); + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); + } else if (id == done_button) { + if (firstNameField.getText().length() != 0) { + saveName(); finishFragment(); - } else if (id == done_button) { - if (firstNameField.getText().length() != 0) { - saveName(); - finishFragment(); - } } } - }); + } + }); - ActionBarMenu menu = actionBar.createMenu(); - doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); + ActionBarMenu menu = actionBar.createMenu(); + doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); - TLRPC.Chat currentChat = MessagesController.getInstance().getChat(chat_id); + TLRPC.Chat currentChat = MessagesController.getInstance().getChat(chat_id); - fragmentView = new LinearLayout(getParentActivity()); - fragmentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); - ((LinearLayout) fragmentView).setOrientation(LinearLayout.VERTICAL); - fragmentView.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { + fragmentView = new LinearLayout(context); + fragmentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + ((LinearLayout) fragmentView).setOrientation(LinearLayout.VERTICAL); + fragmentView.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + + firstNameField = new EditText(context); + firstNameField.setText(currentChat.title); + firstNameField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); + firstNameField.setHintTextColor(0xff979797); + firstNameField.setTextColor(0xff212121); + firstNameField.setMaxLines(3); + firstNameField.setPadding(0, 0, 0, 0); + firstNameField.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); + firstNameField.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); + firstNameField.setImeOptions(EditorInfo.IME_ACTION_DONE); + firstNameField.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); + AndroidUtilities.clearCursorDrawable(firstNameField); + firstNameField.setOnEditorActionListener(new TextView.OnEditorActionListener() { + @Override + public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { + if (i == EditorInfo.IME_ACTION_DONE && doneButton != null) { + doneButton.performClick(); return true; } - }); - - firstNameField = new EditText(getParentActivity()); - firstNameField.setText(currentChat.title); - firstNameField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - firstNameField.setHintTextColor(0xff979797); - firstNameField.setTextColor(0xff212121); - firstNameField.setMaxLines(3); - firstNameField.setPadding(0, 0, 0, 0); - firstNameField.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); - firstNameField.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); - firstNameField.setImeOptions(EditorInfo.IME_ACTION_DONE); - firstNameField.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); - AndroidUtilities.clearCursorDrawable(firstNameField); - firstNameField.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { - if (i == EditorInfo.IME_ACTION_DONE && doneButton != null) { - doneButton.performClick(); - return true; - } - return false; - } - }); - - ((LinearLayout) fragmentView).addView(firstNameField); - LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams)firstNameField.getLayoutParams(); - layoutParams.topMargin = AndroidUtilities.dp(24); - layoutParams.height = AndroidUtilities.dp(36); - layoutParams.leftMargin = AndroidUtilities.dp(24); - layoutParams.rightMargin = AndroidUtilities.dp(24); - layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; - firstNameField.setLayoutParams(layoutParams); - - if (chat_id > 0) { - firstNameField.setHint(LocaleController.getString("GroupName", R.string.GroupName)); - } else { - firstNameField.setHint(LocaleController.getString("EnterListName", R.string.EnterListName)); + return false; } - firstNameField.setSelection(firstNameField.length()); + }); + + ((LinearLayout) fragmentView).addView(firstNameField); + LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) firstNameField.getLayoutParams(); + layoutParams.topMargin = AndroidUtilities.dp(24); + layoutParams.height = AndroidUtilities.dp(36); + layoutParams.leftMargin = AndroidUtilities.dp(24); + layoutParams.rightMargin = AndroidUtilities.dp(24); + layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; + firstNameField.setLayoutParams(layoutParams); + + if (chat_id > 0) { + firstNameField.setHint(LocaleController.getString("GroupName", R.string.GroupName)); } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); - } + firstNameField.setHint(LocaleController.getString("EnterListName", R.string.EnterListName)); } + firstNameField.setSelection(firstNameField.length()); + return fragmentView; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChangeNameActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChangeNameActivity.java index 465b38ff1..4c672106e 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChangeNameActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChangeNameActivity.java @@ -9,6 +9,7 @@ package org.telegram.ui; import android.app.Activity; +import android.content.Context; import android.content.SharedPreferences; import android.text.InputType; import android.util.TypedValue; @@ -48,117 +49,111 @@ public class ChangeNameActivity extends BaseFragment { private final static int done_button = 1; @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - actionBar.setTitle(LocaleController.getString("EditName", R.string.EditName)); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setAllowOverlayTitle(true); + actionBar.setTitle(LocaleController.getString("EditName", R.string.EditName)); + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); + } else if (id == done_button) { + if (firstNameField.getText().length() != 0) { + saveName(); finishFragment(); - } else if (id == done_button) { - if (firstNameField.getText().length() != 0) { - saveName(); - finishFragment(); - } } } - }); - - ActionBarMenu menu = actionBar.createMenu(); - doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); - - TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); - if (user == null) { - user = UserConfig.getCurrentUser(); } + }); - fragmentView = new LinearLayout(getParentActivity()); - fragmentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); - ((LinearLayout) fragmentView).setOrientation(LinearLayout.VERTICAL); - fragmentView.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { + ActionBarMenu menu = actionBar.createMenu(); + doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); + + TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); + if (user == null) { + user = UserConfig.getCurrentUser(); + } + + fragmentView = new LinearLayout(context); + fragmentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + ((LinearLayout) fragmentView).setOrientation(LinearLayout.VERTICAL); + fragmentView.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + + firstNameField = new EditText(context); + firstNameField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); + firstNameField.setHintTextColor(0xff979797); + firstNameField.setTextColor(0xff212121); + firstNameField.setMaxLines(1); + firstNameField.setLines(1); + firstNameField.setSingleLine(true); + firstNameField.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); + firstNameField.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); + firstNameField.setImeOptions(EditorInfo.IME_ACTION_NEXT); + firstNameField.setHint(LocaleController.getString("FirstName", R.string.FirstName)); + AndroidUtilities.clearCursorDrawable(firstNameField); + ((LinearLayout) fragmentView).addView(firstNameField); + LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) firstNameField.getLayoutParams(); + layoutParams.topMargin = AndroidUtilities.dp(24); + layoutParams.height = AndroidUtilities.dp(36); + layoutParams.leftMargin = AndroidUtilities.dp(24); + layoutParams.rightMargin = AndroidUtilities.dp(24); + layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; + firstNameField.setLayoutParams(layoutParams); + firstNameField.setOnEditorActionListener(new TextView.OnEditorActionListener() { + @Override + public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { + if (i == EditorInfo.IME_ACTION_NEXT) { + lastNameField.requestFocus(); + lastNameField.setSelection(lastNameField.length()); return true; } - }); - - firstNameField = new EditText(getParentActivity()); - firstNameField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - firstNameField.setHintTextColor(0xff979797); - firstNameField.setTextColor(0xff212121); - firstNameField.setMaxLines(1); - firstNameField.setLines(1); - firstNameField.setSingleLine(true); - firstNameField.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); - firstNameField.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); - firstNameField.setImeOptions(EditorInfo.IME_ACTION_NEXT); - firstNameField.setHint(LocaleController.getString("FirstName", R.string.FirstName)); - AndroidUtilities.clearCursorDrawable(firstNameField); - ((LinearLayout) fragmentView).addView(firstNameField); - LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams)firstNameField.getLayoutParams(); - layoutParams.topMargin = AndroidUtilities.dp(24); - layoutParams.height = AndroidUtilities.dp(36); - layoutParams.leftMargin = AndroidUtilities.dp(24); - layoutParams.rightMargin = AndroidUtilities.dp(24); - layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; - firstNameField.setLayoutParams(layoutParams); - firstNameField.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { - if (i == EditorInfo.IME_ACTION_NEXT) { - lastNameField.requestFocus(); - lastNameField.setSelection(lastNameField.length()); - return true; - } - return false; - } - }); - - lastNameField = new EditText(getParentActivity()); - lastNameField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - lastNameField.setHintTextColor(0xff979797); - lastNameField.setTextColor(0xff212121); - lastNameField.setMaxLines(1); - lastNameField.setLines(1); - lastNameField.setSingleLine(true); - lastNameField.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); - lastNameField.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); - lastNameField.setImeOptions(EditorInfo.IME_ACTION_DONE); - lastNameField.setHint(LocaleController.getString("LastName", R.string.LastName)); - AndroidUtilities.clearCursorDrawable(lastNameField); - ((LinearLayout) fragmentView).addView(lastNameField); - layoutParams = (LinearLayout.LayoutParams)lastNameField.getLayoutParams(); - layoutParams.topMargin = AndroidUtilities.dp(16); - layoutParams.height = AndroidUtilities.dp(36); - layoutParams.leftMargin = AndroidUtilities.dp(24); - layoutParams.rightMargin = AndroidUtilities.dp(24); - layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; - lastNameField.setLayoutParams(layoutParams); - lastNameField.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { - if (i == EditorInfo.IME_ACTION_DONE) { - doneButton.performClick(); - return true; - } - return false; - } - }); - - if (user != null) { - firstNameField.setText(user.first_name); - firstNameField.setSelection(firstNameField.length()); - lastNameField.setText(user.last_name); + return false; } - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); + }); + + lastNameField = new EditText(context); + lastNameField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); + lastNameField.setHintTextColor(0xff979797); + lastNameField.setTextColor(0xff212121); + lastNameField.setMaxLines(1); + lastNameField.setLines(1); + lastNameField.setSingleLine(true); + lastNameField.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); + lastNameField.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); + lastNameField.setImeOptions(EditorInfo.IME_ACTION_DONE); + lastNameField.setHint(LocaleController.getString("LastName", R.string.LastName)); + AndroidUtilities.clearCursorDrawable(lastNameField); + ((LinearLayout) fragmentView).addView(lastNameField); + layoutParams = (LinearLayout.LayoutParams) lastNameField.getLayoutParams(); + layoutParams.topMargin = AndroidUtilities.dp(16); + layoutParams.height = AndroidUtilities.dp(36); + layoutParams.leftMargin = AndroidUtilities.dp(24); + layoutParams.rightMargin = AndroidUtilities.dp(24); + layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; + lastNameField.setLayoutParams(layoutParams); + lastNameField.setOnEditorActionListener(new TextView.OnEditorActionListener() { + @Override + public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { + if (i == EditorInfo.IME_ACTION_DONE) { + doneButton.performClick(); + return true; + } + return false; } + }); + + if (user != null) { + firstNameField.setText(user.first_name); + firstNameField.setSelection(firstNameField.length()); + lastNameField.setText(user.last_name); } + return fragmentView; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChangePhoneActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChangePhoneActivity.java index 18f5423df..01e54b550 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChangePhoneActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChangePhoneActivity.java @@ -25,7 +25,6 @@ import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; -import android.view.ViewGroup; import android.view.WindowManager; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.inputmethod.EditorInfo; @@ -101,80 +100,74 @@ public class ChangePhoneActivity extends BaseFragment { } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setTitle(LocaleController.getString("AppName", R.string.AppName)); - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == done_button) { - views[currentViewNum].onNextPressed(); - } else if (id == -1) { - finishFragment(); + public View createView(Context context, LayoutInflater inflater) { + actionBar.setTitle(LocaleController.getString("AppName", R.string.AppName)); + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == done_button) { + views[currentViewNum].onNextPressed(); + } else if (id == -1) { + finishFragment(); + } + } + }); + + ActionBarMenu menu = actionBar.createMenu(); + menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); + + fragmentView = new ScrollView(context); + ScrollView scrollView = (ScrollView) fragmentView; + scrollView.setFillViewport(true); + + FrameLayout frameLayout = new FrameLayout(context); + scrollView.addView(frameLayout); + ScrollView.LayoutParams layoutParams = (ScrollView.LayoutParams) frameLayout.getLayoutParams(); + layoutParams.width = ScrollView.LayoutParams.MATCH_PARENT; + layoutParams.height = ScrollView.LayoutParams.WRAP_CONTENT; + layoutParams.gravity = Gravity.TOP | Gravity.LEFT; + frameLayout.setLayoutParams(layoutParams); + + views[0] = new PhoneView(context); + views[0].setVisibility(View.VISIBLE); + frameLayout.addView(views[0]); + FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) views[0].getLayoutParams(); + layoutParams1.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams1.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams1.leftMargin = AndroidUtilities.dp(16); + layoutParams1.rightMargin = AndroidUtilities.dp(16); + layoutParams1.topMargin = AndroidUtilities.dp(30); + layoutParams1.gravity = Gravity.TOP | Gravity.LEFT; + views[0].setLayoutParams(layoutParams1); + + views[1] = new LoginActivitySmsView(context); + views[1].setVisibility(View.GONE); + frameLayout.addView(views[1]); + layoutParams1 = (FrameLayout.LayoutParams) views[1].getLayoutParams(); + layoutParams1.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams1.height = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams1.leftMargin = AndroidUtilities.dp(16); + layoutParams1.rightMargin = AndroidUtilities.dp(16); + layoutParams1.topMargin = AndroidUtilities.dp(30); + layoutParams1.gravity = Gravity.TOP | Gravity.LEFT; + views[1].setLayoutParams(layoutParams1); + + try { + if (views[0] == null || views[1] == null) { + FrameLayout parent = (FrameLayout) ((ScrollView) fragmentView).getChildAt(0); + for (int a = 0; a < views.length; a++) { + if (views[a] == null) { + views[a] = (SlideView) parent.getChildAt(a); } } - }); - - ActionBarMenu menu = actionBar.createMenu(); - menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); - - fragmentView = new ScrollView(getParentActivity()); - ScrollView scrollView = (ScrollView) fragmentView; - scrollView.setFillViewport(true); - - FrameLayout frameLayout = new FrameLayout(getParentActivity()); - scrollView.addView(frameLayout); - ScrollView.LayoutParams layoutParams = (ScrollView.LayoutParams) frameLayout.getLayoutParams(); - layoutParams.width = ScrollView.LayoutParams.MATCH_PARENT; - layoutParams.height = ScrollView.LayoutParams.WRAP_CONTENT; - layoutParams.gravity = Gravity.TOP | Gravity.LEFT; - frameLayout.setLayoutParams(layoutParams); - - views[0] = new PhoneView(getParentActivity()); - views[0].setVisibility(View.VISIBLE); - frameLayout.addView(views[0]); - FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) views[0].getLayoutParams(); - layoutParams1.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams1.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams1.leftMargin = AndroidUtilities.dp(16); - layoutParams1.rightMargin = AndroidUtilities.dp(16); - layoutParams1.topMargin = AndroidUtilities.dp(30); - layoutParams1.gravity = Gravity.TOP | Gravity.LEFT; - views[0].setLayoutParams(layoutParams1); - - views[1] = new LoginActivitySmsView(getParentActivity()); - views[1].setVisibility(View.GONE); - frameLayout.addView(views[1]); - layoutParams1 = (FrameLayout.LayoutParams) views[1].getLayoutParams(); - layoutParams1.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams1.height = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams1.leftMargin = AndroidUtilities.dp(16); - layoutParams1.rightMargin = AndroidUtilities.dp(16); - layoutParams1.topMargin = AndroidUtilities.dp(30); - layoutParams1.gravity = Gravity.TOP | Gravity.LEFT; - views[1].setLayoutParams(layoutParams1); - - try { - if (views[0] == null || views[1] == null) { - FrameLayout parent = (FrameLayout)((ScrollView) fragmentView).getChildAt(0); - for (int a = 0; a < views.length; a++) { - if (views[a] == null) { - views[a] = (SlideView)parent.getChildAt(a); - } - } - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } - - actionBar.setTitle(views[0].getHeaderName()); - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); } + } catch (Exception e) { + FileLog.e("tmessages", e); } + + actionBar.setTitle(views[0].getHeaderName()); + return fragmentView; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChangePhoneHelpActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChangePhoneHelpActivity.java index a2f952728..3da860185 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChangePhoneHelpActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChangePhoneHelpActivity.java @@ -9,13 +9,13 @@ package org.telegram.ui; import android.app.AlertDialog; +import android.content.Context; import android.content.DialogInterface; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; -import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; @@ -35,129 +35,122 @@ import org.telegram.ui.ActionBar.BaseFragment; public class ChangePhoneHelpActivity extends BaseFragment { @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - - TLRPC.User user = UserConfig.getCurrentUser(); - String value; - if (user != null && user.phone != null && user.phone.length() != 0) { - value = PhoneFormat.getInstance().format("+" + user.phone); - } else { - value = LocaleController.getString("NumberUnknown", R.string.NumberUnknown); - } - - actionBar.setTitle(value); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } - } - }); - - fragmentView = new RelativeLayout(getParentActivity()); - fragmentView.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - return true; - } - }); - - RelativeLayout relativeLayout = (RelativeLayout) fragmentView; - - ScrollView scrollView = new ScrollView(getParentActivity()); - relativeLayout.addView(scrollView); - RelativeLayout.LayoutParams layoutParams3 = (RelativeLayout.LayoutParams) scrollView.getLayoutParams(); - layoutParams3.width = RelativeLayout.LayoutParams.MATCH_PARENT; - layoutParams3.height = RelativeLayout.LayoutParams.WRAP_CONTENT; - layoutParams3.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE); - scrollView.setLayoutParams(layoutParams3); - - LinearLayout linearLayout = new LinearLayout(getParentActivity()); - linearLayout.setOrientation(LinearLayout.VERTICAL); - linearLayout.setPadding(0, AndroidUtilities.dp(20), 0, AndroidUtilities.dp(20)); - scrollView.addView(linearLayout); - ScrollView.LayoutParams layoutParams = (ScrollView.LayoutParams) linearLayout.getLayoutParams(); - layoutParams.width = ScrollView.LayoutParams.MATCH_PARENT; - layoutParams.height = ScrollView.LayoutParams.WRAP_CONTENT; - linearLayout.setLayoutParams(layoutParams); - - ImageView imageView = new ImageView(getParentActivity()); - imageView.setImageResource(R.drawable.phone_change); - linearLayout.addView(imageView); - LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams)imageView.getLayoutParams(); - layoutParams2.width = LinearLayout.LayoutParams.WRAP_CONTENT; - layoutParams2.height = LinearLayout.LayoutParams.WRAP_CONTENT; - layoutParams2.gravity = Gravity.CENTER_HORIZONTAL; - imageView.setLayoutParams(layoutParams2); - - TextView textView = new TextView(getParentActivity()); - textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - textView.setGravity(Gravity.CENTER_HORIZONTAL); - textView.setTextColor(0xff212121); - - try { - textView.setText(AndroidUtilities.replaceBold(LocaleController.getString("PhoneNumberHelp", R.string.PhoneNumberHelp))); - } catch (Exception e) { - FileLog.e("tmessages", e); - textView.setText(LocaleController.getString("PhoneNumberHelp", R.string.PhoneNumberHelp)); - } - linearLayout.addView(textView); - layoutParams2 = (LinearLayout.LayoutParams)textView.getLayoutParams(); - layoutParams2.width = LinearLayout.LayoutParams.WRAP_CONTENT; - layoutParams2.height = LinearLayout.LayoutParams.WRAP_CONTENT; - layoutParams2.gravity = Gravity.CENTER_HORIZONTAL; - layoutParams2.leftMargin = AndroidUtilities.dp(20); - layoutParams2.rightMargin = AndroidUtilities.dp(20); - layoutParams2.topMargin = AndroidUtilities.dp(56); - textView.setLayoutParams(layoutParams2); - - textView = new TextView(getParentActivity()); - textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - textView.setGravity(Gravity.CENTER_HORIZONTAL); - textView.setTextColor(0xff4d83b3); - textView.setText(LocaleController.getString("PhoneNumberChange", R.string.PhoneNumberChange)); - textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - textView.setPadding(0, AndroidUtilities.dp(10), 0, AndroidUtilities.dp(10)); - linearLayout.addView(textView); - layoutParams2 = (LinearLayout.LayoutParams)textView.getLayoutParams(); - layoutParams2.width = LinearLayout.LayoutParams.WRAP_CONTENT; - layoutParams2.height = LinearLayout.LayoutParams.WRAP_CONTENT; - layoutParams2.gravity = Gravity.CENTER_HORIZONTAL; - layoutParams2.leftMargin = AndroidUtilities.dp(20); - layoutParams2.rightMargin = AndroidUtilities.dp(20); - layoutParams2.topMargin = AndroidUtilities.dp(46); - textView.setLayoutParams(layoutParams2); - - textView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setMessage(LocaleController.getString("PhoneNumberAlert", R.string.PhoneNumberAlert)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - presentFragment(new ChangePhoneActivity(), true); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } - }); + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setAllowOverlayTitle(true); + TLRPC.User user = UserConfig.getCurrentUser(); + String value; + if (user != null && user.phone != null && user.phone.length() != 0) { + value = PhoneFormat.getInstance().format("+" + user.phone); } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); - } + value = LocaleController.getString("NumberUnknown", R.string.NumberUnknown); } + + actionBar.setTitle(value); + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); + } + } + }); + + fragmentView = new RelativeLayout(context); + fragmentView.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + + RelativeLayout relativeLayout = (RelativeLayout) fragmentView; + + ScrollView scrollView = new ScrollView(context); + relativeLayout.addView(scrollView); + RelativeLayout.LayoutParams layoutParams3 = (RelativeLayout.LayoutParams) scrollView.getLayoutParams(); + layoutParams3.width = RelativeLayout.LayoutParams.MATCH_PARENT; + layoutParams3.height = RelativeLayout.LayoutParams.WRAP_CONTENT; + layoutParams3.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE); + scrollView.setLayoutParams(layoutParams3); + + LinearLayout linearLayout = new LinearLayout(context); + linearLayout.setOrientation(LinearLayout.VERTICAL); + linearLayout.setPadding(0, AndroidUtilities.dp(20), 0, AndroidUtilities.dp(20)); + scrollView.addView(linearLayout); + ScrollView.LayoutParams layoutParams = (ScrollView.LayoutParams) linearLayout.getLayoutParams(); + layoutParams.width = ScrollView.LayoutParams.MATCH_PARENT; + layoutParams.height = ScrollView.LayoutParams.WRAP_CONTENT; + linearLayout.setLayoutParams(layoutParams); + + ImageView imageView = new ImageView(context); + imageView.setImageResource(R.drawable.phone_change); + linearLayout.addView(imageView); + LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) imageView.getLayoutParams(); + layoutParams2.width = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.height = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.gravity = Gravity.CENTER_HORIZONTAL; + imageView.setLayoutParams(layoutParams2); + + TextView textView = new TextView(context); + textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); + textView.setGravity(Gravity.CENTER_HORIZONTAL); + textView.setTextColor(0xff212121); + + try { + textView.setText(AndroidUtilities.replaceTags(LocaleController.getString("PhoneNumberHelp", R.string.PhoneNumberHelp))); + } catch (Exception e) { + FileLog.e("tmessages", e); + textView.setText(LocaleController.getString("PhoneNumberHelp", R.string.PhoneNumberHelp)); + } + linearLayout.addView(textView); + layoutParams2 = (LinearLayout.LayoutParams) textView.getLayoutParams(); + layoutParams2.width = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.height = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.gravity = Gravity.CENTER_HORIZONTAL; + layoutParams2.leftMargin = AndroidUtilities.dp(20); + layoutParams2.rightMargin = AndroidUtilities.dp(20); + layoutParams2.topMargin = AndroidUtilities.dp(56); + textView.setLayoutParams(layoutParams2); + + textView = new TextView(context); + textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); + textView.setGravity(Gravity.CENTER_HORIZONTAL); + textView.setTextColor(0xff4d83b3); + textView.setText(LocaleController.getString("PhoneNumberChange", R.string.PhoneNumberChange)); + textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); + textView.setPadding(0, AndroidUtilities.dp(10), 0, AndroidUtilities.dp(10)); + linearLayout.addView(textView); + layoutParams2 = (LinearLayout.LayoutParams) textView.getLayoutParams(); + layoutParams2.width = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.height = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.gravity = Gravity.CENTER_HORIZONTAL; + layoutParams2.leftMargin = AndroidUtilities.dp(20); + layoutParams2.rightMargin = AndroidUtilities.dp(20); + layoutParams2.topMargin = AndroidUtilities.dp(46); + textView.setLayoutParams(layoutParams2); + + textView.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (getParentActivity() == null) { + return; + } + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + builder.setMessage(LocaleController.getString("PhoneNumberAlert", R.string.PhoneNumberAlert)); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + presentFragment(new ChangePhoneActivity(), true); + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } + }); + return fragmentView; } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChangeUsernameActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChangeUsernameActivity.java index 0f5d84290..e0169de83 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChangeUsernameActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChangeUsernameActivity.java @@ -11,6 +11,7 @@ package org.telegram.ui; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; +import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.text.Editable; @@ -61,130 +62,124 @@ public class ChangeUsernameActivity extends BaseFragment { private final static int done_button = 1; @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - actionBar.setTitle(LocaleController.getString("Username", R.string.Username)); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } else if (id == done_button) { - saveName(); - } + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setAllowOverlayTitle(true); + actionBar.setTitle(LocaleController.getString("Username", R.string.Username)); + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); + } else if (id == done_button) { + saveName(); } - }); - - ActionBarMenu menu = actionBar.createMenu(); - doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); - - TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); - if (user == null) { - user = UserConfig.getCurrentUser(); } + }); - fragmentView = new LinearLayout(getParentActivity()); - fragmentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); - ((LinearLayout) fragmentView).setOrientation(LinearLayout.VERTICAL); - fragmentView.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { + ActionBarMenu menu = actionBar.createMenu(); + doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); + + TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); + if (user == null) { + user = UserConfig.getCurrentUser(); + } + + fragmentView = new LinearLayout(context); + fragmentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + ((LinearLayout) fragmentView).setOrientation(LinearLayout.VERTICAL); + fragmentView.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + + firstNameField = new EditText(context); + firstNameField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); + firstNameField.setHintTextColor(0xff979797); + firstNameField.setTextColor(0xff212121); + firstNameField.setMaxLines(1); + firstNameField.setLines(1); + firstNameField.setPadding(0, 0, 0, 0); + firstNameField.setSingleLine(true); + firstNameField.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); + firstNameField.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); + firstNameField.setImeOptions(EditorInfo.IME_ACTION_DONE); + firstNameField.setHint(LocaleController.getString("UsernamePlaceholder", R.string.UsernamePlaceholder)); + AndroidUtilities.clearCursorDrawable(firstNameField); + firstNameField.setOnEditorActionListener(new TextView.OnEditorActionListener() { + @Override + public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { + if (i == EditorInfo.IME_ACTION_DONE && doneButton != null) { + doneButton.performClick(); return true; } - }); - - firstNameField = new EditText(getParentActivity()); - firstNameField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - firstNameField.setHintTextColor(0xff979797); - firstNameField.setTextColor(0xff212121); - firstNameField.setMaxLines(1); - firstNameField.setLines(1); - firstNameField.setPadding(0, 0, 0, 0); - firstNameField.setSingleLine(true); - firstNameField.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); - firstNameField.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); - firstNameField.setImeOptions(EditorInfo.IME_ACTION_DONE); - firstNameField.setHint(LocaleController.getString("UsernamePlaceholder", R.string.UsernamePlaceholder)); - AndroidUtilities.clearCursorDrawable(firstNameField); - firstNameField.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { - if (i == EditorInfo.IME_ACTION_DONE && doneButton != null) { - doneButton.performClick(); - return true; - } - return false; - } - }); - - ((LinearLayout) fragmentView).addView(firstNameField); - LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams)firstNameField.getLayoutParams(); - layoutParams.topMargin = AndroidUtilities.dp(24); - layoutParams.height = AndroidUtilities.dp(36); - layoutParams.leftMargin = AndroidUtilities.dp(24); - layoutParams.rightMargin = AndroidUtilities.dp(24); - layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; - firstNameField.setLayoutParams(layoutParams); - - if (user != null && user.username != null && user.username.length() > 0) { - firstNameField.setText(user.username); - firstNameField.setSelection(firstNameField.length()); + return false; } + }); - checkTextView = new TextView(getParentActivity()); - checkTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); - checkTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); - ((LinearLayout) fragmentView).addView(checkTextView); - layoutParams = (LinearLayout.LayoutParams)checkTextView.getLayoutParams(); - layoutParams.topMargin = AndroidUtilities.dp(12); - layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT; - layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT; - layoutParams.gravity = LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT; - layoutParams.leftMargin = AndroidUtilities.dp(24); - layoutParams.rightMargin = AndroidUtilities.dp(24); - checkTextView.setLayoutParams(layoutParams); + ((LinearLayout) fragmentView).addView(firstNameField); + LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) firstNameField.getLayoutParams(); + layoutParams.topMargin = AndroidUtilities.dp(24); + layoutParams.height = AndroidUtilities.dp(36); + layoutParams.leftMargin = AndroidUtilities.dp(24); + layoutParams.rightMargin = AndroidUtilities.dp(24); + layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; + firstNameField.setLayoutParams(layoutParams); - TextView helpTextView = new TextView(getParentActivity()); - helpTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); - helpTextView.setTextColor(0xff6d6d72); - helpTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); - helpTextView.setText(Html.fromHtml(LocaleController.getString("UsernameHelp", R.string.UsernameHelp))); - ((LinearLayout) fragmentView).addView(helpTextView); - layoutParams = (LinearLayout.LayoutParams)helpTextView.getLayoutParams(); - layoutParams.topMargin = AndroidUtilities.dp(10); - layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT; - layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT; - layoutParams.gravity = LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT; - layoutParams.leftMargin = AndroidUtilities.dp(24); - layoutParams.rightMargin = AndroidUtilities.dp(24); - helpTextView.setLayoutParams(layoutParams); - - firstNameField.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { - - } - - @Override - public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { - checkUserName(firstNameField.getText().toString(), false); - } - - @Override - public void afterTextChanged(Editable editable) { - - } - }); - - checkTextView.setVisibility(View.GONE); - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); - } + if (user != null && user.username != null && user.username.length() > 0) { + firstNameField.setText(user.username); + firstNameField.setSelection(firstNameField.length()); } + + checkTextView = new TextView(context); + checkTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); + checkTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); + ((LinearLayout) fragmentView).addView(checkTextView); + layoutParams = (LinearLayout.LayoutParams) checkTextView.getLayoutParams(); + layoutParams.topMargin = AndroidUtilities.dp(12); + layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams.gravity = LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT; + layoutParams.leftMargin = AndroidUtilities.dp(24); + layoutParams.rightMargin = AndroidUtilities.dp(24); + checkTextView.setLayoutParams(layoutParams); + + TextView helpTextView = new TextView(context); + helpTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); + helpTextView.setTextColor(0xff6d6d72); + helpTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); + helpTextView.setText(AndroidUtilities.replaceTags(LocaleController.getString("UsernameHelp", R.string.UsernameHelp))); + ((LinearLayout) fragmentView).addView(helpTextView); + layoutParams = (LinearLayout.LayoutParams) helpTextView.getLayoutParams(); + layoutParams.topMargin = AndroidUtilities.dp(10); + layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams.gravity = LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT; + layoutParams.leftMargin = AndroidUtilities.dp(24); + layoutParams.rightMargin = AndroidUtilities.dp(24); + helpTextView.setLayoutParams(layoutParams); + + firstNameField.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { + + } + + @Override + public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { + checkUserName(firstNameField.getText().toString(), false); + } + + @Override + public void afterTextChanged(Editable editable) { + + } + }); + + checkTextView.setVisibility(View.GONE); + return fragmentView; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java index ce9cd1f9c..801c41d59 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java @@ -27,7 +27,6 @@ import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; import android.support.v7.widget.LinearLayoutManager; -import android.text.Html; import android.text.TextUtils; import android.util.Base64; import android.util.SparseArray; @@ -166,6 +165,12 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not private MessageObject replyingMessageObject; private boolean paused = true; private boolean readWhenResume = false; + private TLRPC.FileLocation replyImageLocation; + private long linkSearchRequestId; + private TLRPC.WebPage foundWebPage; + private String pendingLinkSearchString; + private Runnable pendingWebPageTimeoutRunnable; + private Runnable waitingForCharaterEnterRunnable; private boolean openAnimationEnded = false; @@ -381,7 +386,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not return false; } } - dialog_id = ((long)encId) << 32; + dialog_id = ((long) encId) << 32; maxMessageId = Integer.MIN_VALUE; minMessageId = Integer.MAX_VALUE; MediaController.getInstance().startMediaObserver(); @@ -415,6 +420,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not NotificationCenter.getInstance().addObserver(this, NotificationCenter.replaceMessagesObjects); NotificationCenter.getInstance().addObserver(this, NotificationCenter.notificationsSettingsUpdated); NotificationCenter.getInstance().addObserver(this, NotificationCenter.didLoadedReplyMessages); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.didReceivedWebpages); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.didReceivedWebpagesInUpdates); super.onFragmentCreate(); @@ -451,12 +458,6 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (chatActivityEnterView != null) { chatActivityEnterView.onDestroy(); } - if (avatarImageView != null) { - avatarImageView.setImageDrawable(null); - } - if (replyImageView != null) { - replyImageView.setImageDrawable(null); - } NotificationCenter.getInstance().removeObserver(this, NotificationCenter.messagesDidLoaded); NotificationCenter.getInstance().removeObserver(this, NotificationCenter.emojiDidLoaded); NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces); @@ -483,6 +484,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not NotificationCenter.getInstance().removeObserver(this, NotificationCenter.replaceMessagesObjects); NotificationCenter.getInstance().removeObserver(this, NotificationCenter.notificationsSettingsUpdated); NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didLoadedReplyMessages); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didReceivedWebpages); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didReceivedWebpagesInUpdates); + if (AndroidUtilities.isTablet()) { NotificationCenter.getInstance().postNotificationName(NotificationCenter.openedChatChanged, dialog_id, true); } @@ -503,1444 +507,1531 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - lastPrintString = null; - lastStatus = null; + public View createView(Context context, LayoutInflater inflater) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(final int id) { - if (id == attach_photo || id == attach_gallery || id == attach_document || id == attach_video) { - String action = null; - if (currentChat != null) { - if (currentChat.participants_count > MessagesController.getInstance().groupBigSize) { - if (id == attach_photo || id == attach_gallery) { - action = "bigchat_upload_photo"; - } else { - action = "bigchat_upload_document"; - } + lastPrintString = null; + lastStatus = null; + hasOwnBackground = true; + + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(final int id) { + if (id == attach_photo || id == attach_gallery || id == attach_document || id == attach_video) { + String action = null; + if (currentChat != null) { + if (currentChat.participants_count > MessagesController.getInstance().groupBigSize) { + if (id == attach_photo || id == attach_gallery) { + action = "bigchat_upload_photo"; } else { - if (id == attach_photo || id == attach_gallery) { - action = "chat_upload_photo"; - } else { - action = "chat_upload_document"; - } + action = "bigchat_upload_document"; } } else { if (id == attach_photo || id == attach_gallery) { - action = "pm_upload_photo"; + action = "chat_upload_photo"; } else { - action = "pm_upload_document"; + action = "chat_upload_document"; } } - if (action != null && !MessagesController.isFeatureEnabled(action, ChatActivity.this)) { - return; + } else { + if (id == attach_photo || id == attach_gallery) { + action = "pm_upload_photo"; + } else { + action = "pm_upload_document"; } } - if (id == -1) { - finishFragment(); - } else if (id == -2) { - selectedMessagesIds.clear(); - selectedMessagesCanCopyIds.clear(); - actionBar.hideActionMode(); - updateVisibleRows(); - } else if (id == attach_photo) { - try { - Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); - File image = Utilities.generatePicturePath(); - if (image != null) { - takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image)); - currentPicturePath = image.getAbsolutePath(); - } - startActivityForResult(takePictureIntent, 0); - } catch (Exception e) { - FileLog.e("tmessages", e); + if (action != null && !MessagesController.isFeatureEnabled(action, ChatActivity.this)) { + return; + } + } + if (id == -1) { + finishFragment(); + } else if (id == -2) { + selectedMessagesIds.clear(); + selectedMessagesCanCopyIds.clear(); + actionBar.hideActionMode(); + updateVisibleRows(); + } else if (id == attach_photo) { + try { + Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); + File image = Utilities.generatePicturePath(); + if (image != null) { + takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image)); + currentPicturePath = image.getAbsolutePath(); + } + startActivityForResult(takePictureIntent, 0); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } else if (id == attach_gallery) { + PhotoAlbumPickerActivity fragment = new PhotoAlbumPickerActivity(false); + fragment.setDelegate(new PhotoAlbumPickerActivity.PhotoAlbumPickerActivityDelegate() { + @Override + public void didSelectPhotos(ArrayList photos, ArrayList webPhotos) { + SendMessagesHelper.prepareSendingPhotos(photos, null, dialog_id, replyingMessageObject); + SendMessagesHelper.prepareSendingPhotosSearch(webPhotos, dialog_id, replyingMessageObject); + showReplyPanel(false, null, null, null, false, true); } - } else if (id == attach_gallery) { - PhotoAlbumPickerActivity fragment = new PhotoAlbumPickerActivity(false); - fragment.setDelegate(new PhotoAlbumPickerActivity.PhotoAlbumPickerActivityDelegate() { - @Override - public void didSelectPhotos(ArrayList photos, ArrayList webPhotos) { - SendMessagesHelper.prepareSendingPhotos(photos, null, dialog_id, replyingMessageObject); - SendMessagesHelper.prepareSendingPhotosSearch(webPhotos, dialog_id, replyingMessageObject); - showReplyForMessageObjectOrForward(false, null, null, true); - } - @Override - public void startPhotoSelectActivity() { - try { - Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); - photoPickerIntent.setType("image/*"); - startActivityForResult(photoPickerIntent, 1); - } catch (Exception e) { - FileLog.e("tmessages", e); - } + @Override + public void startPhotoSelectActivity() { + try { + Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); + photoPickerIntent.setType("image/*"); + startActivityForResult(photoPickerIntent, 1); + } catch (Exception e) { + FileLog.e("tmessages", e); } - }); - presentFragment(fragment); - } else if (id == attach_video) { - try { - Intent pickIntent = new Intent(); - pickIntent.setType("video/*"); - pickIntent.setAction(Intent.ACTION_GET_CONTENT); - pickIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, (long) (1024 * 1024 * 1536)); - Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); - File video = Utilities.generateVideoPath(); - if (video != null) { - if (Build.VERSION.SDK_INT >= 18) { - takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(video)); - } - takeVideoIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, (long) (1024 * 1024 * 1536)); - currentPicturePath = video.getAbsolutePath(); + } + }); + presentFragment(fragment); + } else if (id == attach_video) { + try { + Intent pickIntent = new Intent(); + pickIntent.setType("video/*"); + pickIntent.setAction(Intent.ACTION_GET_CONTENT); + pickIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, (long) (1024 * 1024 * 1536)); + Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); + File video = Utilities.generateVideoPath(); + if (video != null) { + if (Build.VERSION.SDK_INT >= 18) { + takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(video)); } - Intent chooserIntent = Intent.createChooser(pickIntent, null); - chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{takeVideoIntent}); + takeVideoIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, (long) (1024 * 1024 * 1536)); + currentPicturePath = video.getAbsolutePath(); + } + Intent chooserIntent = Intent.createChooser(pickIntent, null); + chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{takeVideoIntent}); - startActivityForResult(chooserIntent, 2); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } else if (id == attach_location) { - if (!isGoogleMapsInstalled()) { - return; - } - LocationActivity fragment = new LocationActivity(); - fragment.setDelegate(new LocationActivity.LocationActivityDelegate() { - @Override - public void didSelectLocation(double latitude, double longitude) { - SendMessagesHelper.getInstance().sendMessage(latitude, longitude, dialog_id, replyingMessageObject); - moveScrollToLastMessage(); - showReplyForMessageObjectOrForward(false, null, null, true); - if (paused) { - scrollToTopOnResume = true; - } - } - }); - presentFragment(fragment); - } else if (id == attach_document) { - DocumentSelectActivity fragment = new DocumentSelectActivity(); - fragment.setDelegate(new DocumentSelectActivity.DocumentSelectActivityDelegate() { - @Override - public void didSelectFiles(DocumentSelectActivity activity, ArrayList files) { - activity.finishFragment(); - SendMessagesHelper.prepareSendingDocuments(files, files, null, null, dialog_id, replyingMessageObject); - showReplyForMessageObjectOrForward(false, null, null, true); + startActivityForResult(chooserIntent, 2); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } else if (id == attach_location) { + if (!isGoogleMapsInstalled()) { + return; + } + LocationActivity fragment = new LocationActivity(); + fragment.setDelegate(new LocationActivity.LocationActivityDelegate() { + @Override + public void didSelectLocation(double latitude, double longitude) { + SendMessagesHelper.getInstance().sendMessage(latitude, longitude, dialog_id, replyingMessageObject); + moveScrollToLastMessage(); + showReplyPanel(false, null, null, null, false, true); + if (paused) { + scrollToTopOnResume = true; } + } + }); + presentFragment(fragment); + } else if (id == attach_document) { + DocumentSelectActivity fragment = new DocumentSelectActivity(); + fragment.setDelegate(new DocumentSelectActivity.DocumentSelectActivityDelegate() { + @Override + public void didSelectFiles(DocumentSelectActivity activity, ArrayList files) { + activity.finishFragment(); + SendMessagesHelper.prepareSendingDocuments(files, files, null, null, dialog_id, replyingMessageObject); + showReplyPanel(false, null, null, null, false, true); + } - @Override - public void startDocumentSelectActivity() { - try { - Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); - photoPickerIntent.setType("*/*"); - startActivityForResult(photoPickerIntent, 21); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - }); - presentFragment(fragment); - } else if (id == copy) { - String str = ""; - ArrayList ids = new ArrayList<>(selectedMessagesCanCopyIds.keySet()); - if (currentEncryptedChat == null) { - Collections.sort(ids); - } else { - Collections.sort(ids, Collections.reverseOrder()); - } - for (Integer messageId : ids) { - MessageObject messageObject = selectedMessagesCanCopyIds.get(messageId); - if (str.length() != 0) { - str += "\n"; - } - if (messageObject.messageOwner.message != null) { - str += messageObject.messageOwner.message; - } else { - str += messageObject.messageText; + @Override + public void startDocumentSelectActivity() { + try { + Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); + photoPickerIntent.setType("*/*"); + startActivityForResult(photoPickerIntent, 21); + } catch (Exception e) { + FileLog.e("tmessages", e); } } + }); + presentFragment(fragment); + } else if (id == copy) { + String str = ""; + ArrayList ids = new ArrayList<>(selectedMessagesCanCopyIds.keySet()); + if (currentEncryptedChat == null) { + Collections.sort(ids); + } else { + Collections.sort(ids, Collections.reverseOrder()); + } + for (Integer messageId : ids) { + MessageObject messageObject = selectedMessagesCanCopyIds.get(messageId); if (str.length() != 0) { - if (Build.VERSION.SDK_INT < 11) { - android.text.ClipboardManager clipboard = (android.text.ClipboardManager) ApplicationLoader.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE); - clipboard.setText(str); - } else { - android.content.ClipboardManager clipboard = (android.content.ClipboardManager) ApplicationLoader.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE); - android.content.ClipData clip = android.content.ClipData.newPlainText("label", str); - clipboard.setPrimaryClip(clip); - } + str += "\n"; } - selectedMessagesIds.clear(); - selectedMessagesCanCopyIds.clear(); - actionBar.hideActionMode(); - updateVisibleRows(); - } else if (id == delete) { - if (getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setMessage(LocaleController.formatString("AreYouSureDeleteMessages", R.string.AreYouSureDeleteMessages, LocaleController.formatPluralString("messages", selectedMessagesIds.size()))); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - ArrayList ids = new ArrayList<>(selectedMessagesIds.keySet()); - ArrayList random_ids = null; - if (currentEncryptedChat != null) { - random_ids = new ArrayList<>(); - for (HashMap.Entry entry : selectedMessagesIds.entrySet()) { - MessageObject msg = entry.getValue(); - if (msg.messageOwner.random_id != 0 && msg.type != 10) { - random_ids.add(msg.messageOwner.random_id); - } - } - } - MessagesController.getInstance().deleteMessages(ids, random_ids, currentEncryptedChat); - actionBar.hideActionMode(); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } else if (id == forward) { - Bundle args = new Bundle(); - args.putBoolean("onlySelect", true); - args.putBoolean("serverOnly", true); - MessagesActivity fragment = new MessagesActivity(args); - fragment.setDelegate(ChatActivity.this); - presentFragment(fragment); - } else if (id == chat_enc_timer) { - if (getParentActivity() == null) { - return; - } - showAlertDialog(AndroidUtilities.buildTTLAlert(getParentActivity(), currentEncryptedChat)); - } else if (id == clear_history || id == delete_chat) { - if (getParentActivity() == null) { - return; - } - final boolean isChat = (int)dialog_id < 0 && (int)(dialog_id >> 32) != 1; - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - if (id == clear_history) { - builder.setMessage(LocaleController.getString("AreYouSureClearHistory", R.string.AreYouSureClearHistory)); + if (messageObject.messageOwner.message != null) { + str += messageObject.messageOwner.message; } else { - if (isChat) { - builder.setMessage(LocaleController.getString("AreYouSureDeleteAndExit", R.string.AreYouSureDeleteAndExit)); - } else { - builder.setMessage(LocaleController.getString("AreYouSureDeleteThisChat", R.string.AreYouSureDeleteThisChat)); - } + str += messageObject.messageText; } - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - MessagesController.getInstance().deleteDialog(dialog_id, 0, id == clear_history); - if (id != clear_history) { - if (isChat) { - MessagesController.getInstance().deleteUserFromChat((int) -dialog_id, MessagesController.getInstance().getUser(UserConfig.getClientUserId()), null); - } - finishFragment(); - } - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } else if (id == share_contact) { - if (currentUser == null || getParentActivity() == null) { - return; - } - if (currentUser.phone != null && currentUser.phone.length() != 0) { - Bundle args = new Bundle(); - args.putInt("user_id", currentUser.id); - args.putBoolean("addContact", true); - presentFragment(new ContactAddActivity(args)); + } + if (str.length() != 0) { + if (Build.VERSION.SDK_INT < 11) { + android.text.ClipboardManager clipboard = (android.text.ClipboardManager) ApplicationLoader.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE); + clipboard.setText(str); } else { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setMessage(LocaleController.getString("AreYouSureShareMyContactInfo", R.string.AreYouSureShareMyContactInfo)); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - SendMessagesHelper.getInstance().sendMessage(UserConfig.getCurrentUser(), dialog_id, replyingMessageObject); - moveScrollToLastMessage(); - showReplyForMessageObjectOrForward(false, null, null, true); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } - } else if (id == mute) { - boolean muted = MessagesController.getInstance().isDialogMuted(dialog_id); - if (!muted) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("Notifications", R.string.Notifications)); - CharSequence[] items = new CharSequence[]{ - LocaleController.formatString("MuteFor", R.string.MuteFor, LocaleController.formatPluralString("Hours", 1)), - LocaleController.formatString("MuteFor", R.string.MuteFor, LocaleController.formatPluralString("Hours", 8)), - LocaleController.formatString("MuteFor", R.string.MuteFor, LocaleController.formatPluralString("Days", 2)), - LocaleController.getString("MuteDisable", R.string.MuteDisable) - }; - builder.setItems(items, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - int untilTime = ConnectionsManager.getInstance().getCurrentTime(); - if (i == 0) { - untilTime += 60 * 60; - } else if (i == 1) { - untilTime += 60 * 60 * 8; - } else if (i == 2) { - untilTime += 60 * 60 * 48; - } else if (i == 3) { - untilTime = Integer.MAX_VALUE; - } - - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - long flags = 0; - if (i == 3) { - editor.putInt("notify2_" + dialog_id, 2); - flags = 1; - } else { - editor.putInt("notify2_" + dialog_id, 3); - editor.putInt("notifyuntil_" + dialog_id, untilTime); - flags = ((long)untilTime << 32) | 1; - } - MessagesStorage.getInstance().setDialogFlags(dialog_id, flags); - editor.commit(); - TLRPC.TL_dialog dialog = MessagesController.getInstance().dialogs_dict.get(dialog_id); - if (dialog != null) { - dialog.notify_settings = new TLRPC.TL_peerNotifySettings(); - dialog.notify_settings.mute_until = untilTime; - } - NotificationsController.updateServerNotificationsSettings(dialog_id); - } - } - ); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } else { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - editor.putInt("notify2_" + dialog_id, 0); - MessagesStorage.getInstance().setDialogFlags(dialog_id, 0); - editor.commit(); - TLRPC.TL_dialog dialog = MessagesController.getInstance().dialogs_dict.get(dialog_id); - if (dialog != null) { - dialog.notify_settings = new TLRPC.TL_peerNotifySettings(); - } - NotificationsController.updateServerNotificationsSettings(dialog_id); - } - } else if (id == reply) { - if (selectedMessagesIds.size() == 1) { - ArrayList ids = new ArrayList<>(selectedMessagesIds.keySet()); - MessageObject messageObject = messagesDict.get(ids.get(0)); - if (messageObject != null && messageObject.messageOwner.id > 0) { - showReplyForMessageObjectOrForward(true, messageObject, null, true); - } - } - selectedMessagesIds.clear(); - selectedMessagesCanCopyIds.clear(); - actionBar.hideActionMode(); - updateVisibleRows(); - } - } - }); - - avatarContainer = new FrameLayoutFixed(getParentActivity()); - avatarContainer.setBackgroundResource(R.drawable.bar_selector); - avatarContainer.setPadding(AndroidUtilities.dp(8), 0, AndroidUtilities.dp(8), 0); - actionBar.addView(avatarContainer); - FrameLayout.LayoutParams layoutParams2 = (FrameLayout.LayoutParams) avatarContainer.getLayoutParams(); - layoutParams2.height = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams2.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams2.rightMargin = AndroidUtilities.dp(40); - layoutParams2.leftMargin = AndroidUtilities.dp(56); - layoutParams2.gravity = Gravity.TOP | Gravity.LEFT; - avatarContainer.setLayoutParams(layoutParams2); - avatarContainer.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (currentUser != null) { - Bundle args = new Bundle(); - args.putInt("user_id", currentUser.id); - if (currentEncryptedChat != null) { - args.putLong("dialog_id", dialog_id); - } - presentFragment(new ProfileActivity(args)); - } else if (currentChat != null) { - Bundle args = new Bundle(); - args.putInt("chat_id", currentChat.id); - ProfileActivity fragment = new ProfileActivity(args); - fragment.setChatInfo(info); - presentFragment(fragment); - } - } - }); - - if (currentChat != null) { - int count = currentChat.participants_count; - if (info != null) { - count = info.participants.size(); - } - if (count == 0 || currentChat.left || currentChat instanceof TLRPC.TL_chatForbidden || info != null && info instanceof TLRPC.TL_chatParticipantsForbidden) { - avatarContainer.setEnabled(false); - } - } - - avatarImageView = new BackupImageView(getParentActivity()); - avatarImageView.imageReceiver.setRoundRadius(AndroidUtilities.dp(21)); - avatarImageView.processDetach = false; - avatarContainer.addView(avatarImageView); - layoutParams2 = (FrameLayout.LayoutParams) avatarImageView.getLayoutParams(); - layoutParams2.width = AndroidUtilities.dp(42); - layoutParams2.height = AndroidUtilities.dp(42); - layoutParams2.topMargin = AndroidUtilities.dp(3); - layoutParams2.gravity = Gravity.TOP | Gravity.LEFT; - avatarImageView.setLayoutParams(layoutParams2); - - if (currentEncryptedChat != null) { - timeItem = new ImageView(getParentActivity()); - timeItem.setPadding(AndroidUtilities.dp(10), AndroidUtilities.dp(10), AndroidUtilities.dp(5), AndroidUtilities.dp(5)); - timeItem.setScaleType(ImageView.ScaleType.CENTER); - avatarContainer.addView(timeItem); - timerDrawable = new TimerDrawable(getParentActivity()); - - layoutParams2 = (FrameLayout.LayoutParams) timeItem.getLayoutParams(); - layoutParams2.width = AndroidUtilities.dp(34); - layoutParams2.height = AndroidUtilities.dp(34); - layoutParams2.topMargin = AndroidUtilities.dp(18); - layoutParams2.leftMargin = AndroidUtilities.dp(16); - layoutParams2.gravity = Gravity.TOP | Gravity.LEFT; - timeItem.setLayoutParams(layoutParams2); - timeItem.setImageDrawable(timerDrawable); - - timeItem.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (getParentActivity() == null) { - return; - } - showAlertDialog(AndroidUtilities.buildTTLAlert(getParentActivity(), currentEncryptedChat)); - } - }); - } - - nameTextView = new TextView(getParentActivity()); - nameTextView.setTextColor(0xffffffff); - nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - nameTextView.setLines(1); - nameTextView.setMaxLines(1); - nameTextView.setSingleLine(true); - nameTextView.setEllipsize(TextUtils.TruncateAt.END); - nameTextView.setGravity(Gravity.LEFT); - nameTextView.setCompoundDrawablePadding(AndroidUtilities.dp(4)); - nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - avatarContainer.addView(nameTextView); - layoutParams2 = (FrameLayout.LayoutParams) nameTextView.getLayoutParams(); - layoutParams2.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams2.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams2.leftMargin = AndroidUtilities.dp(54); - layoutParams2.bottomMargin = AndroidUtilities.dp(22); - layoutParams2.gravity = Gravity.BOTTOM; - nameTextView.setLayoutParams(layoutParams2); - - onlineTextView = new TextView(getParentActivity()); - onlineTextView.setTextColor(0xffd7e8f7); - onlineTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - onlineTextView.setLines(1); - onlineTextView.setMaxLines(1); - onlineTextView.setSingleLine(true); - onlineTextView.setEllipsize(TextUtils.TruncateAt.END); - onlineTextView.setGravity(Gravity.LEFT); - avatarContainer.addView(onlineTextView); - layoutParams2 = (FrameLayout.LayoutParams) onlineTextView.getLayoutParams(); - layoutParams2.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams2.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams2.leftMargin = AndroidUtilities.dp(54); - layoutParams2.bottomMargin = AndroidUtilities.dp(4); - layoutParams2.gravity = Gravity.BOTTOM; - onlineTextView.setLayoutParams(layoutParams2); - - ActionBarMenu menu = actionBar.createMenu(); - - headerItem = menu.addItem(0, R.drawable.ic_ab_other); - if (currentUser != null) { - addContactItem = headerItem.addSubItem(share_contact, "", 0); - } - if (currentEncryptedChat != null) { - timeItem2 = headerItem.addSubItem(chat_enc_timer, LocaleController.getString("SetTimer", R.string.SetTimer), 0); - } - headerItem.addSubItem(clear_history, LocaleController.getString("ClearHistory", R.string.ClearHistory), 0); - if (currentChat != null && !isBroadcast) { - headerItem.addSubItem(delete_chat, LocaleController.getString("DeleteAndExit", R.string.DeleteAndExit), 0); - } else { - headerItem.addSubItem(delete_chat, LocaleController.getString("DeleteChatUser", R.string.DeleteChatUser), 0); - } - muteItem = headerItem.addSubItem(mute, null, 0); - - LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) headerItem.getLayoutParams(); - layoutParams.rightMargin = AndroidUtilities.dp(-48); - headerItem.setLayoutParams(layoutParams); - - updateTitle(); - updateSubtitle(); - updateTitleIcons(); - - attachItem = menu.addItem(chat_menu_attach, R.drawable.ic_ab_other); - attachItem.addSubItem(attach_photo, LocaleController.getString("ChatTakePhoto", R.string.ChatTakePhoto), R.drawable.ic_attach_photo); - attachItem.addSubItem(attach_gallery, LocaleController.getString("ChatGallery", R.string.ChatGallery), R.drawable.ic_attach_gallery); - attachItem.addSubItem(attach_video, LocaleController.getString("ChatVideo", R.string.ChatVideo), R.drawable.ic_attach_video); - attachItem.addSubItem(attach_document, LocaleController.getString("ChatDocument", R.string.ChatDocument), R.drawable.ic_ab_doc); - attachItem.addSubItem(attach_location, LocaleController.getString("ChatLocation", R.string.ChatLocation), R.drawable.ic_attach_location); - attachItem.setVisibility(View.INVISIBLE); - - menuItem = menu.addItem(chat_menu_attach, R.drawable.ic_ab_attach); - menuItem.addSubItem(attach_photo, LocaleController.getString("ChatTakePhoto", R.string.ChatTakePhoto), R.drawable.ic_attach_photo); - menuItem.addSubItem(attach_gallery, LocaleController.getString("ChatGallery", R.string.ChatGallery), R.drawable.ic_attach_gallery); - menuItem.addSubItem(attach_video, LocaleController.getString("ChatVideo", R.string.ChatVideo), R.drawable.ic_attach_video); - menuItem.addSubItem(attach_document, LocaleController.getString("ChatDocument", R.string.ChatDocument), R.drawable.ic_ab_doc); - menuItem.addSubItem(attach_location, LocaleController.getString("ChatLocation", R.string.ChatLocation), R.drawable.ic_attach_location); - menuItem.setShowFromBottom(true); - menuItem.setBackgroundDrawable(null); - - actionModeViews.clear(); - - final ActionBarMenu actionMode = actionBar.createActionMode(); - actionModeViews.add(actionMode.addItem(-2, R.drawable.ic_ab_back_grey, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); - - selectedMessagesCountTextView = new TextView(actionMode.getContext()); - selectedMessagesCountTextView.setTextSize(18); - selectedMessagesCountTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - selectedMessagesCountTextView.setTextColor(0xff737373); - selectedMessagesCountTextView.setSingleLine(true); - selectedMessagesCountTextView.setLines(1); - selectedMessagesCountTextView.setEllipsize(TextUtils.TruncateAt.END); - selectedMessagesCountTextView.setPadding(AndroidUtilities.dp(11), 0, 0, AndroidUtilities.dp(2)); - selectedMessagesCountTextView.setGravity(Gravity.CENTER_VERTICAL); - selectedMessagesCountTextView.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - return true; - } - }); - actionMode.addView(selectedMessagesCountTextView); - layoutParams = (LinearLayout.LayoutParams)selectedMessagesCountTextView.getLayoutParams(); - layoutParams.weight = 1; - layoutParams.width = 0; - layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT; - selectedMessagesCountTextView.setLayoutParams(layoutParams); - - if (currentEncryptedChat == null) { - actionModeViews.add(actionMode.addItem(copy, R.drawable.ic_ab_fwd_copy, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); - if (!isBroadcast) { - actionModeViews.add(actionMode.addItem(reply, R.drawable.ic_ab_reply, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); - } - actionModeViews.add(actionMode.addItem(forward, R.drawable.ic_ab_fwd_forward, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); - actionModeViews.add(actionMode.addItem(delete, R.drawable.ic_ab_fwd_delete, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); - } else { - actionModeViews.add(actionMode.addItem(copy, R.drawable.ic_ab_fwd_copy, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); - actionModeViews.add(actionMode.addItem(delete, R.drawable.ic_ab_fwd_delete, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); - } - actionMode.getItem(copy).setVisibility(selectedMessagesCanCopyIds.size() != 0 ? View.VISIBLE : View.GONE); - if (actionMode.getItem(reply) != null) { - actionMode.getItem(reply).setVisibility(selectedMessagesIds.size() == 1 ? View.VISIBLE : View.GONE); - } - checkActionBarMenu(); - - fragmentView = new SizeNotifierRelativeLayout(getParentActivity()); - SizeNotifierRelativeLayout contentView = (SizeNotifierRelativeLayout) fragmentView; - - contentView.setBackgroundImage(ApplicationLoader.getCachedWallpaper()); - - emptyViewContainer = new FrameLayout(getParentActivity()); - emptyViewContainer.setPadding(0, 0, 0, AndroidUtilities.dp(48)); - emptyViewContainer.setVisibility(View.INVISIBLE); - contentView.addView(emptyViewContainer); - RelativeLayout.LayoutParams layoutParams3 = (RelativeLayout.LayoutParams) emptyViewContainer.getLayoutParams(); - layoutParams3.width = RelativeLayout.LayoutParams.MATCH_PARENT; - layoutParams3.height = RelativeLayout.LayoutParams.MATCH_PARENT; - emptyViewContainer.setLayoutParams(layoutParams3); - emptyViewContainer.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - return true; - } - }); - - if (currentEncryptedChat == null) { - TextView emptyView = new TextView(getParentActivity()); - if (currentUser != null && currentUser.id != 777000 && (currentUser.id / 1000 == 333 || currentUser.id % 1000 == 0)) { - emptyView.setText(LocaleController.getString("GotAQuestion", R.string.GotAQuestion)); - } else { - emptyView.setText(LocaleController.getString("NoMessages", R.string.NoMessages)); - } - emptyView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - emptyView.setGravity(Gravity.CENTER); - emptyView.setTextColor(0xffffffff); - emptyView.setBackgroundResource(ApplicationLoader.isCustomTheme() ? R.drawable.system_black : R.drawable.system_blue); - emptyView.setPadding(AndroidUtilities.dp(7), AndroidUtilities.dp(1), AndroidUtilities.dp(7), AndroidUtilities.dp(1)); - emptyViewContainer.addView(emptyView); - layoutParams2 = (FrameLayout.LayoutParams) emptyView.getLayoutParams(); - layoutParams2.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams2.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams2.gravity = Gravity.CENTER; - emptyView.setLayoutParams(layoutParams2); - } else { - LinearLayout secretChatPlaceholder = new LinearLayout(getParentActivity()); - secretChatPlaceholder.setBackgroundResource(ApplicationLoader.isCustomTheme() ? R.drawable.system_black : R.drawable.system_blue); - secretChatPlaceholder.setPadding(AndroidUtilities.dp(16), AndroidUtilities.dp(12), AndroidUtilities.dp(16), AndroidUtilities.dp(12)); - secretChatPlaceholder.setOrientation(LinearLayout.VERTICAL); - emptyViewContainer.addView(secretChatPlaceholder); - layoutParams2 = (FrameLayout.LayoutParams) secretChatPlaceholder.getLayoutParams(); - layoutParams2.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams2.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams2.gravity = Gravity.CENTER; - secretChatPlaceholder.setLayoutParams(layoutParams2); - - secretViewStatusTextView = new TextView(getParentActivity()); - secretViewStatusTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); - secretViewStatusTextView.setTextColor(0xffffffff); - secretViewStatusTextView.setGravity(Gravity.CENTER_HORIZONTAL); - secretViewStatusTextView.setMaxWidth(AndroidUtilities.dp(210)); - if (currentEncryptedChat.admin_id == UserConfig.getClientUserId()) { - if (currentUser.first_name.length() > 0) { - secretViewStatusTextView.setText(LocaleController.formatString("EncryptedPlaceholderTitleOutgoing", R.string.EncryptedPlaceholderTitleOutgoing, currentUser.first_name)); - } else { - secretViewStatusTextView.setText(LocaleController.formatString("EncryptedPlaceholderTitleOutgoing", R.string.EncryptedPlaceholderTitleOutgoing, currentUser.last_name)); - } - } else { - if (currentUser.first_name.length() > 0) { - secretViewStatusTextView.setText(LocaleController.formatString("EncryptedPlaceholderTitleIncoming", R.string.EncryptedPlaceholderTitleIncoming, currentUser.first_name)); - } else { - secretViewStatusTextView.setText(LocaleController.formatString("EncryptedPlaceholderTitleIncoming", R.string.EncryptedPlaceholderTitleIncoming, currentUser.last_name)); - } - } - secretChatPlaceholder.addView(secretViewStatusTextView); - layoutParams = (LinearLayout.LayoutParams) secretViewStatusTextView.getLayoutParams(); - layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT; - layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT; - layoutParams.gravity = Gravity.CENTER_HORIZONTAL; - secretViewStatusTextView.setLayoutParams(layoutParams); - - TextView textView = new TextView(getParentActivity()); - textView.setText(LocaleController.getString("EncryptedDescriptionTitle", R.string.EncryptedDescriptionTitle)); - textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); - textView.setTextColor(0xffffffff); - textView.setGravity(Gravity.CENTER_HORIZONTAL); - textView.setMaxWidth(AndroidUtilities.dp(260)); - secretChatPlaceholder.addView(textView); - layoutParams = (LinearLayout.LayoutParams) textView.getLayoutParams(); - layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT; - layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT; - layoutParams.topMargin = AndroidUtilities.dp(8); - layoutParams.gravity = LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT; - textView.setLayoutParams(layoutParams); - - for (int a = 0; a < 4; a++) { - LinearLayout linearLayout = new LinearLayout(getParentActivity()); - linearLayout.setOrientation(LinearLayout.HORIZONTAL); - secretChatPlaceholder.addView(linearLayout); - layoutParams = (LinearLayout.LayoutParams) linearLayout.getLayoutParams(); - layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT; - layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT; - layoutParams.topMargin = AndroidUtilities.dp(8); - layoutParams.gravity = LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT; - linearLayout.setLayoutParams(layoutParams); - - ImageView imageView = new ImageView(getParentActivity()); - imageView.setImageResource(R.drawable.ic_lock_white); - - textView = new TextView(getParentActivity()); - textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); - textView.setTextColor(0xffffffff); - textView.setGravity(Gravity.CENTER_VERTICAL | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); - textView.setMaxWidth(AndroidUtilities.dp(260)); - - switch (a) { - case 0: - textView.setText(LocaleController.getString("EncryptedDescription1", R.string.EncryptedDescription1)); - break; - case 1: - textView.setText(LocaleController.getString("EncryptedDescription2", R.string.EncryptedDescription2)); - break; - case 2: - textView.setText(LocaleController.getString("EncryptedDescription3", R.string.EncryptedDescription3)); - break; - case 3: - textView.setText(LocaleController.getString("EncryptedDescription4", R.string.EncryptedDescription4)); - break; - } - - if (LocaleController.isRTL) { - linearLayout.addView(textView); - linearLayout.addView(imageView); - } else { - linearLayout.addView(imageView); - linearLayout.addView(textView); - } - layoutParams = (LinearLayout.LayoutParams) imageView.getLayoutParams(); - layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT; - layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT; - layoutParams.rightMargin = LocaleController.isRTL ? 0 : AndroidUtilities.dp(8); - layoutParams.leftMargin = LocaleController.isRTL ? AndroidUtilities.dp(8) : 0; - layoutParams.topMargin = AndroidUtilities.dp(LocaleController.isRTL ? 3 : 4); - imageView.setLayoutParams(layoutParams); - - layoutParams = (LinearLayout.LayoutParams) textView.getLayoutParams(); - layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT; - layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT; - textView.setLayoutParams(layoutParams); - } - } - - chatListView = new LayoutListView(getParentActivity()); - chatListView.setAdapter(chatAdapter = new ChatAdapter(getParentActivity())); - chatListView.setCacheColorHint(ApplicationLoader.getSelectedColor()); - chatListView.setClipToPadding(false); - chatListView.setStackFromBottom(true); - chatListView.setPadding(0, AndroidUtilities.dp(4), 0, AndroidUtilities.dp(3)); - chatListView.setDivider(null); - chatListView.setSelector(R.drawable.transparent); - chatListView.setOnItemLongClickListener(onItemLongClickListener); - chatListView.setOnItemClickListener(onItemClickListener); - contentView.addView(chatListView); - layoutParams3 = (RelativeLayout.LayoutParams) chatListView.getLayoutParams(); - layoutParams3.width = RelativeLayout.LayoutParams.MATCH_PARENT; - layoutParams3.height = RelativeLayout.LayoutParams.MATCH_PARENT; - layoutParams3.bottomMargin = -AndroidUtilities.dp(3); - layoutParams3.addRule(RelativeLayout.ABOVE, id_chat_compose_panel); - chatListView.setLayoutParams(layoutParams3); - chatListView.setOnInterceptTouchEventListener(new LayoutListView.OnInterceptTouchEventListener() { - @Override - public boolean onInterceptTouchEvent(MotionEvent event) { - if (actionBar.isActionModeShowed()) { - return false; - } - if (event.getAction() == MotionEvent.ACTION_DOWN) { - int x = (int)event.getX(); - int y = (int)event.getY(); - int count = chatListView.getChildCount(); - Rect rect = new Rect(); - for (int a = 0; a < count; a++) { - View view = chatListView.getChildAt(a); - int top = view.getTop(); - int bottom = view.getBottom(); - view.getLocalVisibleRect(rect); - if (top > y || bottom < y) { - continue; - } - if (!(view instanceof ChatMediaCell)) { - break; - } - final ChatMediaCell cell = (ChatMediaCell)view; - final MessageObject messageObject = cell.getMessageObject(); - if (messageObject == null || !messageObject.isSecretPhoto() || !cell.getPhotoImage().isInsideImage(x, y - top)) { - break; - } - File file = FileLoader.getPathToMessage(messageObject.messageOwner); - if (!file.exists()) { - break; - } - startX = x; - startY = y; - chatListView.setOnItemClickListener(null); - openSecretPhotoRunnable = new Runnable() { - @Override - public void run() { - if (openSecretPhotoRunnable == null) { - return; - } - chatListView.requestDisallowInterceptTouchEvent(true); - chatListView.setOnItemLongClickListener(null); - chatListView.setLongClickable(false); - openSecretPhotoRunnable = null; - if (sendSecretMessageRead(messageObject)) { - cell.invalidate(); - } - SecretPhotoViewer.getInstance().setParentActivity(getParentActivity()); - SecretPhotoViewer.getInstance().openPhoto(messageObject); - } - }; - AndroidUtilities.runOnUIThread(openSecretPhotoRunnable, 100); - return true; + android.content.ClipboardManager clipboard = (android.content.ClipboardManager) ApplicationLoader.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE); + android.content.ClipData clip = android.content.ClipData.newPlainText("label", str); + clipboard.setPrimaryClip(clip); } } - return false; - } - }); - chatListView.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - if (openSecretPhotoRunnable != null || SecretPhotoViewer.getInstance().isVisible()) { - if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_POINTER_UP) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - chatListView.setOnItemClickListener(onItemClickListener); - } - }, 150); - if (openSecretPhotoRunnable != null) { - AndroidUtilities.cancelRunOnUIThread(openSecretPhotoRunnable); - openSecretPhotoRunnable = null; - try { - Toast.makeText(v.getContext(), LocaleController.getString("PhotoTip", R.string.PhotoTip), Toast.LENGTH_SHORT).show(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } else { - if (SecretPhotoViewer.getInstance().isVisible()) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - chatListView.setOnItemLongClickListener(onItemLongClickListener); - chatListView.setLongClickable(true); - } - }); - SecretPhotoViewer.getInstance().closePhoto(); - } - } - } else if (event.getAction() != MotionEvent.ACTION_DOWN) { - if (SecretPhotoViewer.getInstance().isVisible()) { - return true; - } else if (openSecretPhotoRunnable != null) { - if (event.getAction() == MotionEvent.ACTION_MOVE) { - if (Math.hypot(startX - event.getX(), startY - event.getY()) > AndroidUtilities.dp(5)) { - AndroidUtilities.cancelRunOnUIThread(openSecretPhotoRunnable); - openSecretPhotoRunnable = null; - } - } else { - AndroidUtilities.cancelRunOnUIThread(openSecretPhotoRunnable); - openSecretPhotoRunnable = null; - } - } - } - } - return false; - } - }); - chatListView.setOnScrollListener(new AbsListView.OnScrollListener() { - Rect scrollRect = new Rect(); - - @Override - public void onScrollStateChanged(AbsListView absListView, int i) { - if (i == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL || i == AbsListView.OnScrollListener.SCROLL_STATE_FLING && highlightMessageId != Integer.MAX_VALUE) { - highlightMessageId = Integer.MAX_VALUE; - updateVisibleRows(); - } - } - - @Override - public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - if (visibleItemCount > 0) { - if (firstVisibleItem <= 10) { - if (!endReached && !loading) { - if (messagesByDays.size() != 0) { - MessagesController.getInstance().loadMessages(dialog_id, 20, maxMessageId, !cacheEndReaced && startLoadFromMessageId == 0, minDate, classGuid, 0, 0, 0, startLoadFromMessageId == 0); - } else { - MessagesController.getInstance().loadMessages(dialog_id, 20, 0, !cacheEndReaced && startLoadFromMessageId == 0, minDate, classGuid, 0, 0, 0, startLoadFromMessageId == 0); - } - loading = true; - } - } - if (firstVisibleItem + visibleItemCount >= totalItemCount - 6) { - if (!forward_end_reached && !loadingForward) { - MessagesController.getInstance().loadMessages(dialog_id, 20, minMessageId, startLoadFromMessageId == 0, maxDate, classGuid, 1, 0, 0, startLoadFromMessageId == 0); - loadingForward = true; - } - } - if (firstVisibleItem + visibleItemCount == totalItemCount && forward_end_reached) { - showPagedownButton(false, true); - } - } - for (int a = 0; a < visibleItemCount; a++) { - View view = absListView.getChildAt(a); - if (view instanceof ChatMessageCell) { - ChatMessageCell messageCell = (ChatMessageCell)view; - messageCell.getLocalVisibleRect(scrollRect); - messageCell.setVisiblePart(scrollRect.top, scrollRect.bottom - scrollRect.top); - } - } - } - }); - - progressView = new FrameLayout(getParentActivity()); - progressView.setVisibility(View.INVISIBLE); - progressView.setBackgroundResource(ApplicationLoader.isCustomTheme() ? R.drawable.system_loader2 : R.drawable.system_loader1); - contentView.addView(progressView); - layoutParams3 = (RelativeLayout.LayoutParams) progressView.getLayoutParams(); - layoutParams3.width = AndroidUtilities.dp(36); - layoutParams3.height = AndroidUtilities.dp(36); - layoutParams3.bottomMargin = AndroidUtilities.dp(48); - layoutParams3.addRule(RelativeLayout.CENTER_IN_PARENT); - progressView.setLayoutParams(layoutParams3); - - ProgressBar progressBar = new ProgressBar(getParentActivity()); - try { - progressBar.setIndeterminateDrawable(getParentActivity().getResources().getDrawable(R.drawable.loading_animation)); - } catch (Exception e) { - //don't promt - } - progressBar.setIndeterminate(true); - AndroidUtilities.setProgressBarAnimationDuration(progressBar, 1500); - progressView.addView(progressBar); - layoutParams2 = (FrameLayout.LayoutParams) progressBar.getLayoutParams(); - layoutParams2.width = AndroidUtilities.dp(32); - layoutParams2.height = AndroidUtilities.dp(32); - layoutParams2.gravity = Gravity.CENTER; - progressBar.setLayoutParams(layoutParams2); - - if (currentEncryptedChat == null && !isBroadcast) { - mentionListView = new ListView(getParentActivity()); - mentionListView.setBackgroundResource(R.drawable.compose_panel); - mentionListView.setVisibility(View.GONE); - mentionListView.setPadding(0, AndroidUtilities.dp(2), 0, 0); - mentionListView.setClipToPadding(true); - mentionListView.setDividerHeight(0); - mentionListView.setDivider(null); - if (Build.VERSION.SDK_INT > 8) { - mentionListView.setOverScrollMode(ListView.OVER_SCROLL_NEVER); - } - contentView.addView(mentionListView); - layoutParams3 = (RelativeLayout.LayoutParams) mentionListView.getLayoutParams(); - layoutParams3.width = RelativeLayout.LayoutParams.MATCH_PARENT; - layoutParams3.height = AndroidUtilities.dp(110); - layoutParams3.topMargin = -AndroidUtilities.dp(108); - layoutParams3.addRule(RelativeLayout.ALIGN_TOP, id_chat_compose_panel); - mentionListView.setLayoutParams(layoutParams3); - - mentionListView.setAdapter(mentionsAdapter = new MentionsAdapter(getParentActivity(), new MentionsAdapter.MentionsAdapterDelegate() { - @Override - public void needChangePanelVisibility(boolean show) { - if (show) { - RelativeLayout.LayoutParams layoutParams3 = (RelativeLayout.LayoutParams) mentionListView.getLayoutParams(); - int height = 36 * Math.min(3, mentionsAdapter.getCount()) + (mentionsAdapter.getCount() > 3 ? 18 : 0); - layoutParams3.height = AndroidUtilities.dp(2 + height); - layoutParams3.topMargin = -AndroidUtilities.dp(height); - mentionListView.setLayoutParams(layoutParams3); - - if (mentionListAnimation != null) { - mentionListAnimation.cancel(); - mentionListAnimation = null; - } - - if (mentionListView.getVisibility() == View.VISIBLE) { - ViewProxy.setAlpha(mentionListView, 1.0f); - return; - } - if (allowStickersPanel) { - mentionListView.setVisibility(View.VISIBLE); - mentionListAnimation = new AnimatorSetProxy(); - mentionListAnimation.playTogether( - ObjectAnimatorProxy.ofFloat(mentionListView, "alpha", 0.0f, 1.0f) - ); - mentionListAnimation.addListener(new AnimatorListenerAdapterProxy() { - @Override - public void onAnimationEnd(Object animation) { - if (mentionListAnimation != null && mentionListAnimation.equals(animation)) { - mentionListView.clearAnimation(); - mentionListAnimation = null; - } - } - }); - mentionListAnimation.setDuration(200); - mentionListAnimation.start(); - } else { - ViewProxy.setAlpha(mentionListView, 1.0f); - mentionListView.clearAnimation(); - mentionListView.setVisibility(View.INVISIBLE); - } - } else { - if (mentionListAnimation != null) { - mentionListAnimation.cancel(); - mentionListAnimation = null; - } - - if (mentionListView.getVisibility() == View.GONE) { - return; - } - if (allowStickersPanel) { - mentionListAnimation = new AnimatorSetProxy(); - mentionListAnimation.playTogether( - ObjectAnimatorProxy.ofFloat(mentionListView, "alpha", 0.0f) - ); - mentionListAnimation.addListener(new AnimatorListenerAdapterProxy() { - @Override - public void onAnimationEnd(Object animation) { - if (mentionListAnimation != null && mentionListAnimation.equals(animation)) { - mentionListView.clearAnimation(); - mentionListView.setVisibility(View.GONE); - mentionListAnimation = null; - } - } - }); - mentionListAnimation.setDuration(200); - mentionListAnimation.start(); - } else { - mentionListView.clearAnimation(); - mentionListView.setVisibility(View.GONE); - } - } - } - })); - mentionsAdapter.setChatInfo(info); - mentionsAdapter.setNeedUsernames(currentChat != null); - - mentionListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView parent, View view, int position, long id) { - Object object = mentionsAdapter.getItem(position); - int start = mentionsAdapter.getResultStartPosition(); - int len = mentionsAdapter.getResultLength(); - if (object instanceof TLRPC.User) { - TLRPC.User user = (TLRPC.User) object; - if (user != null) { - chatActivityEnterView.replaceWithText(start, len, "@" + user.username + " "); - } - } else if (object instanceof String) { - chatActivityEnterView.replaceWithText(start, len, object + " "); - } - } - }); - - mentionListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { - @Override - public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { - Object object = mentionsAdapter.getItem(position); - if (object instanceof String) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setMessage(LocaleController.getString("ClearSearch", R.string.ClearSearch)); - builder.setPositiveButton(LocaleController.getString("ClearButton", R.string.ClearButton).toUpperCase(), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - mentionsAdapter.clearRecentHashtags(); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - return true; - } - return false; - } - }); - } - - if (chatActivityEnterView != null) { - chatActivityEnterView.onDestroy(); - } - chatActivityEnterView = new ChatActivityEnterView(getParentActivity(), contentView, this, true); - chatActivityEnterView.setDialogId(dialog_id); - chatActivityEnterView.addToAttachLayout(menuItem); - chatActivityEnterView.setId(id_chat_compose_panel); - contentView.addView(chatActivityEnterView); - layoutParams3 = (RelativeLayout.LayoutParams) chatActivityEnterView.getLayoutParams(); - layoutParams3.width = RelativeLayout.LayoutParams.MATCH_PARENT; - layoutParams3.height = RelativeLayout.LayoutParams.WRAP_CONTENT; - layoutParams3.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); - chatActivityEnterView.setLayoutParams(layoutParams3); - chatActivityEnterView.setDelegate(new ChatActivityEnterView.ChatActivityEnterViewDelegate() { - @Override - public void onMessageSend(String message) { - moveScrollToLastMessage(); - showReplyForMessageObjectOrForward(false, null, null, true); - if (mentionsAdapter != null) { - mentionsAdapter.addHashtagsFromMessage(message); - } - if (message != null) { - NotificationsController.getInstance().playOutChatSound(); - } - } - - @Override - public void onTextChanged(CharSequence text) { - if (stickersAdapter != null) { - stickersAdapter.loadStikersForEmoji(text); - } - if (mentionsAdapter != null) { - mentionsAdapter.searchUsernameOrHashtag(text.toString(), chatActivityEnterView.getCursorPosition(), messages); - } - } - - @Override - public void needSendTyping() { - MessagesController.getInstance().sendTyping(dialog_id, classGuid); - } - - @Override - public void onAttachButtonHidden() { - if (attachItem != null) { - attachItem.setVisibility(View.VISIBLE); - } - if (headerItem != null) { - headerItem.setVisibility(View.INVISIBLE); - } - } - - @Override - public void onAttachButtonShow() { - if (attachItem != null) { - attachItem.setVisibility(View.INVISIBLE); - } - if (headerItem != null) { - headerItem.setVisibility(View.VISIBLE); - } - } - - @Override - public void onWindowSizeChanged(int size) { - if (size < AndroidUtilities.dp(72) + AndroidUtilities.getCurrentActionBarHeight()) { - allowStickersPanel = false; - if (stickersPanel.getVisibility() == View.VISIBLE) { - stickersPanel.clearAnimation(); - stickersPanel.setVisibility(View.INVISIBLE); - } - if (mentionListView != null && mentionListView.getVisibility() == View.VISIBLE) { - mentionListView.clearAnimation(); - mentionListView.setVisibility(View.INVISIBLE); - } - } else { - allowStickersPanel = true; - if (stickersPanel.getVisibility() == View.INVISIBLE) { - stickersPanel.clearAnimation(); - stickersPanel.setVisibility(View.VISIBLE); - } - if (mentionListView != null && mentionListView.getVisibility() == View.INVISIBLE) { - mentionListView.clearAnimation(); - mentionListView.setVisibility(View.VISIBLE); - } - } - } - }); - - FrameLayout replyLayout = new FrameLayout(getParentActivity()); - replyLayout.setClickable(true); - chatActivityEnterView.addTopView(replyLayout, AndroidUtilities.dp(48)); - - View lineView = new View(getParentActivity()); - lineView.setBackgroundColor(0xffe8e8e8); - replyLayout.addView(lineView); - layoutParams2 = (FrameLayout.LayoutParams) lineView.getLayoutParams(); - layoutParams2.gravity = Gravity.BOTTOM; - layoutParams2.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams2.height = AndroidUtilities.dp(1); - lineView.setLayoutParams(layoutParams2); - - replyIconImageView = new ImageView(getParentActivity()); - replyIconImageView.setScaleType(ImageView.ScaleType.CENTER); - replyLayout.addView(replyIconImageView); - layoutParams2 = (FrameLayout.LayoutParams) replyIconImageView.getLayoutParams(); - layoutParams2.gravity = Gravity.TOP | Gravity.LEFT; - layoutParams2.width = AndroidUtilities.dp(52); - layoutParams2.height = AndroidUtilities.dp(46); - replyIconImageView.setLayoutParams(layoutParams2); - - ImageView imageView = new ImageView(getParentActivity()); - imageView.setImageResource(R.drawable.delete_reply); - imageView.setScaleType(ImageView.ScaleType.CENTER); - replyLayout.addView(imageView); - layoutParams2 = (FrameLayout.LayoutParams) imageView.getLayoutParams(); - layoutParams2.topMargin = AndroidUtilities.dp(0.5f); - layoutParams2.width = AndroidUtilities.dp(52); - layoutParams2.height = AndroidUtilities.dp(46); - layoutParams2.gravity = Gravity.RIGHT | Gravity.TOP; - imageView.setLayoutParams(layoutParams2); - imageView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (forwardingMessages != null) { - forwardingMessages.clear(); - } - showReplyForMessageObjectOrForward(false, null, null, true); - } - }); - - replyNameTextView = new TextView(getParentActivity()); - replyNameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - replyNameTextView.setTextColor(0xff377aae); - replyNameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - replyNameTextView.setSingleLine(true); - replyNameTextView.setEllipsize(TextUtils.TruncateAt.END); - replyNameTextView.setMaxLines(1); - replyLayout.addView(replyNameTextView); - layoutParams2 = (FrameLayout.LayoutParams) replyNameTextView.getLayoutParams(); - layoutParams2.leftMargin = AndroidUtilities.dp(52); - layoutParams2.rightMargin = AndroidUtilities.dp(52); - layoutParams2.topMargin = AndroidUtilities.dp(4); - layoutParams2.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams2.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams2.gravity = Gravity.TOP | Gravity.LEFT; - replyNameTextView.setLayoutParams(layoutParams2); - - replyObjectTextView = new TextView(getParentActivity()); - replyObjectTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - replyObjectTextView.setTextColor(0xff999999); - replyObjectTextView.setSingleLine(true); - replyObjectTextView.setEllipsize(TextUtils.TruncateAt.END); - replyObjectTextView.setMaxLines(1); - replyLayout.addView(replyObjectTextView); - layoutParams2 = (FrameLayout.LayoutParams) replyObjectTextView.getLayoutParams(); - layoutParams2.leftMargin = AndroidUtilities.dp(52); - layoutParams2.rightMargin = AndroidUtilities.dp(52); - layoutParams2.topMargin = AndroidUtilities.dp(22); - layoutParams2.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams2.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams2.gravity = Gravity.TOP | Gravity.LEFT; - replyObjectTextView.setLayoutParams(layoutParams2); - - replyImageView = new BackupImageView(getParentActivity()); - replyImageView.processDetach = false; - replyLayout.addView(replyImageView); - layoutParams2 = (FrameLayout.LayoutParams) replyImageView.getLayoutParams(); - layoutParams2.leftMargin = AndroidUtilities.dp(52); - layoutParams2.topMargin = AndroidUtilities.dp(6); - layoutParams2.width = AndroidUtilities.dp(34); - layoutParams2.height = AndroidUtilities.dp(34); - layoutParams2.gravity = Gravity.TOP | Gravity.LEFT; - replyImageView.setLayoutParams(layoutParams2); - - stickersPanel = new FrameLayout(getParentActivity()); - stickersPanel.setVisibility(View.GONE); - contentView.addView(stickersPanel); - layoutParams3 = (RelativeLayout.LayoutParams) stickersPanel.getLayoutParams(); - layoutParams3.width = RelativeLayout.LayoutParams.WRAP_CONTENT; - layoutParams3.height = AndroidUtilities.dp(81.5f); - layoutParams3.bottomMargin = AndroidUtilities.dp(38); - layoutParams3.addRule(RelativeLayout.ALIGN_BOTTOM, id_chat_compose_panel); - stickersPanel.setLayoutParams(layoutParams3); - - stickersListView = new RecyclerListView(getParentActivity()); - LinearLayoutManager layoutManager = new LinearLayoutManager(getParentActivity()); - layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); - stickersListView.setLayoutManager(layoutManager); - stickersListView.setClipToPadding(false); - if (Build.VERSION.SDK_INT >= 9) { - stickersListView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER); - } - stickersPanel.addView(stickersListView); - layoutParams2 = (FrameLayout.LayoutParams) stickersListView.getLayoutParams(); - layoutParams2.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams2.height = AndroidUtilities.dp(78); - stickersListView.setLayoutParams(layoutParams2); - if (currentEncryptedChat == null || currentEncryptedChat != null && AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 23) { - if (stickersAdapter != null) { - stickersAdapter.destroy(); - } - stickersListView.setPadding(AndroidUtilities.dp(18), 0, AndroidUtilities.dp(18), 0); - stickersListView.setAdapter(stickersAdapter = new StickersAdapter(getParentActivity(), new StickersAdapter.StickersAdapterDelegate() { - @Override - public void needChangePanelVisibility(final boolean show) { - if (show && stickersPanel.getVisibility() == View.VISIBLE || !show && stickersPanel.getVisibility() == View.GONE) { - return; - } - if (show) { - stickersListView.scrollToPosition(0); - stickersPanel.clearAnimation(); - stickersPanel.setVisibility(allowStickersPanel ? View.VISIBLE : View.INVISIBLE); - } - if (runningAnimation != null) { - runningAnimation.cancel(); - runningAnimation = null; - } - if (stickersPanel.getVisibility() != View.INVISIBLE) { - runningAnimation = new AnimatorSetProxy(); - runningAnimation.playTogether( - ObjectAnimatorProxy.ofFloat(stickersPanel, "alpha", show ? 0.0f : 1.0f, show ? 1.0f : 0.0f) - ); - runningAnimation.setDuration(150); - runningAnimation.addListener(new AnimatorListenerAdapterProxy() { - @Override - public void onAnimationEnd(Object animation) { - if (runningAnimation != null && runningAnimation.equals(animation)) { - if (!show) { - stickersAdapter.clearStickers(); - stickersPanel.clearAnimation(); - stickersPanel.setVisibility(View.GONE); - } - runningAnimation = null; - } - } - }); - runningAnimation.start(); - } else if (!show) { - stickersPanel.setVisibility(View.GONE); - } - } - })); - stickersListView.addOnItemTouchListener(new RecyclerListView.RecyclerListViewItemClickListener(getParentActivity(), new RecyclerListView.OnItemClickListener() { - @Override - public void onItemClick(View view, int position) { - TLRPC.Document document = stickersAdapter.getItem(position); - if (document instanceof TLRPC.TL_document) { - if (currentEncryptedChat != null && document.thumb instanceof TLRPC.TL_photoSize) { - File file = FileLoader.getPathToAttach(document.thumb, true); - if (file.exists()) { - try { - int len = (int)file.length(); - byte[] arr = new byte[(int)file.length()]; - RandomAccessFile reader = new RandomAccessFile(file, "r"); - reader.readFully(arr); - TLRPC.TL_document newDocument = new TLRPC.TL_document(); - newDocument.thumb = new TLRPC.TL_photoCachedSize(); - newDocument.thumb.location = document.thumb.location; - newDocument.thumb.size = document.thumb.size; - newDocument.thumb.w = document.thumb.w; - newDocument.thumb.h = document.thumb.h; - newDocument.thumb.type = document.thumb.type; - newDocument.thumb.bytes = arr; - - newDocument.id = document.id; - newDocument.access_hash = document.access_hash; - newDocument.date = document.date; - newDocument.mime_type = document.mime_type; - newDocument.size = document.size; - newDocument.dc_id = document.dc_id; - newDocument.attributes = document.attributes; - document = newDocument; - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - } - for (int a = 0; a < document.attributes.size(); a++) { - TLRPC.DocumentAttribute attribute = document.attributes.get(a); - if (attribute instanceof TLRPC.TL_documentAttributeSticker) { - document.attributes.remove(a); - document.attributes.add(new TLRPC.TL_documentAttributeSticker_old()); - break; - } - } - SendMessagesHelper.getInstance().sendMessage((TLRPC.TL_document) document, null, null, dialog_id, replyingMessageObject); - showReplyForMessageObjectOrForward(false, null, null, true); - } - chatActivityEnterView.setFieldText(""); - } - })); - } - - imageView = new ImageView(getParentActivity()); - imageView.setImageResource(R.drawable.stickers_back_arrow); - stickersPanel.addView(imageView); - layoutParams2 = (FrameLayout.LayoutParams) imageView.getLayoutParams(); - layoutParams2.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams2.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams2.gravity = Gravity.BOTTOM; - layoutParams2.leftMargin = AndroidUtilities.dp(53); - imageView.setLayoutParams(layoutParams2); - - bottomOverlay = new FrameLayout(getParentActivity()); - bottomOverlay.setBackgroundColor(0xffffffff); - bottomOverlay.setVisibility(View.INVISIBLE); - bottomOverlay.setFocusable(true); - bottomOverlay.setFocusableInTouchMode(true); - bottomOverlay.setClickable(true); - contentView.addView(bottomOverlay); - layoutParams3 = (RelativeLayout.LayoutParams) bottomOverlay.getLayoutParams(); - layoutParams3.width = RelativeLayout.LayoutParams.MATCH_PARENT; - layoutParams3.height = AndroidUtilities.dp(48); - layoutParams3.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); - bottomOverlay.setLayoutParams(layoutParams3); - - bottomOverlayText = new TextView(getParentActivity()); - bottomOverlayText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - bottomOverlayText.setTextColor(0xff7f7f7f); - bottomOverlay.addView(bottomOverlayText); - layoutParams2 = (FrameLayout.LayoutParams) bottomOverlayText.getLayoutParams(); - layoutParams2.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams2.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams2.gravity = Gravity.CENTER; - bottomOverlayText.setLayoutParams(layoutParams2); - - bottomOverlayChat = new FrameLayout(getParentActivity()); - bottomOverlayChat.setBackgroundColor(0xfffbfcfd); - bottomOverlayChat.setVisibility(View.INVISIBLE); - contentView.addView(bottomOverlayChat); - layoutParams3 = (RelativeLayout.LayoutParams) bottomOverlayChat.getLayoutParams(); - layoutParams3.width = RelativeLayout.LayoutParams.MATCH_PARENT; - layoutParams3.height = AndroidUtilities.dp(48); - layoutParams3.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); - bottomOverlayChat.setLayoutParams(layoutParams3); - bottomOverlayChat.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { + selectedMessagesIds.clear(); + selectedMessagesCanCopyIds.clear(); + actionBar.hideActionMode(); + updateVisibleRows(); + } else if (id == delete) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setMessage(LocaleController.formatString("AreYouSureDeleteMessages", R.string.AreYouSureDeleteMessages, LocaleController.formatPluralString("messages", selectedMessagesIds.size()))); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - if (currentUser != null && userBlocked) { - builder.setMessage(LocaleController.getString("AreYouSureUnblockContact", R.string.AreYouSureUnblockContact)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - MessagesController.getInstance().unblockUser(currentUser.id); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + ArrayList ids = new ArrayList<>(selectedMessagesIds.keySet()); + ArrayList random_ids = null; + if (currentEncryptedChat != null) { + random_ids = new ArrayList<>(); + for (HashMap.Entry entry : selectedMessagesIds.entrySet()) { + MessageObject msg = entry.getValue(); + if (msg.messageOwner.random_id != 0 && msg.type != 10) { + random_ids.add(msg.messageOwner.random_id); + } + } } - }); - } else { - builder.setMessage(LocaleController.getString("AreYouSureDeleteThisChat", R.string.AreYouSureDeleteThisChat)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - MessagesController.getInstance().deleteDialog(dialog_id, 0, false); - finishFragment(); - } - }); - } + MessagesController.getInstance().deleteMessages(ids, random_ids, currentEncryptedChat); + actionBar.hideActionMode(); + } + }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showAlertDialog(builder); + } else if (id == forward) { + Bundle args = new Bundle(); + args.putBoolean("onlySelect", true); + args.putBoolean("serverOnly", true); + MessagesActivity fragment = new MessagesActivity(args); + fragment.setDelegate(ChatActivity.this); + presentFragment(fragment); + } else if (id == chat_enc_timer) { + if (getParentActivity() == null) { + return; + } + showAlertDialog(AndroidUtilities.buildTTLAlert(getParentActivity(), currentEncryptedChat)); + } else if (id == clear_history || id == delete_chat) { + if (getParentActivity() == null) { + return; + } + final boolean isChat = (int) dialog_id < 0 && (int) (dialog_id >> 32) != 1; + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + if (id == clear_history) { + builder.setMessage(LocaleController.getString("AreYouSureClearHistory", R.string.AreYouSureClearHistory)); + } else { + if (isChat) { + builder.setMessage(LocaleController.getString("AreYouSureDeleteAndExit", R.string.AreYouSureDeleteAndExit)); + } else { + builder.setMessage(LocaleController.getString("AreYouSureDeleteThisChat", R.string.AreYouSureDeleteThisChat)); + } + } + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + if (id != clear_history) { + if (isChat) { + MessagesController.getInstance().deleteUserFromChat((int) -dialog_id, MessagesController.getInstance().getUser(UserConfig.getClientUserId()), null); + } else { + MessagesController.getInstance().deleteDialog(dialog_id, 0, false); + } + finishFragment(); + } else { + MessagesController.getInstance().deleteDialog(dialog_id, 0, true); + } + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } else if (id == share_contact) { + if (currentUser == null || getParentActivity() == null) { + return; + } + if (currentUser.phone != null && currentUser.phone.length() != 0) { + Bundle args = new Bundle(); + args.putInt("user_id", currentUser.id); + args.putBoolean("addContact", true); + presentFragment(new ContactAddActivity(args)); + } else { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setMessage(LocaleController.getString("AreYouSureShareMyContactInfo", R.string.AreYouSureShareMyContactInfo)); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + SendMessagesHelper.getInstance().sendMessage(UserConfig.getCurrentUser(), dialog_id, replyingMessageObject); + moveScrollToLastMessage(); + showReplyPanel(false, null, null, null, false, true); + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } + } else if (id == mute) { + boolean muted = MessagesController.getInstance().isDialogMuted(dialog_id); + if (!muted) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("Notifications", R.string.Notifications)); + CharSequence[] items = new CharSequence[]{ + LocaleController.formatString("MuteFor", R.string.MuteFor, LocaleController.formatPluralString("Hours", 1)), + LocaleController.formatString("MuteFor", R.string.MuteFor, LocaleController.formatPluralString("Hours", 8)), + LocaleController.formatString("MuteFor", R.string.MuteFor, LocaleController.formatPluralString("Days", 2)), + LocaleController.getString("MuteDisable", R.string.MuteDisable) + }; + builder.setItems(items, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + int untilTime = ConnectionsManager.getInstance().getCurrentTime(); + if (i == 0) { + untilTime += 60 * 60; + } else if (i == 1) { + untilTime += 60 * 60 * 8; + } else if (i == 2) { + untilTime += 60 * 60 * 48; + } else if (i == 3) { + untilTime = Integer.MAX_VALUE; + } + + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + long flags = 0; + if (i == 3) { + editor.putInt("notify2_" + dialog_id, 2); + flags = 1; + } else { + editor.putInt("notify2_" + dialog_id, 3); + editor.putInt("notifyuntil_" + dialog_id, untilTime); + flags = ((long) untilTime << 32) | 1; + } + MessagesStorage.getInstance().setDialogFlags(dialog_id, flags); + editor.commit(); + TLRPC.TL_dialog dialog = MessagesController.getInstance().dialogs_dict.get(dialog_id); + if (dialog != null) { + dialog.notify_settings = new TLRPC.TL_peerNotifySettings(); + dialog.notify_settings.mute_until = untilTime; + } + NotificationsController.updateServerNotificationsSettings(dialog_id); + } + } + ); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } else { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + editor.putInt("notify2_" + dialog_id, 0); + MessagesStorage.getInstance().setDialogFlags(dialog_id, 0); + editor.commit(); + TLRPC.TL_dialog dialog = MessagesController.getInstance().dialogs_dict.get(dialog_id); + if (dialog != null) { + dialog.notify_settings = new TLRPC.TL_peerNotifySettings(); + } + NotificationsController.updateServerNotificationsSettings(dialog_id); + } + } else if (id == reply) { + if (selectedMessagesIds.size() == 1) { + ArrayList ids = new ArrayList<>(selectedMessagesIds.keySet()); + MessageObject messageObject = messagesDict.get(ids.get(0)); + if (messageObject != null && messageObject.messageOwner.id > 0) { + showReplyPanel(true, messageObject, null, null, false, true); + } + } + selectedMessagesIds.clear(); + selectedMessagesCanCopyIds.clear(); + actionBar.hideActionMode(); + updateVisibleRows(); + } + } + }); + + avatarContainer = new FrameLayoutFixed(context); + avatarContainer.setBackgroundResource(R.drawable.bar_selector); + avatarContainer.setPadding(AndroidUtilities.dp(8), 0, AndroidUtilities.dp(8), 0); + actionBar.addView(avatarContainer); + FrameLayout.LayoutParams layoutParams2 = (FrameLayout.LayoutParams) avatarContainer.getLayoutParams(); + layoutParams2.height = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams2.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.rightMargin = AndroidUtilities.dp(40); + layoutParams2.leftMargin = AndroidUtilities.dp(56); + layoutParams2.gravity = Gravity.TOP | Gravity.LEFT; + avatarContainer.setLayoutParams(layoutParams2); + avatarContainer.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (currentUser != null) { + Bundle args = new Bundle(); + args.putInt("user_id", currentUser.id); + if (currentEncryptedChat != null) { + args.putLong("dialog_id", dialog_id); + } + presentFragment(new ProfileActivity(args)); + } else if (currentChat != null) { + Bundle args = new Bundle(); + args.putInt("chat_id", currentChat.id); + ProfileActivity fragment = new ProfileActivity(args); + fragment.setChatInfo(info); + presentFragment(fragment); + } + } + }); + + if (currentChat != null) { + int count = currentChat.participants_count; + if (info != null) { + count = info.participants.size(); + } + if (count == 0 || currentChat.left || currentChat instanceof TLRPC.TL_chatForbidden || info != null && info instanceof TLRPC.TL_chatParticipantsForbidden) { + avatarContainer.setEnabled(false); + } + } + + avatarImageView = new BackupImageView(context); + avatarImageView.setRoundRadius(AndroidUtilities.dp(21)); + avatarContainer.addView(avatarImageView); + layoutParams2 = (FrameLayout.LayoutParams) avatarImageView.getLayoutParams(); + layoutParams2.width = AndroidUtilities.dp(42); + layoutParams2.height = AndroidUtilities.dp(42); + layoutParams2.topMargin = AndroidUtilities.dp(3); + layoutParams2.gravity = Gravity.TOP | Gravity.LEFT; + avatarImageView.setLayoutParams(layoutParams2); + + if (currentEncryptedChat != null) { + timeItem = new ImageView(context); + timeItem.setPadding(AndroidUtilities.dp(10), AndroidUtilities.dp(10), AndroidUtilities.dp(5), AndroidUtilities.dp(5)); + timeItem.setScaleType(ImageView.ScaleType.CENTER); + avatarContainer.addView(timeItem); + timerDrawable = new TimerDrawable(context); + + layoutParams2 = (FrameLayout.LayoutParams) timeItem.getLayoutParams(); + layoutParams2.width = AndroidUtilities.dp(34); + layoutParams2.height = AndroidUtilities.dp(34); + layoutParams2.topMargin = AndroidUtilities.dp(18); + layoutParams2.leftMargin = AndroidUtilities.dp(16); + layoutParams2.gravity = Gravity.TOP | Gravity.LEFT; + timeItem.setLayoutParams(layoutParams2); + timeItem.setImageDrawable(timerDrawable); + + timeItem.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (getParentActivity() == null) { + return; + } + showAlertDialog(AndroidUtilities.buildTTLAlert(getParentActivity(), currentEncryptedChat)); } }); + } - bottomOverlayChatText = new TextView(getParentActivity()); - bottomOverlayChatText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - bottomOverlayChatText.setTextColor(0xff3e6fa1); - bottomOverlayChat.addView(bottomOverlayChatText); - layoutParams2 = (FrameLayout.LayoutParams) bottomOverlayChatText.getLayoutParams(); + nameTextView = new TextView(context); + nameTextView.setTextColor(0xffffffff); + nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); + nameTextView.setLines(1); + nameTextView.setMaxLines(1); + nameTextView.setSingleLine(true); + nameTextView.setEllipsize(TextUtils.TruncateAt.END); + nameTextView.setGravity(Gravity.LEFT); + nameTextView.setCompoundDrawablePadding(AndroidUtilities.dp(4)); + nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); + avatarContainer.addView(nameTextView); + layoutParams2 = (FrameLayout.LayoutParams) nameTextView.getLayoutParams(); + layoutParams2.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.leftMargin = AndroidUtilities.dp(54); + layoutParams2.bottomMargin = AndroidUtilities.dp(22); + layoutParams2.gravity = Gravity.BOTTOM; + nameTextView.setLayoutParams(layoutParams2); + + onlineTextView = new TextView(context); + onlineTextView.setTextColor(0xffd7e8f7); + onlineTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + onlineTextView.setLines(1); + onlineTextView.setMaxLines(1); + onlineTextView.setSingleLine(true); + onlineTextView.setEllipsize(TextUtils.TruncateAt.END); + onlineTextView.setGravity(Gravity.LEFT); + avatarContainer.addView(onlineTextView); + layoutParams2 = (FrameLayout.LayoutParams) onlineTextView.getLayoutParams(); + layoutParams2.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.leftMargin = AndroidUtilities.dp(54); + layoutParams2.bottomMargin = AndroidUtilities.dp(4); + layoutParams2.gravity = Gravity.BOTTOM; + onlineTextView.setLayoutParams(layoutParams2); + + ActionBarMenu menu = actionBar.createMenu(); + + headerItem = menu.addItem(0, R.drawable.ic_ab_other); + if (currentUser != null) { + addContactItem = headerItem.addSubItem(share_contact, "", 0); + } + if (currentEncryptedChat != null) { + timeItem2 = headerItem.addSubItem(chat_enc_timer, LocaleController.getString("SetTimer", R.string.SetTimer), 0); + } + headerItem.addSubItem(clear_history, LocaleController.getString("ClearHistory", R.string.ClearHistory), 0); + if (currentChat != null && !isBroadcast) { + headerItem.addSubItem(delete_chat, LocaleController.getString("DeleteAndExit", R.string.DeleteAndExit), 0); + } else { + headerItem.addSubItem(delete_chat, LocaleController.getString("DeleteChatUser", R.string.DeleteChatUser), 0); + } + muteItem = headerItem.addSubItem(mute, null, 0); + + LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) headerItem.getLayoutParams(); + layoutParams.rightMargin = AndroidUtilities.dp(-48); + headerItem.setLayoutParams(layoutParams); + + updateTitle(); + updateSubtitle(); + updateTitleIcons(); + + attachItem = menu.addItem(chat_menu_attach, R.drawable.ic_ab_other); + attachItem.addSubItem(attach_photo, LocaleController.getString("ChatTakePhoto", R.string.ChatTakePhoto), R.drawable.ic_attach_photo); + attachItem.addSubItem(attach_gallery, LocaleController.getString("ChatGallery", R.string.ChatGallery), R.drawable.ic_attach_gallery); + attachItem.addSubItem(attach_video, LocaleController.getString("ChatVideo", R.string.ChatVideo), R.drawable.ic_attach_video); + attachItem.addSubItem(attach_document, LocaleController.getString("ChatDocument", R.string.ChatDocument), R.drawable.ic_ab_doc); + attachItem.addSubItem(attach_location, LocaleController.getString("ChatLocation", R.string.ChatLocation), R.drawable.ic_attach_location); + attachItem.setVisibility(View.INVISIBLE); + + menuItem = menu.addItem(chat_menu_attach, R.drawable.ic_ab_attach); + menuItem.addSubItem(attach_photo, LocaleController.getString("ChatTakePhoto", R.string.ChatTakePhoto), R.drawable.ic_attach_photo); + menuItem.addSubItem(attach_gallery, LocaleController.getString("ChatGallery", R.string.ChatGallery), R.drawable.ic_attach_gallery); + menuItem.addSubItem(attach_video, LocaleController.getString("ChatVideo", R.string.ChatVideo), R.drawable.ic_attach_video); + menuItem.addSubItem(attach_document, LocaleController.getString("ChatDocument", R.string.ChatDocument), R.drawable.ic_ab_doc); + menuItem.addSubItem(attach_location, LocaleController.getString("ChatLocation", R.string.ChatLocation), R.drawable.ic_attach_location); + menuItem.setShowFromBottom(true); + menuItem.setBackgroundDrawable(null); + + actionModeViews.clear(); + + final ActionBarMenu actionMode = actionBar.createActionMode(); + actionModeViews.add(actionMode.addItem(-2, R.drawable.ic_ab_back_grey, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); + + selectedMessagesCountTextView = new TextView(actionMode.getContext()); + selectedMessagesCountTextView.setTextSize(18); + selectedMessagesCountTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); + selectedMessagesCountTextView.setTextColor(0xff737373); + selectedMessagesCountTextView.setSingleLine(true); + selectedMessagesCountTextView.setLines(1); + selectedMessagesCountTextView.setEllipsize(TextUtils.TruncateAt.END); + selectedMessagesCountTextView.setPadding(AndroidUtilities.dp(11), 0, 0, AndroidUtilities.dp(2)); + selectedMessagesCountTextView.setGravity(Gravity.CENTER_VERTICAL); + selectedMessagesCountTextView.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + actionMode.addView(selectedMessagesCountTextView); + layoutParams = (LinearLayout.LayoutParams) selectedMessagesCountTextView.getLayoutParams(); + layoutParams.weight = 1; + layoutParams.width = 0; + layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT; + selectedMessagesCountTextView.setLayoutParams(layoutParams); + + if (currentEncryptedChat == null) { + actionModeViews.add(actionMode.addItem(copy, R.drawable.ic_ab_fwd_copy, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); + if (!isBroadcast) { + actionModeViews.add(actionMode.addItem(reply, R.drawable.ic_ab_reply, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); + } + actionModeViews.add(actionMode.addItem(forward, R.drawable.ic_ab_fwd_forward, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); + actionModeViews.add(actionMode.addItem(delete, R.drawable.ic_ab_fwd_delete, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); + } else { + actionModeViews.add(actionMode.addItem(copy, R.drawable.ic_ab_fwd_copy, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); + actionModeViews.add(actionMode.addItem(delete, R.drawable.ic_ab_fwd_delete, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); + } + actionMode.getItem(copy).setVisibility(selectedMessagesCanCopyIds.size() != 0 ? View.VISIBLE : View.GONE); + if (actionMode.getItem(reply) != null) { + actionMode.getItem(reply).setVisibility(selectedMessagesIds.size() == 1 ? View.VISIBLE : View.GONE); + } + checkActionBarMenu(); + + fragmentView = new SizeNotifierRelativeLayout(context); + SizeNotifierRelativeLayout contentView = (SizeNotifierRelativeLayout) fragmentView; + + contentView.setBackgroundImage(ApplicationLoader.getCachedWallpaper()); + + emptyViewContainer = new FrameLayout(context); + emptyViewContainer.setPadding(0, 0, 0, AndroidUtilities.dp(48)); + emptyViewContainer.setVisibility(View.INVISIBLE); + contentView.addView(emptyViewContainer); + RelativeLayout.LayoutParams layoutParams3 = (RelativeLayout.LayoutParams) emptyViewContainer.getLayoutParams(); + layoutParams3.width = RelativeLayout.LayoutParams.MATCH_PARENT; + layoutParams3.height = RelativeLayout.LayoutParams.MATCH_PARENT; + emptyViewContainer.setLayoutParams(layoutParams3); + emptyViewContainer.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + + if (currentEncryptedChat == null) { + TextView emptyView = new TextView(context); + if (currentUser != null && currentUser.id != 777000 && (currentUser.id / 1000 == 333 || currentUser.id % 1000 == 0)) { + emptyView.setText(LocaleController.getString("GotAQuestion", R.string.GotAQuestion)); + } else { + emptyView.setText(LocaleController.getString("NoMessages", R.string.NoMessages)); + } + emptyView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); + emptyView.setGravity(Gravity.CENTER); + emptyView.setTextColor(0xffffffff); + emptyView.setBackgroundResource(ApplicationLoader.isCustomTheme() ? R.drawable.system_black : R.drawable.system_blue); + emptyView.setPadding(AndroidUtilities.dp(7), AndroidUtilities.dp(1), AndroidUtilities.dp(7), AndroidUtilities.dp(1)); + emptyViewContainer.addView(emptyView); + layoutParams2 = (FrameLayout.LayoutParams) emptyView.getLayoutParams(); layoutParams2.width = FrameLayout.LayoutParams.WRAP_CONTENT; layoutParams2.height = FrameLayout.LayoutParams.WRAP_CONTENT; layoutParams2.gravity = Gravity.CENTER; - bottomOverlayChatText.setLayoutParams(layoutParams2); + emptyView.setLayoutParams(layoutParams2); + } else { + LinearLayout secretChatPlaceholder = new LinearLayout(context); + secretChatPlaceholder.setBackgroundResource(ApplicationLoader.isCustomTheme() ? R.drawable.system_black : R.drawable.system_blue); + secretChatPlaceholder.setPadding(AndroidUtilities.dp(16), AndroidUtilities.dp(12), AndroidUtilities.dp(16), AndroidUtilities.dp(12)); + secretChatPlaceholder.setOrientation(LinearLayout.VERTICAL); + emptyViewContainer.addView(secretChatPlaceholder); + layoutParams2 = (FrameLayout.LayoutParams) secretChatPlaceholder.getLayoutParams(); + layoutParams2.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.gravity = Gravity.CENTER; + secretChatPlaceholder.setLayoutParams(layoutParams2); - pagedownButton = new ImageView(getParentActivity()); - pagedownButton.setVisibility(View.INVISIBLE); - pagedownButton.setImageResource(R.drawable.pagedown); - contentView.addView(pagedownButton); - layoutParams3 = (RelativeLayout.LayoutParams) pagedownButton.getLayoutParams(); - layoutParams3.width = RelativeLayout.LayoutParams.WRAP_CONTENT; - layoutParams3.height = RelativeLayout.LayoutParams.WRAP_CONTENT; - layoutParams3.rightMargin = AndroidUtilities.dp(6); - layoutParams3.bottomMargin = AndroidUtilities.dp(4); - layoutParams3.addRule(RelativeLayout.ABOVE, id_chat_compose_panel); - layoutParams3.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); - pagedownButton.setLayoutParams(layoutParams3); - pagedownButton.setOnClickListener(new View.OnClickListener() { + secretViewStatusTextView = new TextView(context); + secretViewStatusTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); + secretViewStatusTextView.setTextColor(0xffffffff); + secretViewStatusTextView.setGravity(Gravity.CENTER_HORIZONTAL); + secretViewStatusTextView.setMaxWidth(AndroidUtilities.dp(210)); + if (currentEncryptedChat.admin_id == UserConfig.getClientUserId()) { + if (currentUser.first_name.length() > 0) { + secretViewStatusTextView.setText(LocaleController.formatString("EncryptedPlaceholderTitleOutgoing", R.string.EncryptedPlaceholderTitleOutgoing, currentUser.first_name)); + } else { + secretViewStatusTextView.setText(LocaleController.formatString("EncryptedPlaceholderTitleOutgoing", R.string.EncryptedPlaceholderTitleOutgoing, currentUser.last_name)); + } + } else { + if (currentUser.first_name.length() > 0) { + secretViewStatusTextView.setText(LocaleController.formatString("EncryptedPlaceholderTitleIncoming", R.string.EncryptedPlaceholderTitleIncoming, currentUser.first_name)); + } else { + secretViewStatusTextView.setText(LocaleController.formatString("EncryptedPlaceholderTitleIncoming", R.string.EncryptedPlaceholderTitleIncoming, currentUser.last_name)); + } + } + secretChatPlaceholder.addView(secretViewStatusTextView); + layoutParams = (LinearLayout.LayoutParams) secretViewStatusTextView.getLayoutParams(); + layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams.gravity = Gravity.CENTER_HORIZONTAL; + secretViewStatusTextView.setLayoutParams(layoutParams); + + TextView textView = new TextView(context); + textView.setText(LocaleController.getString("EncryptedDescriptionTitle", R.string.EncryptedDescriptionTitle)); + textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); + textView.setTextColor(0xffffffff); + textView.setGravity(Gravity.CENTER_HORIZONTAL); + textView.setMaxWidth(AndroidUtilities.dp(260)); + secretChatPlaceholder.addView(textView); + layoutParams = (LinearLayout.LayoutParams) textView.getLayoutParams(); + layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams.topMargin = AndroidUtilities.dp(8); + layoutParams.gravity = LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT; + textView.setLayoutParams(layoutParams); + + for (int a = 0; a < 4; a++) { + LinearLayout linearLayout = new LinearLayout(context); + linearLayout.setOrientation(LinearLayout.HORIZONTAL); + secretChatPlaceholder.addView(linearLayout); + layoutParams = (LinearLayout.LayoutParams) linearLayout.getLayoutParams(); + layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams.topMargin = AndroidUtilities.dp(8); + layoutParams.gravity = LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT; + linearLayout.setLayoutParams(layoutParams); + + ImageView imageView = new ImageView(context); + imageView.setImageResource(R.drawable.ic_lock_white); + + textView = new TextView(context); + textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); + textView.setTextColor(0xffffffff); + textView.setGravity(Gravity.CENTER_VERTICAL | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); + textView.setMaxWidth(AndroidUtilities.dp(260)); + + switch (a) { + case 0: + textView.setText(LocaleController.getString("EncryptedDescription1", R.string.EncryptedDescription1)); + break; + case 1: + textView.setText(LocaleController.getString("EncryptedDescription2", R.string.EncryptedDescription2)); + break; + case 2: + textView.setText(LocaleController.getString("EncryptedDescription3", R.string.EncryptedDescription3)); + break; + case 3: + textView.setText(LocaleController.getString("EncryptedDescription4", R.string.EncryptedDescription4)); + break; + } + + if (LocaleController.isRTL) { + linearLayout.addView(textView); + linearLayout.addView(imageView); + } else { + linearLayout.addView(imageView); + linearLayout.addView(textView); + } + layoutParams = (LinearLayout.LayoutParams) imageView.getLayoutParams(); + layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams.rightMargin = LocaleController.isRTL ? 0 : AndroidUtilities.dp(8); + layoutParams.leftMargin = LocaleController.isRTL ? AndroidUtilities.dp(8) : 0; + layoutParams.topMargin = AndroidUtilities.dp(LocaleController.isRTL ? 3 : 4); + imageView.setLayoutParams(layoutParams); + + layoutParams = (LinearLayout.LayoutParams) textView.getLayoutParams(); + layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT; + textView.setLayoutParams(layoutParams); + } + } + + chatListView = new LayoutListView(context); + chatListView.setAdapter(chatAdapter = new ChatAdapter(context)); + chatListView.setCacheColorHint(ApplicationLoader.getSelectedColor()); + chatListView.setClipToPadding(false); + chatListView.setStackFromBottom(true); + chatListView.setPadding(0, AndroidUtilities.dp(4), 0, AndroidUtilities.dp(3)); + chatListView.setDivider(null); + chatListView.setSelector(R.drawable.transparent); + chatListView.setOnItemLongClickListener(onItemLongClickListener); + chatListView.setOnItemClickListener(onItemClickListener); + contentView.addView(chatListView); + layoutParams3 = (RelativeLayout.LayoutParams) chatListView.getLayoutParams(); + layoutParams3.width = RelativeLayout.LayoutParams.MATCH_PARENT; + layoutParams3.height = RelativeLayout.LayoutParams.MATCH_PARENT; + layoutParams3.bottomMargin = -AndroidUtilities.dp(3); + layoutParams3.addRule(RelativeLayout.ABOVE, id_chat_compose_panel); + chatListView.setLayoutParams(layoutParams3); + chatListView.setOnInterceptTouchEventListener(new LayoutListView.OnInterceptTouchEventListener() { + @Override + public boolean onInterceptTouchEvent(MotionEvent event) { + if (actionBar.isActionModeShowed()) { + return false; + } + if (event.getAction() == MotionEvent.ACTION_DOWN) { + int x = (int) event.getX(); + int y = (int) event.getY(); + int count = chatListView.getChildCount(); + Rect rect = new Rect(); + for (int a = 0; a < count; a++) { + View view = chatListView.getChildAt(a); + int top = view.getTop(); + int bottom = view.getBottom(); + view.getLocalVisibleRect(rect); + if (top > y || bottom < y) { + continue; + } + if (!(view instanceof ChatMediaCell)) { + break; + } + final ChatMediaCell cell = (ChatMediaCell) view; + final MessageObject messageObject = cell.getMessageObject(); + if (messageObject == null || !messageObject.isSecretPhoto() || !cell.getPhotoImage().isInsideImage(x, y - top)) { + break; + } + File file = FileLoader.getPathToMessage(messageObject.messageOwner); + if (!file.exists()) { + break; + } + startX = x; + startY = y; + chatListView.setOnItemClickListener(null); + openSecretPhotoRunnable = new Runnable() { + @Override + public void run() { + if (openSecretPhotoRunnable == null) { + return; + } + chatListView.requestDisallowInterceptTouchEvent(true); + chatListView.setOnItemLongClickListener(null); + chatListView.setLongClickable(false); + openSecretPhotoRunnable = null; + if (sendSecretMessageRead(messageObject)) { + cell.invalidate(); + } + SecretPhotoViewer.getInstance().setParentActivity(getParentActivity()); + SecretPhotoViewer.getInstance().openPhoto(messageObject); + } + }; + AndroidUtilities.runOnUIThread(openSecretPhotoRunnable, 100); + return true; + } + } + return false; + } + }); + chatListView.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + if (openSecretPhotoRunnable != null || SecretPhotoViewer.getInstance().isVisible()) { + if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_POINTER_UP) { + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + chatListView.setOnItemClickListener(onItemClickListener); + } + }, 150); + if (openSecretPhotoRunnable != null) { + AndroidUtilities.cancelRunOnUIThread(openSecretPhotoRunnable); + openSecretPhotoRunnable = null; + try { + Toast.makeText(v.getContext(), LocaleController.getString("PhotoTip", R.string.PhotoTip), Toast.LENGTH_SHORT).show(); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } else { + if (SecretPhotoViewer.getInstance().isVisible()) { + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + chatListView.setOnItemLongClickListener(onItemLongClickListener); + chatListView.setLongClickable(true); + } + }); + SecretPhotoViewer.getInstance().closePhoto(); + } + } + } else if (event.getAction() != MotionEvent.ACTION_DOWN) { + if (SecretPhotoViewer.getInstance().isVisible()) { + return true; + } else if (openSecretPhotoRunnable != null) { + if (event.getAction() == MotionEvent.ACTION_MOVE) { + if (Math.hypot(startX - event.getX(), startY - event.getY()) > AndroidUtilities.dp(5)) { + AndroidUtilities.cancelRunOnUIThread(openSecretPhotoRunnable); + openSecretPhotoRunnable = null; + } + } else { + AndroidUtilities.cancelRunOnUIThread(openSecretPhotoRunnable); + openSecretPhotoRunnable = null; + } + } + } + } + return false; + } + }); + chatListView.setOnScrollListener(new AbsListView.OnScrollListener() { + Rect scrollRect = new Rect(); + + @Override + public void onScrollStateChanged(AbsListView absListView, int i) { + if (i == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL || i == AbsListView.OnScrollListener.SCROLL_STATE_FLING && highlightMessageId != Integer.MAX_VALUE) { + highlightMessageId = Integer.MAX_VALUE; + updateVisibleRows(); + } + } + + @Override + public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + if (visibleItemCount > 0) { + if (firstVisibleItem <= 10) { + if (!endReached && !loading) { + if (messagesByDays.size() != 0) { + MessagesController.getInstance().loadMessages(dialog_id, 20, maxMessageId, !cacheEndReaced && startLoadFromMessageId == 0, minDate, classGuid, 0, 0, 0, startLoadFromMessageId == 0); + } else { + MessagesController.getInstance().loadMessages(dialog_id, 20, 0, !cacheEndReaced && startLoadFromMessageId == 0, minDate, classGuid, 0, 0, 0, startLoadFromMessageId == 0); + } + loading = true; + } + } + if (firstVisibleItem + visibleItemCount >= totalItemCount - 6) { + if (!forward_end_reached && !loadingForward) { + MessagesController.getInstance().loadMessages(dialog_id, 20, minMessageId, startLoadFromMessageId == 0, maxDate, classGuid, 1, 0, 0, startLoadFromMessageId == 0); + loadingForward = true; + } + } + if (firstVisibleItem + visibleItemCount == totalItemCount && forward_end_reached) { + showPagedownButton(false, true); + } + } + for (int a = 0; a < visibleItemCount; a++) { + View view = absListView.getChildAt(a); + if (view instanceof ChatMessageCell) { + ChatMessageCell messageCell = (ChatMessageCell) view; + messageCell.getLocalVisibleRect(scrollRect); + messageCell.setVisiblePart(scrollRect.top, scrollRect.bottom - scrollRect.top); + } + } + } + }); + + progressView = new FrameLayout(context); + progressView.setVisibility(View.INVISIBLE); + progressView.setBackgroundResource(ApplicationLoader.isCustomTheme() ? R.drawable.system_loader2 : R.drawable.system_loader1); + contentView.addView(progressView); + layoutParams3 = (RelativeLayout.LayoutParams) progressView.getLayoutParams(); + layoutParams3.width = AndroidUtilities.dp(36); + layoutParams3.height = AndroidUtilities.dp(36); + layoutParams3.bottomMargin = AndroidUtilities.dp(48); + layoutParams3.addRule(RelativeLayout.CENTER_IN_PARENT); + progressView.setLayoutParams(layoutParams3); + + ProgressBar progressBar = new ProgressBar(context); + try { + progressBar.setIndeterminateDrawable(context.getResources().getDrawable(R.drawable.loading_animation)); + } catch (Exception e) { + //don't promt + } + progressBar.setIndeterminate(true); + AndroidUtilities.setProgressBarAnimationDuration(progressBar, 1500); + progressView.addView(progressBar); + layoutParams2 = (FrameLayout.LayoutParams) progressBar.getLayoutParams(); + layoutParams2.width = AndroidUtilities.dp(32); + layoutParams2.height = AndroidUtilities.dp(32); + layoutParams2.gravity = Gravity.CENTER; + progressBar.setLayoutParams(layoutParams2); + + if (currentEncryptedChat == null && !isBroadcast) { + mentionListView = new ListView(context); + mentionListView.setBackgroundResource(R.drawable.compose_panel); + mentionListView.setVisibility(View.GONE); + mentionListView.setPadding(0, AndroidUtilities.dp(2), 0, 0); + mentionListView.setClipToPadding(true); + mentionListView.setDividerHeight(0); + mentionListView.setDivider(null); + if (Build.VERSION.SDK_INT > 8) { + mentionListView.setOverScrollMode(ListView.OVER_SCROLL_NEVER); + } + contentView.addView(mentionListView); + layoutParams3 = (RelativeLayout.LayoutParams) mentionListView.getLayoutParams(); + layoutParams3.width = RelativeLayout.LayoutParams.MATCH_PARENT; + layoutParams3.height = AndroidUtilities.dp(110); + layoutParams3.topMargin = -AndroidUtilities.dp(108); + layoutParams3.addRule(RelativeLayout.ALIGN_TOP, id_chat_compose_panel); + mentionListView.setLayoutParams(layoutParams3); + + mentionListView.setAdapter(mentionsAdapter = new MentionsAdapter(context, new MentionsAdapter.MentionsAdapterDelegate() { @Override - public void onClick(View view) { - if (returnToMessageId > 0) { - scrollToMessageId(returnToMessageId, 0, true); + public void needChangePanelVisibility(boolean show) { + if (show) { + RelativeLayout.LayoutParams layoutParams3 = (RelativeLayout.LayoutParams) mentionListView.getLayoutParams(); + int height = 36 * Math.min(3, mentionsAdapter.getCount()) + (mentionsAdapter.getCount() > 3 ? 18 : 0); + layoutParams3.height = AndroidUtilities.dp(2 + height); + layoutParams3.topMargin = -AndroidUtilities.dp(height); + mentionListView.setLayoutParams(layoutParams3); + + if (mentionListAnimation != null) { + mentionListAnimation.cancel(); + mentionListAnimation = null; + } + + if (mentionListView.getVisibility() == View.VISIBLE) { + ViewProxy.setAlpha(mentionListView, 1.0f); + return; + } + if (allowStickersPanel) { + mentionListView.setVisibility(View.VISIBLE); + mentionListAnimation = new AnimatorSetProxy(); + mentionListAnimation.playTogether( + ObjectAnimatorProxy.ofFloat(mentionListView, "alpha", 0.0f, 1.0f) + ); + mentionListAnimation.addListener(new AnimatorListenerAdapterProxy() { + @Override + public void onAnimationEnd(Object animation) { + if (mentionListAnimation != null && mentionListAnimation.equals(animation)) { + mentionListView.clearAnimation(); + mentionListAnimation = null; + } + } + }); + mentionListAnimation.setDuration(200); + mentionListAnimation.start(); + } else { + ViewProxy.setAlpha(mentionListView, 1.0f); + mentionListView.clearAnimation(); + mentionListView.setVisibility(View.INVISIBLE); + } } else { - scrollToLastMessage(); + if (mentionListAnimation != null) { + mentionListAnimation.cancel(); + mentionListAnimation = null; + } + + if (mentionListView.getVisibility() == View.GONE) { + return; + } + if (allowStickersPanel) { + mentionListAnimation = new AnimatorSetProxy(); + mentionListAnimation.playTogether( + ObjectAnimatorProxy.ofFloat(mentionListView, "alpha", 0.0f) + ); + mentionListAnimation.addListener(new AnimatorListenerAdapterProxy() { + @Override + public void onAnimationEnd(Object animation) { + if (mentionListAnimation != null && mentionListAnimation.equals(animation)) { + mentionListView.clearAnimation(); + mentionListView.setVisibility(View.GONE); + mentionListAnimation = null; + } + } + }); + mentionListAnimation.setDuration(200); + mentionListAnimation.start(); + } else { + mentionListView.clearAnimation(); + mentionListView.setVisibility(View.GONE); + } + } + } + })); + mentionsAdapter.setChatInfo(info); + mentionsAdapter.setNeedUsernames(currentChat != null); + + mentionListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + Object object = mentionsAdapter.getItem(position); + int start = mentionsAdapter.getResultStartPosition(); + int len = mentionsAdapter.getResultLength(); + if (object instanceof TLRPC.User) { + TLRPC.User user = (TLRPC.User) object; + if (user != null) { + chatActivityEnterView.replaceWithText(start, len, "@" + user.username + " "); + } + } else if (object instanceof String) { + chatActivityEnterView.replaceWithText(start, len, object + " "); } } }); - if (loading && messages.isEmpty()) { - progressView.setVisibility(View.VISIBLE); - chatListView.setEmptyView(null); - } else { - progressView.setVisibility(View.INVISIBLE); - chatListView.setEmptyView(emptyViewContainer); + mentionListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { + @Override + public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { + Object object = mentionsAdapter.getItem(position); + if (object instanceof String) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + builder.setMessage(LocaleController.getString("ClearSearch", R.string.ClearSearch)); + builder.setPositiveButton(LocaleController.getString("ClearButton", R.string.ClearButton).toUpperCase(), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + mentionsAdapter.clearRecentHashtags(); + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + return true; + } + return false; + } + }); + } + + if (chatActivityEnterView != null) { + chatActivityEnterView.onDestroy(); + } + chatActivityEnterView = new ChatActivityEnterView(getParentActivity(), contentView, this, true); + chatActivityEnterView.setDialogId(dialog_id); + chatActivityEnterView.addToAttachLayout(menuItem); + chatActivityEnterView.setId(id_chat_compose_panel); + contentView.addView(chatActivityEnterView); + layoutParams3 = (RelativeLayout.LayoutParams) chatActivityEnterView.getLayoutParams(); + layoutParams3.width = RelativeLayout.LayoutParams.MATCH_PARENT; + layoutParams3.height = RelativeLayout.LayoutParams.WRAP_CONTENT; + layoutParams3.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); + chatActivityEnterView.setLayoutParams(layoutParams3); + chatActivityEnterView.setDelegate(new ChatActivityEnterView.ChatActivityEnterViewDelegate() { + @Override + public void onMessageSend(String message) { + moveScrollToLastMessage(); + showReplyPanel(false, null, null, null, false, true); + if (mentionsAdapter != null) { + mentionsAdapter.addHashtagsFromMessage(message); + } + if (message != null) { + NotificationsController.getInstance().playOutChatSound(); + } } - updateContactStatus(); - updateBottomOverlay(); - updateSecretStatus(); - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); + @Override + public void onTextChanged(final CharSequence text, boolean bigChange) { + if (stickersAdapter != null) { + stickersAdapter.loadStikersForEmoji(text); + } + if (mentionsAdapter != null) { + mentionsAdapter.searchUsernameOrHashtag(text.toString(), chatActivityEnterView.getCursorPosition(), messages); + } + if (waitingForCharaterEnterRunnable != null) { + AndroidUtilities.cancelRunOnUIThread(waitingForCharaterEnterRunnable); + waitingForCharaterEnterRunnable = null; + } + if (bigChange) { + searchLinks(text, true); + } else { + waitingForCharaterEnterRunnable = new Runnable() { + @Override + public void run() { + if (this == waitingForCharaterEnterRunnable) { + searchLinks(text, false); + waitingForCharaterEnterRunnable = null; + } + } + }; + AndroidUtilities.runOnUIThread(waitingForCharaterEnterRunnable, 1000); + } } + + @Override + public void needSendTyping() { + MessagesController.getInstance().sendTyping(dialog_id, classGuid); + } + + @Override + public void onAttachButtonHidden() { + if (attachItem != null) { + attachItem.setVisibility(View.VISIBLE); + } + if (headerItem != null) { + headerItem.setVisibility(View.INVISIBLE); + } + } + + @Override + public void onAttachButtonShow() { + if (attachItem != null) { + attachItem.setVisibility(View.INVISIBLE); + } + if (headerItem != null) { + headerItem.setVisibility(View.VISIBLE); + } + } + + @Override + public void onWindowSizeChanged(int size) { + if (size < AndroidUtilities.dp(72) + AndroidUtilities.getCurrentActionBarHeight()) { + allowStickersPanel = false; + if (stickersPanel.getVisibility() == View.VISIBLE) { + stickersPanel.clearAnimation(); + stickersPanel.setVisibility(View.INVISIBLE); + } + if (mentionListView != null && mentionListView.getVisibility() == View.VISIBLE) { + mentionListView.clearAnimation(); + mentionListView.setVisibility(View.INVISIBLE); + } + } else { + allowStickersPanel = true; + if (stickersPanel.getVisibility() == View.INVISIBLE) { + stickersPanel.clearAnimation(); + stickersPanel.setVisibility(View.VISIBLE); + } + if (mentionListView != null && mentionListView.getVisibility() == View.INVISIBLE) { + mentionListView.clearAnimation(); + mentionListView.setVisibility(View.VISIBLE); + } + } + } + }); + + FrameLayout replyLayout = new FrameLayout(context); + replyLayout.setClickable(true); + chatActivityEnterView.addTopView(replyLayout, AndroidUtilities.dp(48)); + + View lineView = new View(context); + lineView.setBackgroundColor(0xffe8e8e8); + replyLayout.addView(lineView); + layoutParams2 = (FrameLayout.LayoutParams) lineView.getLayoutParams(); + layoutParams2.gravity = Gravity.BOTTOM; + layoutParams2.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams2.height = AndroidUtilities.dp(1); + lineView.setLayoutParams(layoutParams2); + + replyIconImageView = new ImageView(context); + replyIconImageView.setScaleType(ImageView.ScaleType.CENTER); + replyLayout.addView(replyIconImageView); + layoutParams2 = (FrameLayout.LayoutParams) replyIconImageView.getLayoutParams(); + layoutParams2.gravity = Gravity.TOP | Gravity.LEFT; + layoutParams2.width = AndroidUtilities.dp(52); + layoutParams2.height = AndroidUtilities.dp(46); + replyIconImageView.setLayoutParams(layoutParams2); + + ImageView imageView = new ImageView(context); + imageView.setImageResource(R.drawable.delete_reply); + imageView.setScaleType(ImageView.ScaleType.CENTER); + replyLayout.addView(imageView); + layoutParams2 = (FrameLayout.LayoutParams) imageView.getLayoutParams(); + layoutParams2.topMargin = AndroidUtilities.dp(0.5f); + layoutParams2.width = AndroidUtilities.dp(52); + layoutParams2.height = AndroidUtilities.dp(46); + layoutParams2.gravity = Gravity.RIGHT | Gravity.TOP; + imageView.setLayoutParams(layoutParams2); + imageView.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (forwardingMessages != null) { + forwardingMessages.clear(); + } + showReplyPanel(false, null, null, foundWebPage, true, true); + } + }); + + replyNameTextView = new TextView(context); + replyNameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + replyNameTextView.setTextColor(0xff377aae); + replyNameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); + replyNameTextView.setSingleLine(true); + replyNameTextView.setEllipsize(TextUtils.TruncateAt.END); + replyNameTextView.setMaxLines(1); + replyLayout.addView(replyNameTextView); + layoutParams2 = (FrameLayout.LayoutParams) replyNameTextView.getLayoutParams(); + layoutParams2.leftMargin = AndroidUtilities.dp(52); + layoutParams2.rightMargin = AndroidUtilities.dp(52); + layoutParams2.topMargin = AndroidUtilities.dp(4); + layoutParams2.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.gravity = Gravity.TOP | Gravity.LEFT; + replyNameTextView.setLayoutParams(layoutParams2); + + replyObjectTextView = new TextView(context); + replyObjectTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + replyObjectTextView.setTextColor(0xff999999); + replyObjectTextView.setSingleLine(true); + replyObjectTextView.setEllipsize(TextUtils.TruncateAt.END); + replyObjectTextView.setMaxLines(1); + replyLayout.addView(replyObjectTextView); + layoutParams2 = (FrameLayout.LayoutParams) replyObjectTextView.getLayoutParams(); + layoutParams2.leftMargin = AndroidUtilities.dp(52); + layoutParams2.rightMargin = AndroidUtilities.dp(52); + layoutParams2.topMargin = AndroidUtilities.dp(22); + layoutParams2.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.gravity = Gravity.TOP | Gravity.LEFT; + replyObjectTextView.setLayoutParams(layoutParams2); + + replyImageView = new BackupImageView(context); + replyLayout.addView(replyImageView); + layoutParams2 = (FrameLayout.LayoutParams) replyImageView.getLayoutParams(); + layoutParams2.leftMargin = AndroidUtilities.dp(52); + layoutParams2.topMargin = AndroidUtilities.dp(6); + layoutParams2.width = AndroidUtilities.dp(34); + layoutParams2.height = AndroidUtilities.dp(34); + layoutParams2.gravity = Gravity.TOP | Gravity.LEFT; + replyImageView.setLayoutParams(layoutParams2); + + stickersPanel = new FrameLayout(context); + stickersPanel.setVisibility(View.GONE); + contentView.addView(stickersPanel); + layoutParams3 = (RelativeLayout.LayoutParams) stickersPanel.getLayoutParams(); + layoutParams3.width = RelativeLayout.LayoutParams.WRAP_CONTENT; + layoutParams3.height = AndroidUtilities.dp(81.5f); + layoutParams3.bottomMargin = AndroidUtilities.dp(38); + layoutParams3.addRule(RelativeLayout.ALIGN_BOTTOM, id_chat_compose_panel); + stickersPanel.setLayoutParams(layoutParams3); + + stickersListView = new RecyclerListView(context); + LinearLayoutManager layoutManager = new LinearLayoutManager(context); + layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); + stickersListView.setLayoutManager(layoutManager); + stickersListView.setClipToPadding(false); + if (Build.VERSION.SDK_INT >= 9) { + stickersListView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER); } + stickersPanel.addView(stickersListView); + layoutParams2 = (FrameLayout.LayoutParams) stickersListView.getLayoutParams(); + layoutParams2.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams2.height = AndroidUtilities.dp(78); + stickersListView.setLayoutParams(layoutParams2); + if (currentEncryptedChat == null || currentEncryptedChat != null && AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 23) { + if (stickersAdapter != null) { + stickersAdapter.destroy(); + } + stickersListView.setPadding(AndroidUtilities.dp(18), 0, AndroidUtilities.dp(18), 0); + stickersListView.setAdapter(stickersAdapter = new StickersAdapter(context, new StickersAdapter.StickersAdapterDelegate() { + @Override + public void needChangePanelVisibility(final boolean show) { + if (show && stickersPanel.getVisibility() == View.VISIBLE || !show && stickersPanel.getVisibility() == View.GONE) { + return; + } + if (show) { + stickersListView.scrollToPosition(0); + stickersPanel.clearAnimation(); + stickersPanel.setVisibility(allowStickersPanel ? View.VISIBLE : View.INVISIBLE); + } + if (runningAnimation != null) { + runningAnimation.cancel(); + runningAnimation = null; + } + if (stickersPanel.getVisibility() != View.INVISIBLE) { + runningAnimation = new AnimatorSetProxy(); + runningAnimation.playTogether( + ObjectAnimatorProxy.ofFloat(stickersPanel, "alpha", show ? 0.0f : 1.0f, show ? 1.0f : 0.0f) + ); + runningAnimation.setDuration(150); + runningAnimation.addListener(new AnimatorListenerAdapterProxy() { + @Override + public void onAnimationEnd(Object animation) { + if (runningAnimation != null && runningAnimation.equals(animation)) { + if (!show) { + stickersAdapter.clearStickers(); + stickersPanel.clearAnimation(); + stickersPanel.setVisibility(View.GONE); + } + runningAnimation = null; + } + } + }); + runningAnimation.start(); + } else if (!show) { + stickersPanel.setVisibility(View.GONE); + } + } + })); + stickersListView.addOnItemTouchListener(new RecyclerListView.RecyclerListViewItemClickListener(context, new RecyclerListView.OnItemClickListener() { + @Override + public void onItemClick(View view, int position) { + TLRPC.Document document = stickersAdapter.getItem(position); + if (document instanceof TLRPC.TL_document) { + if (currentEncryptedChat != null && document.thumb instanceof TLRPC.TL_photoSize) { + File file = FileLoader.getPathToAttach(document.thumb, true); + if (file.exists()) { + try { + int len = (int) file.length(); + byte[] arr = new byte[(int) file.length()]; + RandomAccessFile reader = new RandomAccessFile(file, "r"); + reader.readFully(arr); + TLRPC.TL_document newDocument = new TLRPC.TL_document(); + newDocument.thumb = new TLRPC.TL_photoCachedSize(); + newDocument.thumb.location = document.thumb.location; + newDocument.thumb.size = document.thumb.size; + newDocument.thumb.w = document.thumb.w; + newDocument.thumb.h = document.thumb.h; + newDocument.thumb.type = document.thumb.type; + newDocument.thumb.bytes = arr; + + newDocument.id = document.id; + newDocument.access_hash = document.access_hash; + newDocument.date = document.date; + newDocument.mime_type = document.mime_type; + newDocument.size = document.size; + newDocument.dc_id = document.dc_id; + newDocument.attributes = document.attributes; + document = newDocument; + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + } + for (int a = 0; a < document.attributes.size(); a++) { + TLRPC.DocumentAttribute attribute = document.attributes.get(a); + if (attribute instanceof TLRPC.TL_documentAttributeSticker) { + document.attributes.remove(a); + document.attributes.add(new TLRPC.TL_documentAttributeSticker_old()); + break; + } + } + SendMessagesHelper.getInstance().sendMessage((TLRPC.TL_document) document, null, null, dialog_id, replyingMessageObject); + showReplyPanel(false, null, null, null, false, true); + } + chatActivityEnterView.setFieldText(""); + } + })); + } + + imageView = new ImageView(context); + imageView.setImageResource(R.drawable.stickers_back_arrow); + stickersPanel.addView(imageView); + layoutParams2 = (FrameLayout.LayoutParams) imageView.getLayoutParams(); + layoutParams2.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.gravity = Gravity.BOTTOM; + layoutParams2.leftMargin = AndroidUtilities.dp(53); + imageView.setLayoutParams(layoutParams2); + + bottomOverlay = new FrameLayout(context); + bottomOverlay.setBackgroundColor(0xffffffff); + bottomOverlay.setVisibility(View.INVISIBLE); + bottomOverlay.setFocusable(true); + bottomOverlay.setFocusableInTouchMode(true); + bottomOverlay.setClickable(true); + contentView.addView(bottomOverlay); + layoutParams3 = (RelativeLayout.LayoutParams) bottomOverlay.getLayoutParams(); + layoutParams3.width = RelativeLayout.LayoutParams.MATCH_PARENT; + layoutParams3.height = AndroidUtilities.dp(48); + layoutParams3.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); + bottomOverlay.setLayoutParams(layoutParams3); + + bottomOverlayText = new TextView(context); + bottomOverlayText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); + bottomOverlayText.setTextColor(0xff7f7f7f); + bottomOverlay.addView(bottomOverlayText); + layoutParams2 = (FrameLayout.LayoutParams) bottomOverlayText.getLayoutParams(); + layoutParams2.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.gravity = Gravity.CENTER; + bottomOverlayText.setLayoutParams(layoutParams2); + + bottomOverlayChat = new FrameLayout(context); + bottomOverlayChat.setBackgroundColor(0xfffbfcfd); + bottomOverlayChat.setVisibility(View.INVISIBLE); + contentView.addView(bottomOverlayChat); + layoutParams3 = (RelativeLayout.LayoutParams) bottomOverlayChat.getLayoutParams(); + layoutParams3.width = RelativeLayout.LayoutParams.MATCH_PARENT; + layoutParams3.height = AndroidUtilities.dp(48); + layoutParams3.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); + bottomOverlayChat.setLayoutParams(layoutParams3); + bottomOverlayChat.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + if (getParentActivity() == null) { + return; + } + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + if (currentUser != null && userBlocked) { + builder.setMessage(LocaleController.getString("AreYouSureUnblockContact", R.string.AreYouSureUnblockContact)); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + MessagesController.getInstance().unblockUser(currentUser.id); + } + }); + } else { + builder.setMessage(LocaleController.getString("AreYouSureDeleteThisChat", R.string.AreYouSureDeleteThisChat)); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + MessagesController.getInstance().deleteDialog(dialog_id, 0, false); + finishFragment(); + } + }); + } + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } + }); + + bottomOverlayChatText = new TextView(context); + bottomOverlayChatText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); + bottomOverlayChatText.setTextColor(0xff3e6fa1); + bottomOverlayChat.addView(bottomOverlayChatText); + layoutParams2 = (FrameLayout.LayoutParams) bottomOverlayChatText.getLayoutParams(); + layoutParams2.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.gravity = Gravity.CENTER; + bottomOverlayChatText.setLayoutParams(layoutParams2); + + pagedownButton = new ImageView(context); + pagedownButton.setVisibility(View.INVISIBLE); + pagedownButton.setImageResource(R.drawable.pagedown); + contentView.addView(pagedownButton); + layoutParams3 = (RelativeLayout.LayoutParams) pagedownButton.getLayoutParams(); + layoutParams3.width = RelativeLayout.LayoutParams.WRAP_CONTENT; + layoutParams3.height = RelativeLayout.LayoutParams.WRAP_CONTENT; + layoutParams3.rightMargin = AndroidUtilities.dp(6); + layoutParams3.bottomMargin = AndroidUtilities.dp(4); + layoutParams3.addRule(RelativeLayout.ABOVE, id_chat_compose_panel); + layoutParams3.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); + pagedownButton.setLayoutParams(layoutParams3); + pagedownButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + if (returnToMessageId > 0) { + scrollToMessageId(returnToMessageId, 0, true); + } else { + scrollToLastMessage(); + } + } + }); + + if (loading && messages.isEmpty()) { + progressView.setVisibility(View.VISIBLE); + chatListView.setEmptyView(null); + } else { + progressView.setVisibility(View.INVISIBLE); + chatListView.setEmptyView(emptyViewContainer); + } + + updateContactStatus(); + updateBottomOverlay(); + updateSecretStatus(); + return fragmentView; } + private void searchLinks(CharSequence charSequence, boolean force) { + if (currentEncryptedChat != null) { + return; + } + if (linkSearchRequestId != 0) { + ConnectionsManager.getInstance().cancelRpc(linkSearchRequestId, true); + linkSearchRequestId = 0; + } + if (force && foundWebPage != null) { + if (foundWebPage.url != null) { + int index = TextUtils.indexOf(charSequence, foundWebPage.url); + char lastChar; + boolean lenEqual; + if (index == -1) { + index = TextUtils.indexOf(charSequence, foundWebPage.display_url); + lenEqual = index != -1 && index + foundWebPage.display_url.length() == charSequence.length(); + lastChar = index != -1 && !lenEqual ? charSequence.charAt(index + foundWebPage.display_url.length()) : 0; + } else { + lenEqual = index != -1 && index + foundWebPage.url.length() == charSequence.length(); + lastChar = index != -1 && !lenEqual ? charSequence.charAt(index + foundWebPage.url.length()) : 0; + } + if (index != -1 && (lenEqual || lastChar == ' ' || lastChar == ',' || lastChar == '.' || lastChar == '!' || lastChar == '/')) { + return; + } + } + pendingLinkSearchString = null; + showReplyPanel(false, null, null, foundWebPage, false, true); + } + if (charSequence.length() == 0 || TextUtils.indexOf(charSequence, "http") == -1 && TextUtils.indexOf(charSequence, ".com/") == -1) { + return; + } + final TLRPC.TL_messages_getWebPagePreview req = new TLRPC.TL_messages_getWebPagePreview(); + if (charSequence instanceof String) { + req.message = (String) charSequence; + } else { + req.message = charSequence.toString(); + } + linkSearchRequestId = ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(final TLObject response, final TLRPC.TL_error error) { + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + linkSearchRequestId = 0; + if (error == null) { + if (response instanceof TLRPC.TL_messageMediaWebPage) { + foundWebPage = ((TLRPC.TL_messageMediaWebPage) response).webpage; + if (foundWebPage instanceof TLRPC.TL_webPage || foundWebPage instanceof TLRPC.TL_webPagePending) { + if (foundWebPage instanceof TLRPC.TL_webPagePending) { + pendingLinkSearchString = req.message; + } + showReplyPanel(true, null, null, foundWebPage, false, true); + } else { + if (foundWebPage != null) { + showReplyPanel(false, null, null, foundWebPage, false, true); + foundWebPage = null; + } + } + } else { + if (foundWebPage != null) { + showReplyPanel(false, null, null, foundWebPage, false, true); + foundWebPage = null; + } + } + } + } + }); + } + }); + ConnectionsManager.getInstance().bindRequestToGuid(linkSearchRequestId, classGuid); + } + private void forwardMessages(ArrayList arrayList, boolean fromMyName) { if (arrayList == null || arrayList.isEmpty()) { return; @@ -1954,9 +2045,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } - public void showReplyForMessageObjectOrForward(boolean show, MessageObject messageObject, ArrayList messageObjects, boolean animated) { + public void showReplyPanel(boolean show, MessageObject messageObject, ArrayList messageObjects, TLRPC.WebPage webPage, boolean cancel, boolean animated) { if (show) { - if (messageObject == null && messageObjects == null) { + if (messageObject == null && messageObjects == null && webPage == null) { return; } if (messageObject != null) { @@ -1965,9 +2056,13 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not return; } forwardingMessages = null; - replyIconImageView.setImageResource(R.drawable.reply); replyingMessageObject = messageObject; chatActivityEnterView.setReplyingMessageObject(messageObject); + + if (foundWebPage != null) { + return; + } + replyIconImageView.setImageResource(R.drawable.reply); replyNameTextView.setText(ContactsController.formatName(user.first_name, user.last_name)); if (messageObject.messageText != null) { String mess = messageObject.messageText.toString(); @@ -1981,12 +2076,16 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (messageObjects.isEmpty()) { return; } - chatActivityEnterView.setForceShowSendButton(true, animated); - chatActivityEnterView.setReplyingMessageObject(null); replyingMessageObject = null; + chatActivityEnterView.setReplyingMessageObject(null); + forwardingMessages = messageObjects; + + if (foundWebPage != null) { + return; + } + chatActivityEnterView.setForceShowSendButton(true, animated); ArrayList uids = new ArrayList<>(); replyIconImageView.setImageResource(R.drawable.forward_blue); - forwardingMessages = messageObjects; uids.add(messageObjects.get(0).messageOwner.from_id); int type = messageObjects.get(0).type; for (int a = 1; a < messageObjects.size(); a++) { @@ -2067,16 +2166,40 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } } + } else if (webPage != null) { + replyIconImageView.setImageResource(R.drawable.link); + if (webPage instanceof TLRPC.TL_webPagePending) { + replyNameTextView.setText(LocaleController.getString("GettingLinkInfo", R.string.GettingLinkInfo)); + replyObjectTextView.setText(pendingLinkSearchString); + } else { + if (webPage.site_name != null) { + replyNameTextView.setText(webPage.site_name); + } else if (webPage.title != null) { + replyNameTextView.setText(webPage.title); + } + if (webPage.description != null) { + replyObjectTextView.setText(webPage.description); + } else if (webPage.title != null && webPage.site_name != null) { + replyObjectTextView.setText(webPage.title); + } else if (webPage.author != null) { + replyObjectTextView.setText(webPage.author); + } else { + replyObjectTextView.setText(webPage.display_url); + } + chatActivityEnterView.setWebPage(webPage, true); + } } FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) replyNameTextView.getLayoutParams(); FrameLayout.LayoutParams layoutParams2 = (FrameLayout.LayoutParams) replyObjectTextView.getLayoutParams(); TLRPC.PhotoSize photoSize = messageObject != null ? FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, 80) : null; - if (photoSize == null || messageObject.type == 13) { + if (photoSize == null || messageObject != null && messageObject.type == 13) { replyImageView.setImageBitmap(null); + replyImageLocation = null; replyImageView.setVisibility(View.INVISIBLE); layoutParams1.leftMargin = layoutParams2.leftMargin = AndroidUtilities.dp(52); } else { - replyImageView.setImage(photoSize.location, "50_50", (Drawable) null); + replyImageLocation = photoSize.location; + replyImageView.setImage(replyImageLocation, "50_50", (Drawable) null); replyImageView.setVisibility(View.VISIBLE); layoutParams1.leftMargin = layoutParams2.leftMargin = AndroidUtilities.dp(96); } @@ -2084,9 +2207,17 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not replyObjectTextView.setLayoutParams(layoutParams2); chatActivityEnterView.showTopView(animated); } else { - if (replyingMessageObject == null && forwardingMessages == null) { + if (replyingMessageObject == null && forwardingMessages == null && foundWebPage == null) { return; } + if (foundWebPage != null) { + foundWebPage = null; + chatActivityEnterView.setWebPage(null, !cancel); + if (webPage != null && (replyingMessageObject != null || forwardingMessages != null)) { + showReplyPanel(true, replyingMessageObject, forwardingMessages, null, false, true); + return; + } + } if (forwardingMessages != null) { forwardMessages(forwardingMessages, false); } @@ -2095,6 +2226,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not chatActivityEnterView.setReplyingMessageObject(null); replyingMessageObject = null; forwardingMessages = null; + replyImageLocation = null; SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); preferences.edit().remove("reply_" + dialog_id).commit(); } @@ -2263,7 +2395,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not bottomOverlay.setVisibility(View.VISIBLE); hideKeyboard = true; } else if (currentEncryptedChat instanceof TLRPC.TL_encryptedChatWaiting) { - bottomOverlayText.setText(Html.fromHtml(LocaleController.formatString("AwaitingEncryption", R.string.AwaitingEncryption, "" + currentUser.first_name + ""))); + bottomOverlayText.setText(AndroidUtilities.replaceTags(LocaleController.formatString("AwaitingEncryption", R.string.AwaitingEncryption, "" + currentUser.first_name + ""))); bottomOverlay.setVisibility(View.VISIBLE); hideKeyboard = true; } else if (currentEncryptedChat instanceof TLRPC.TL_encryptedChatDiscarded) { @@ -2341,7 +2473,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not boolean isBroadcastError = isBroadcast && messageObject.getId() <= 0 && messageObject.isSendError(); if (!isBroadcast && messageObject.getId() <= 0 && messageObject.isOut() || isBroadcastError) { if (messageObject.isSendError()) { - if (!(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty)) { + if (!messageObject.isMediaEmpty()) { return 0; } else { return 7; @@ -2358,7 +2490,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } return 1; } else { - if (!(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty)) { + if (!messageObject.isMediaEmpty()) { if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVideo || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) { @@ -2402,7 +2534,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (messageObject.type == 6) { return -1; } else if (messageObject.isSendError()) { - if (!(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty)) { + if (!messageObject.isMediaEmpty()) { return 0; } else { return 7; @@ -2414,7 +2546,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not return 1; } } else { - if (!(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty)) { + if (!messageObject.isMediaEmpty()) { if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVideo || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) { @@ -2477,9 +2609,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not private void processRowSelect(View view) { MessageObject message = null; if (view instanceof ChatBaseCell) { - message = ((ChatBaseCell)view).getMessageObject(); + message = ((ChatBaseCell) view).getMessageObject(); } else if (view instanceof ChatActionCell) { - message = ((ChatActionCell)view).getMessageObject(); + message = ((ChatActionCell) view).getMessageObject(); } int type = getMessageType(message); @@ -2658,13 +2790,13 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not videoEditedInfo.resultHeight = resultHeight; videoEditedInfo.originalPath = videoPath; SendMessagesHelper.prepareSendingVideo(videoPath, estimatedSize, estimatedDuration, resultWidth, resultHeight, videoEditedInfo, dialog_id, replyingMessageObject); - showReplyForMessageObjectOrForward(false, null, null, true); + showReplyPanel(false, null, null, null, false, true); } }); if (parentLayout == null || !fragment.onFragmentCreate()) { SendMessagesHelper.prepareSendingVideo(videoPath, 0, 0, 0, 0, null, dialog_id, replyingMessageObject); - showReplyForMessageObjectOrForward(false, null, null, true); + showReplyPanel(false, null, null, null, false, true); return false; } parentLayout.presentFragment(fragment, removeLast, true, true); @@ -2689,7 +2821,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not try { ExifInterface ei = new ExifInterface(currentPicturePath); int exif = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); - switch(exif) { + switch (exif) { case ExifInterface.ORIENTATION_ROTATE_90: orientation = 90; break; @@ -2711,10 +2843,10 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not MediaController.PhotoEntry photoEntry = (MediaController.PhotoEntry) arrayList.get(0); if (photoEntry.imagePath != null) { SendMessagesHelper.prepareSendingPhoto(photoEntry.imagePath, null, dialog_id, replyingMessageObject); - showReplyForMessageObjectOrForward(false, null, null, true); + showReplyPanel(false, null, null, null, false, true); } else if (photoEntry.path != null) { SendMessagesHelper.prepareSendingPhoto(photoEntry.path, null, dialog_id, replyingMessageObject); - showReplyForMessageObjectOrForward(false, null, null, true); + showReplyPanel(false, null, null, null, false, true); } } }); @@ -2726,7 +2858,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not return; } SendMessagesHelper.prepareSendingPhoto(null, data.getData(), dialog_id, replyingMessageObject); - showReplyForMessageObjectOrForward(false, null, null, true); + showReplyPanel(false, null, null, null, false, true); } else if (requestCode == 2) { String videoPath = null; if (data != null) { @@ -2760,7 +2892,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } currentPicturePath = null; } - if(Build.VERSION.SDK_INT >= 16) { + if (Build.VERSION.SDK_INT >= 16) { if (paused) { startVideoEdit = videoPath; } else { @@ -2768,7 +2900,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } else { SendMessagesHelper.prepareSendingVideo(videoPath, 0, 0, 0, 0, null, dialog_id, replyingMessageObject); - showReplyForMessageObjectOrForward(false, null, null, true); + showReplyPanel(false, null, null, null, false, true); } } else if (requestCode == 21) { if (data == null || data.getData() == null) { @@ -2786,7 +2918,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not return; } SendMessagesHelper.prepareSendingDocument(tempPath, originalPath, null, null, dialog_id, replyingMessageObject); - showReplyForMessageObjectOrForward(false, null, null, true); + showReplyPanel(false, null, null, null, false, true); } } } @@ -2826,24 +2958,24 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not public void didReceivedNotification(int id, final Object... args) { if (id == NotificationCenter.messagesDidLoaded) { - long did = (Long)args[0]; + long did = (Long) args[0]; if (did == dialog_id) { loadsCount++; - int count = (Integer)args[1]; - boolean isCache = (Boolean)args[3]; - int fnid = (Integer)args[4]; - int last_unread_date = (Integer)args[8]; - int load_type = (Integer)args[9]; + int count = (Integer) args[1]; + boolean isCache = (Boolean) args[3]; + int fnid = (Integer) args[4]; + int last_unread_date = (Integer) args[8]; + int load_type = (Integer) args[9]; boolean wasUnread = false; if (fnid != 0) { first_unread_id = fnid; - last_message_id = (Integer)args[5]; - unread_to_load = (Integer)args[7]; + last_message_id = (Integer) args[5]; + unread_to_load = (Integer) args[7]; } else if (startLoadFromMessageId != 0 && load_type == 3) { - last_message_id = (Integer)args[5]; - first_message_id = (Integer)args[6]; + last_message_id = (Integer) args[5]; + first_message_id = (Integer) args[6]; } - ArrayList messArr = (ArrayList)args[2]; + ArrayList messArr = (ArrayList) args[2]; int newRowsCount = 0; @@ -3086,7 +3218,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not replyObjectTextView.invalidate(); } } else if (id == NotificationCenter.updateInterfaces) { - int updateMask = (Integer)args[0]; + int updateMask = (Integer) args[0]; if ((updateMask & MessagesController.UPDATE_MASK_NAME) != 0 || (updateMask & MessagesController.UPDATE_MASK_CHAT_NAME) != 0) { updateTitle(); } @@ -3118,19 +3250,19 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not updateContactStatus(); } } else if (id == NotificationCenter.didReceivedNewMessages) { - long did = (Long)args[0]; + long did = (Long) args[0]; if (did == dialog_id) { boolean updateChat = false; boolean hasFromMe = false; - ArrayList arr = (ArrayList)args[1]; + ArrayList arr = (ArrayList) args[1]; if (currentEncryptedChat != null && arr.size() == 1) { MessageObject obj = arr.get(0); if (currentEncryptedChat != null && obj.isOut() && obj.messageOwner.action != null && obj.messageOwner.action instanceof TLRPC.TL_messageEncryptedAction && obj.messageOwner.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL && getParentActivity() != null) { - TLRPC.TL_decryptedMessageActionSetMessageTTL action = (TLRPC.TL_decryptedMessageActionSetMessageTTL)obj.messageOwner.action.encryptedAction; + TLRPC.TL_decryptedMessageActionSetMessageTTL action = (TLRPC.TL_decryptedMessageActionSetMessageTTL) obj.messageOwner.action.encryptedAction; if (AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) < 17 && currentEncryptedChat.ttl > 0 && currentEncryptedChat.ttl <= 60) { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); @@ -3152,7 +3284,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not for (MessageObject obj : arr) { if (currentEncryptedChat != null && obj.messageOwner.action != null && obj.messageOwner.action instanceof TLRPC.TL_messageEncryptedAction && obj.messageOwner.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL && timerDrawable != null) { - TLRPC.TL_decryptedMessageActionSetMessageTTL action = (TLRPC.TL_decryptedMessageActionSetMessageTTL)obj.messageOwner.action.encryptedAction; + TLRPC.TL_decryptedMessageActionSetMessageTTL action = (TLRPC.TL_decryptedMessageActionSetMessageTTL) obj.messageOwner.action.encryptedAction; timerDrawable.setTime(action.ttl_seconds); } if (obj.isOut() && obj.isSending()) { @@ -3199,7 +3331,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not for (MessageObject obj : arr) { if (currentEncryptedChat != null && obj.messageOwner.action != null && obj.messageOwner.action instanceof TLRPC.TL_messageEncryptedAction && obj.messageOwner.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL && timerDrawable != null) { - TLRPC.TL_decryptedMessageActionSetMessageTTL action = (TLRPC.TL_decryptedMessageActionSetMessageTTL)obj.messageOwner.action.encryptedAction; + TLRPC.TL_decryptedMessageActionSetMessageTTL action = (TLRPC.TL_decryptedMessageActionSetMessageTTL) obj.messageOwner.action.encryptedAction; timerDrawable.setTime(action.ttl_seconds); } if (messagesDict.containsKey(obj.getId())) { @@ -3298,7 +3430,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } else if (id == NotificationCenter.closeChats) { if (args != null && args.length > 0) { - long did = (Long)args[0]; + long did = (Long) args[0]; if (did == dialog_id) { finishFragment(); } @@ -3345,7 +3477,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not updateVisibleRows(); } } else if (id == NotificationCenter.messagesDeleted) { - ArrayList markAsDeletedMessages = (ArrayList)args[0]; + ArrayList markAsDeletedMessages = (ArrayList) args[0]; boolean updated = false; for (Integer ids : markAsDeletedMessages) { MessageObject obj = messagesDict.get(ids); @@ -3388,11 +3520,12 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not chatAdapter.notifyDataSetChanged(); } } else if (id == NotificationCenter.messageReceivedByServer) { - Integer msgId = (Integer)args[0]; + Integer msgId = (Integer) args[0]; MessageObject obj = messagesDict.get(msgId); if (obj != null) { - Integer newMsgId = (Integer)args[1]; - TLRPC.Message newMsgObj = (TLRPC.Message)args[2]; + Integer newMsgId = (Integer) args[1]; + TLRPC.Message newMsgObj = (TLRPC.Message) args[2]; + boolean mediaUpdated = (Boolean) args[3]; if (newMsgObj != null) { obj.messageOwner.media = newMsgObj.media; obj.generateThumbs(true); @@ -3402,25 +3535,28 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not obj.messageOwner.id = newMsgId; obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; updateVisibleRows(); + if (mediaUpdated && chatListView.getLastVisiblePosition() >= messages.size() - 1) { + moveScrollToLastMessage(); + } } } else if (id == NotificationCenter.messageReceivedByAck) { - Integer msgId = (Integer)args[0]; + Integer msgId = (Integer) args[0]; MessageObject obj = messagesDict.get(msgId); if (obj != null) { obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; updateVisibleRows(); } } else if (id == NotificationCenter.messageSendError) { - Integer msgId = (Integer)args[0]; + Integer msgId = (Integer) args[0]; MessageObject obj = messagesDict.get(msgId); if (obj != null) { obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR; updateVisibleRows(); } } else if (id == NotificationCenter.chatInfoDidLoaded) { - int chatId = (Integer)args[0]; + int chatId = (Integer) args[0]; if (currentChat != null && chatId == currentChat.id) { - info = (TLRPC.ChatParticipants)args[1]; + info = (TLRPC.ChatParticipants) args[1]; if (mentionsAdapter != null) { mentionsAdapter.setChatInfo(info); } @@ -3434,16 +3570,16 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not updateContactStatus(); updateSubtitle(); } else if (id == NotificationCenter.encryptedChatUpdated) { - TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat)args[0]; + TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat) args[0]; if (currentEncryptedChat != null && chat.id == currentEncryptedChat.id) { currentEncryptedChat = chat; updateContactStatus(); updateSecretStatus(); } } else if (id == NotificationCenter.messagesReadedEncrypted) { - int encId = (Integer)args[0]; + int encId = (Integer) args[0]; if (currentEncryptedChat != null && currentEncryptedChat.id == encId) { - int date = (Integer)args[1]; + int date = (Integer) args[1]; boolean started = false; for (MessageObject obj : messages) { if (!obj.isOut()) { @@ -3458,13 +3594,13 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not updateVisibleRows(); } } else if (id == NotificationCenter.audioDidReset) { - Integer mid = (Integer)args[0]; + Integer mid = (Integer) args[0]; if (chatListView != null) { int count = chatListView.getChildCount(); for (int a = 0; a < count; a++) { View view = chatListView.getChildAt(a); if (view instanceof ChatAudioCell) { - ChatAudioCell cell = (ChatAudioCell)view; + ChatAudioCell cell = (ChatAudioCell) view; if (cell.getMessageObject() != null && cell.getMessageObject().getId() == mid) { cell.updateButtonState(); break; @@ -3473,13 +3609,13 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } } else if (id == NotificationCenter.audioProgressDidChanged) { - Integer mid = (Integer)args[0]; + Integer mid = (Integer) args[0]; if (chatListView != null) { int count = chatListView.getChildCount(); for (int a = 0; a < count; a++) { View view = chatListView.getChildAt(a); if (view instanceof ChatAudioCell) { - ChatAudioCell cell = (ChatAudioCell)view; + ChatAudioCell cell = (ChatAudioCell) view; if (cell.getMessageObject() != null && cell.getMessageObject().getId() == mid) { cell.updateProgress(); break; @@ -3488,7 +3624,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } } else if (id == NotificationCenter.removeAllMessagesFromDialog) { - long did = (Long)args[0]; + long did = (Long) args[0]; if (dialog_id == did) { messages.clear(); messagesByDays.clear(); @@ -3520,19 +3656,19 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } } else if (id == NotificationCenter.FileNewChunkAvailable) { - MessageObject messageObject = (MessageObject)args[0]; - long finalSize = (Long)args[2]; + MessageObject messageObject = (MessageObject) args[0]; + long finalSize = (Long) args[2]; if (finalSize != 0 && dialog_id == messageObject.getDialogId()) { MessageObject currentObject = messagesDict.get(messageObject.getId()); if (currentObject != null) { - currentObject.messageOwner.media.video.size = (int)finalSize; + currentObject.messageOwner.media.video.size = (int) finalSize; updateVisibleRows(); } } } else if (id == NotificationCenter.didCreatedNewDeleteTask) { - SparseArray> mids = (SparseArray>)args[0]; + SparseArray> mids = (SparseArray>) args[0]; boolean changed = false; - for(int i = 0; i < mids.size(); i++) { + for (int i = 0; i < mids.size(); i++) { int key = mids.keyAt(i); ArrayList arr = mids.get(key); for (Integer mid : arr) { @@ -3547,10 +3683,10 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not updateVisibleRows(); } } else if (id == NotificationCenter.audioDidStarted) { - MessageObject messageObject = (MessageObject)args[0]; + MessageObject messageObject = (MessageObject) args[0]; sendSecretMessageRead(messageObject); } else if (id == NotificationCenter.updateMessageMedia) { - MessageObject messageObject = (MessageObject)args[0]; + MessageObject messageObject = (MessageObject) args[0]; MessageObject existMessageObject = messagesDict.get(messageObject.getId()); if (existMessageObject != null) { existMessageObject.messageOwner.media = messageObject.messageOwner.media; @@ -3561,10 +3697,14 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } else if (id == NotificationCenter.replaceMessagesObjects) { if (dialog_id == (long) args[0]) { boolean changed = false; + boolean mediaUpdated = false; ArrayList messageObjects = (ArrayList) args[1]; for (MessageObject messageObject : messageObjects) { MessageObject old = messagesDict.get(messageObject.getId()); if (old != null) { + if (!mediaUpdated && messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage) { + mediaUpdated = true; + } messagesDict.put(old.getId(), messageObject); int idx = messages.indexOf(old); if (idx >= 0) { @@ -3575,6 +3715,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } if (changed) { chatAdapter.notifyDataSetChanged(); + if (mediaUpdated && chatListView.getLastVisiblePosition() >= messages.size() - 1) { + moveScrollToLastMessage(); + } } } } else if (id == NotificationCenter.notificationsSettingsUpdated) { @@ -3584,6 +3727,33 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (did == dialog_id) { updateVisibleRows(); } + } else if (id == NotificationCenter.didReceivedWebpages) { + ArrayList arrayList = (ArrayList) args[0]; + boolean updated = false; + for (TLRPC.Message message : arrayList) { + MessageObject currentMessage = messagesDict.get(message.id); + if (currentMessage != null) { + currentMessage.messageOwner.media.webpage = message.media.webpage; + currentMessage.generateThumbs(true); + updated = true; + } + } + if (updated) { + updateVisibleRows(); + if (chatListView.getLastVisiblePosition() >= messages.size() - 1) { + moveScrollToLastMessage(); + } + } + } else if (id == NotificationCenter.didReceivedWebpagesInUpdates) { + if (foundWebPage != null) { + HashMap hashMap = (HashMap) args[0]; + for (TLRPC.WebPage webPage : hashMap.values()) { + if (webPage.id == foundWebPage.id) { + showReplyPanel(!(webPage instanceof TLRPC.TL_webPageEmpty), null, null, webPage, false, true); + break; + } + } + } } } @@ -3594,7 +3764,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not for (int a = 0; a < count; a++) { View view = chatListView.getChildAt(a); if (view instanceof ChatMediaCell) { - ChatMediaCell cell = (ChatMediaCell)view; + ChatMediaCell cell = (ChatMediaCell) view; cell.setAllowedToSetPhoto(true); } } @@ -3666,6 +3836,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } checkActionBarMenu(); + if (replyImageLocation != null && replyImageView != null) { + replyImageView.setImage(replyImageLocation, "50_50", (Drawable) null); + } NotificationsController.getInstance().setOpennedDialogId(dialog_id); if (scrollToTopOnResume) { @@ -3712,7 +3885,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not TLRPC.Message message = (TLRPC.Message) TLClassStore.Instance().TLdeserialize(data, data.readInt32()); if (message != null) { replyingMessageObject = new MessageObject(message, MessagesController.getInstance().getUsers(), false); - showReplyForMessageObjectOrForward(true, replyingMessageObject, null, false); + showReplyPanel(true, replyingMessageObject, null, null, false, false); } } } catch (Exception e) { @@ -4062,11 +4235,11 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not fragment.setDelegate(this); presentFragment(fragment); } else if (option == 3) { - if(Build.VERSION.SDK_INT < 11) { - android.text.ClipboardManager clipboard = (android.text.ClipboardManager)ApplicationLoader.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE); + if (Build.VERSION.SDK_INT < 11) { + android.text.ClipboardManager clipboard = (android.text.ClipboardManager) ApplicationLoader.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(selectedObject.messageText); } else { - android.content.ClipboardManager clipboard = (android.content.ClipboardManager)ApplicationLoader.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE); + android.content.ClipboardManager clipboard = (android.content.ClipboardManager) ApplicationLoader.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText("label", selectedObject.messageText); clipboard.setPrimaryClip(clip); } @@ -4143,7 +4316,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } } else if (option == 8) { - showReplyForMessageObjectOrForward(true, selectedObject, null, true); + showReplyPanel(true, selectedObject, null, null, false, true); } selectedObject = null; } @@ -4234,7 +4407,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } if (did != dialog_id) { - int lower_part = (int)did; + int lower_part = (int) did; if (lower_part != 0) { Bundle args = new Bundle(); args.putBoolean("scrollToTopOnResume", scrollToTopOnResume); @@ -4245,7 +4418,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } ChatActivity chatActivity = new ChatActivity(args); if (presentFragment(chatActivity, true)) { - chatActivity.showReplyForMessageObjectOrForward(true, null, fmessages, false); + chatActivity.showReplyPanel(true, null, fmessages, null, false, false); if (!AndroidUtilities.isTablet()) { removeSelfFromStack(); Activity parentActivity = getParentActivity(); @@ -4265,7 +4438,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } else { activity.finishFragment(); moveScrollToLastMessage(); - showReplyForMessageObjectOrForward(true, null, fmessages, AndroidUtilities.isTablet()); + showReplyPanel(true, null, fmessages, null, false, AndroidUtilities.isTablet()); if (AndroidUtilities.isTablet()) { actionBar.hideActionMode(); } @@ -4292,7 +4465,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not try { ApplicationInfo info = ApplicationLoader.applicationContext.getPackageManager().getApplicationInfo("com.google.android.apps.maps", 0); return true; - } catch(PackageManager.NameNotFoundException e) { + } catch (PackageManager.NameNotFoundException e) { if (getParentActivity() == null) { return false; } @@ -4324,7 +4497,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not for (int a = 0; a < count; a++) { View view = chatListView.getChildAt(a); if (view instanceof ChatBaseCell) { - ChatBaseCell cell = (ChatBaseCell)view; + ChatBaseCell cell = (ChatBaseCell) view; boolean disableSelection = false; boolean selected = false; @@ -4379,14 +4552,14 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ImageReceiver imageReceiver = null; View view = chatListView.getChildAt(a); if (view instanceof ChatMediaCell) { - ChatMediaCell cell = (ChatMediaCell)view; + ChatMediaCell cell = (ChatMediaCell) view; MessageObject message = cell.getMessageObject(); if (message != null && message.getId() == messageObject.getId()) { messageToOpen = message; imageReceiver = cell.getPhotoImage(); } } else if (view instanceof ChatActionCell) { - ChatActionCell cell = (ChatActionCell)view; + ChatActionCell cell = (ChatActionCell) view; MessageObject message = cell.getMessageObject(); if (message != null && message.getId() == messageObject.getId()) { messageToOpen = message; @@ -4416,25 +4589,34 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } @Override - public void willSwitchFromPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) { } + public void willSwitchFromPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) { + } @Override - public void willHidePhotoViewer() { } + public void willHidePhotoViewer() { + } @Override - public boolean isPhotoChecked(int index) { return false; } + public boolean isPhotoChecked(int index) { + return false; + } @Override - public void setPhotoChecked(int index) { } + public void setPhotoChecked(int index) { + } @Override - public void cancelButtonPressed() { } + public void cancelButtonPressed() { + } @Override - public void sendButtonPressed(int index) { } + public void sendButtonPressed(int index) { + } @Override - public int getSelectedCount() { return 0; } + public int getSelectedCount() { + return 0; + } private class ChatAdapter extends BaseFragmentAdapter { @@ -4493,7 +4675,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (i == 0 && !endReached || !forward_end_reached && i == (messages.size() + 1 - offset)) { View progressBar = null; if (view == null) { - LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = li.inflate(R.layout.chat_loading_layout, viewGroup, false); progressBar = view.findViewById(R.id.progressLayout); if (ApplicationLoader.isCustomTheme()) { @@ -4514,21 +4696,22 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (view == null) { if (type == 0) { view = new ChatMessageCell(mContext); - } if (type == 1) { + } + if (type == 1) { view = new ChatMediaCell(mContext); } else if (type == 2) { view = new ChatAudioCell(mContext); } else if (type == 3) { view = new ChatContactCell(mContext); } else if (type == 6) { - LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = li.inflate(R.layout.chat_unread_layout, viewGroup, false); } else if (type == 4) { view = new ChatActionCell(mContext); } if (view instanceof ChatBaseCell) { - ((ChatBaseCell)view).setDelegate(new ChatBaseCell.ChatBaseCellDelegate() { + ((ChatBaseCell) view).setDelegate(new ChatBaseCell.ChatBaseCellDelegate() { @Override public void didPressedUserAvatar(ChatBaseCell cell, TLRPC.User user) { if (actionBar.isActionModeShowed()) { @@ -4671,7 +4854,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } }); } else if (view instanceof ChatContactCell) { - ((ChatContactCell)view).setContactDelegate(new ChatContactCell.ChatContactCellDelegate() { + ((ChatContactCell) view).setContactDelegate(new ChatContactCell.ChatContactCellDelegate() { @Override public void didClickAddButton(ChatContactCell cell, TLRPC.User user) { if (actionBar.isActionModeShowed()) { @@ -4726,7 +4909,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not }); } } else if (view instanceof ChatActionCell) { - ((ChatActionCell)view).setDelegate(new ChatActionCell.ChatActionCellDelegate() { + ((ChatActionCell) view).setDelegate(new ChatActionCell.ChatActionCellDelegate() { @Override public void didClickedImage(ChatActionCell cell) { MessageObject message = cell.getMessageObject(); @@ -4766,20 +4949,20 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } if (view instanceof ChatBaseCell) { - ChatBaseCell baseCell = (ChatBaseCell)view; + ChatBaseCell baseCell = (ChatBaseCell) view; baseCell.isChat = currentChat != null; baseCell.setMessageObject(message); baseCell.setCheckPressed(!disableSelection, disableSelection && selected); if (view instanceof ChatAudioCell && MediaController.getInstance().canDownloadMedia(MediaController.AUTODOWNLOAD_MASK_AUDIO)) { - ((ChatAudioCell)view).downloadAudioIfNeed(); + ((ChatAudioCell) view).downloadAudioIfNeed(); } baseCell.setHighlighted(highlightMessageId != Integer.MAX_VALUE && message.getId() == highlightMessageId); } else if (view instanceof ChatActionCell) { - ChatActionCell actionCell = (ChatActionCell)view; + ChatActionCell actionCell = (ChatActionCell) view; actionCell.setMessageObject(message); } if (type == 6) { - TextView messageTextView = (TextView)view.findViewById(R.id.chat_message_text); + TextView messageTextView = (TextView) view.findViewById(R.id.chat_message_text); messageTextView.setText(LocaleController.formatPluralString("NewMessages", unread_to_load)); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/AvatarUpdater.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/AvatarUpdater.java index a7472c6fa..1fa82ddd5 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/AvatarUpdater.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/AvatarUpdater.java @@ -35,6 +35,7 @@ import java.io.File; import java.util.ArrayList; public class AvatarUpdater implements NotificationCenter.NotificationCenterDelegate, PhotoCropActivity.PhotoEditActivityDelegate { + public String currentPicturePath; private TLRPC.PhotoSize smallPhoto; private TLRPC.PhotoSize bigPhoto; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/BackupImageView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/BackupImageView.java index ad0478dec..e625402ef 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/BackupImageView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/BackupImageView.java @@ -20,10 +20,9 @@ import org.telegram.android.ImageReceiver; import org.telegram.messenger.TLObject; import org.telegram.messenger.TLRPC; - public class BackupImageView extends View { - public ImageReceiver imageReceiver; - public boolean processDetach = true; + + private ImageReceiver imageReceiver; public BackupImageView(Context context) { super(context); @@ -91,12 +90,22 @@ public class BackupImageView extends View { imageReceiver.setImageBitmap(drawable); } + public void setRoundRadius(int value) { + imageReceiver.setRoundRadius(value); + } + + public void setAspectFit(boolean value) { + imageReceiver.setAspectFit(value); + } + + public ImageReceiver getImageReceiver() { + return imageReceiver; + } + @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); - if (processDetach) { - imageReceiver.clearImage(); - } + imageReceiver.clearImage(); } @Override diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatActivityEnterView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatActivityEnterView.java index f4e5a15f1..de1b773b6 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatActivityEnterView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatActivityEnterView.java @@ -61,7 +61,7 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat public interface ChatActivityEnterViewDelegate { void onMessageSend(String message); void needSendTyping(); - void onTextChanged(CharSequence text); + void onTextChanged(CharSequence text, boolean bigChange); void onAttachButtonHidden(); void onAttachButtonShow(); void onWindowSizeChanged(int size); @@ -104,11 +104,15 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat private long dialog_id; private boolean ignoreTextChange; private MessageObject replyingMessageObject; + private TLRPC.WebPage messageWebPage; + private boolean messageWebPageSearch; private ChatActivityEnterViewDelegate delegate; private float topViewAnimation; + private boolean topViewShowed; private boolean needShowTopView; private boolean allowShowTopView; + private AnimatorSetProxy currentTopViewAnimation; public ChatActivityEnterView(Activity context, SizeNotifierRelativeLayout parent, BaseFragment fragment, boolean isChat) { super(context); @@ -234,12 +238,15 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat } @Override - public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { + public void onTextChanged(CharSequence charSequence, int start, int before, int count) { String message = getTrimmedString(charSequence.toString()); checkSendButton(true); if (delegate != null) { - delegate.onTextChanged(charSequence); + if (before > count || count > 1) { + messageWebPageSearch = true; + } + delegate.onTextChanged(charSequence, before > count || count > 1); } if (message.length() != 0 && lastTypingTimeSend < System.currentTimeMillis() - 5000 && !ignoreTextChange) { @@ -499,6 +506,7 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat } public void setTopViewAnimation(float progress) { + topViewAnimation = progress; LayoutParams layoutParams2 = (LayoutParams) textFieldContainer.getLayoutParams(); layoutParams2.topMargin = AndroidUtilities.dp(2) + (int) (topView.getLayoutParams().height * progress); textFieldContainer.setLayoutParams(layoutParams2); @@ -514,75 +522,85 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat } public void showTopView(boolean animated) { - if (topView == null) { + if (topView == null || topViewShowed) { return; } needShowTopView = true; + topViewShowed = true; if (allowShowTopView) { topView.setVisibility(VISIBLE); + float resumeValue = 0.0f; + if (currentTopViewAnimation != null) { + resumeValue = topViewAnimation; + currentTopViewAnimation.cancel(); + currentTopViewAnimation = null; + } if (animated) { if (keyboardVisible || emojiPopup != null && emojiPopup.isShowing()) { - AnimatorSetProxy animatorSetProxy = new AnimatorSetProxy(); - animatorSetProxy.playTogether( - ObjectAnimatorProxy.ofFloat(ChatActivityEnterView.this, "topViewAnimation", 0.0f, 1.0f) + currentTopViewAnimation = new AnimatorSetProxy(); + currentTopViewAnimation.playTogether( + ObjectAnimatorProxy.ofFloat(ChatActivityEnterView.this, "topViewAnimation", 1.0f) ); - animatorSetProxy.addListener(new AnimatorListenerAdapterProxy() { + currentTopViewAnimation.addListener(new AnimatorListenerAdapterProxy() { @Override public void onAnimationEnd(Object animation) { - LayoutParams layoutParams2 = (LayoutParams) textFieldContainer.getLayoutParams(); - layoutParams2.topMargin = AndroidUtilities.dp(2) + topView.getLayoutParams().height; - textFieldContainer.setLayoutParams(layoutParams2); - if (!forceShowSendButton) { - openKeyboard(); + if (animation == currentTopViewAnimation) { + setTopViewAnimation(1.0f); + if (!forceShowSendButton) { + openKeyboard(); + } + currentTopViewAnimation = null; } } }); - animatorSetProxy.setDuration(200); - animatorSetProxy.start(); + currentTopViewAnimation.setDuration(200); + currentTopViewAnimation.start(); } else { - LayoutParams layoutParams2 = (LayoutParams) textFieldContainer.getLayoutParams(); - layoutParams2.topMargin = AndroidUtilities.dp(2) + topView.getLayoutParams().height; - textFieldContainer.setLayoutParams(layoutParams2); + setTopViewAnimation(1.0f); if (!forceShowSendButton) { openKeyboard(); } } } else { - LayoutParams layoutParams2 = (LayoutParams) textFieldContainer.getLayoutParams(); - layoutParams2.topMargin = AndroidUtilities.dp(2) + topView.getLayoutParams().height; - textFieldContainer.setLayoutParams(layoutParams2); + setTopViewAnimation(1.0f); } } } - public void hideTopView(boolean animated) { - if (topView == null) { + public void hideTopView(final boolean animated) { + if (topView == null || !topViewShowed) { return; } + topViewShowed = false; needShowTopView = false; if (allowShowTopView) { + float resumeValue = 1.0f; + if (currentTopViewAnimation != null) { + resumeValue = topViewAnimation; + currentTopViewAnimation.cancel(); + currentTopViewAnimation = null; + } if (animated) { - AnimatorSetProxy animatorSetProxy = new AnimatorSetProxy(); - animatorSetProxy.playTogether( - ObjectAnimatorProxy.ofFloat(ChatActivityEnterView.this, "topViewAnimation", 1.0f, 0.0f) + currentTopViewAnimation = new AnimatorSetProxy(); + currentTopViewAnimation.playTogether( + ObjectAnimatorProxy.ofFloat(ChatActivityEnterView.this, "topViewAnimation", resumeValue, 0.0f) ); - animatorSetProxy.addListener(new AnimatorListenerAdapterProxy() { + currentTopViewAnimation.addListener(new AnimatorListenerAdapterProxy() { @Override public void onAnimationEnd(Object animation) { - topView.setVisibility(GONE); - LayoutParams layoutParams2 = (LayoutParams) textFieldContainer.getLayoutParams(); - layoutParams2.topMargin = AndroidUtilities.dp(2); - textFieldContainer.setLayoutParams(layoutParams2); + if (animation == currentTopViewAnimation) { + topView.setVisibility(GONE); + setTopViewAnimation(0.0f); + currentTopViewAnimation = null; + } } }); - animatorSetProxy.setDuration(200); - animatorSetProxy.start(); + currentTopViewAnimation.setDuration(200); + currentTopViewAnimation.start(); } else { topView.setVisibility(GONE); - LayoutParams layoutParams2 = (LayoutParams) textFieldContainer.getLayoutParams(); - layoutParams2.topMargin = AndroidUtilities.dp(2); - textFieldContainer.setLayoutParams(layoutParams2); + setTopViewAnimation(0.0f); } } } @@ -601,9 +619,7 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat allowShowTopView = false; if (needShowTopView) { topView.setVisibility(View.GONE); - LayoutParams layoutParams2 = (LayoutParams) textFieldContainer.getLayoutParams(); - layoutParams2.topMargin = AndroidUtilities.dp(2); - textFieldContainer.setLayoutParams(layoutParams2); + setTopViewAnimation(0.0f); } } } else { @@ -611,9 +627,7 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat allowShowTopView = true; if (needShowTopView) { topView.setVisibility(View.VISIBLE); - LayoutParams layoutParams2 = (LayoutParams) textFieldContainer.getLayoutParams(); - layoutParams2.topMargin = AndroidUtilities.dp(2) + topView.getLayoutParams().height; - textFieldContainer.setLayoutParams(layoutParams2); + setTopViewAnimation(1.0f); } } } @@ -651,6 +665,11 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat replyingMessageObject = messageObject; } + public void setWebPage(TLRPC.WebPage webPage, boolean searchWebPages) { + messageWebPage = webPage; + messageWebPageSearch = searchWebPages; + } + private void sendMessage() { if (parentFragment != null) { String action = null; @@ -689,7 +708,7 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat int count = (int) Math.ceil(text.length() / 4096.0f); for (int a = 0; a < count; a++) { String mess = text.substring(a * 4096, Math.min((a + 1) * 4096, text.length())); - SendMessagesHelper.getInstance().sendMessage(mess, dialog_id, replyingMessageObject); + SendMessagesHelper.getInstance().sendMessage(mess, dialog_id, replyingMessageObject, messageWebPage, messageWebPageSearch); } return true; } @@ -1107,7 +1126,7 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat messageEditText.setSelection(messageEditText.getText().length()); ignoreTextChange = false; if (delegate != null) { - delegate.onTextChanged(messageEditText.getText()); + delegate.onTextChanged(messageEditText.getText(), true); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ClippingImageView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ClippingImageView.java index 6d6709781..3c17e47ee 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ClippingImageView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ClippingImageView.java @@ -22,6 +22,7 @@ import org.telegram.messenger.FileLog; import org.telegram.ui.AnimationCompat.ViewProxy; public class ClippingImageView extends View { + private int clipBottom; private int clipLeft; private int clipRight; @@ -79,7 +80,7 @@ public class ClippingImageView extends View { } public void onDraw(Canvas canvas) { - if (getVisibility() == GONE || getVisibility() == INVISIBLE) { + if (getVisibility() != VISIBLE) { return; } if (bmp != null) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/EmojiView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/EmojiView.java index 28bdc149a..2f2706d4d 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/EmojiView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/EmojiView.java @@ -31,7 +31,8 @@ import org.telegram.messenger.R; import java.util.ArrayList; public class EmojiView extends LinearLayout { - private ArrayList adapters = new ArrayList(); + + private ArrayList adapters = new ArrayList<>(); private int[] icons = { R.drawable.ic_emoji_recent, R.drawable.ic_emoji_smile, @@ -42,7 +43,7 @@ public class EmojiView extends LinearLayout { private Listener listener; private ViewPager pager; private FrameLayout recentsWrap; - private ArrayList views = new ArrayList(); + private ArrayList views = new ArrayList<>(); public EmojiView(Context paramContext) { super(paramContext); @@ -63,7 +64,7 @@ public class EmojiView extends LinearLayout { if (this.pager.getCurrentItem() == 0) { return; } - ArrayList localArrayList = new ArrayList(); + ArrayList localArrayList = new ArrayList<>(); long[] currentRecent = Emoji.data[0]; boolean was = false; for (long aCurrentRecent : currentRecent) { @@ -161,7 +162,7 @@ public class EmojiView extends LinearLayout { } private void saveRecents() { - ArrayList localArrayList = new ArrayList(); + ArrayList localArrayList = new ArrayList<>(); long[] arrayOfLong = Emoji.data[0]; int i = arrayOfLong.length; for (int j = 0; ; j++) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/FrameLayoutFixed.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/FrameLayoutFixed.java index 1d30c5682..542623e9d 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/FrameLayoutFixed.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/FrameLayoutFixed.java @@ -19,7 +19,8 @@ import org.telegram.messenger.FileLog; import java.util.ArrayList; public class FrameLayoutFixed extends FrameLayout { - private final ArrayList mMatchParentChildren = new ArrayList(1); + + private final ArrayList mMatchParentChildren = new ArrayList<>(1); public FrameLayoutFixed(Context context) { super(context); @@ -110,7 +111,7 @@ public class FrameLayoutFixed extends FrameLayout { } setMeasuredDimension(resolveSizeAndStateFixed(maxWidth, widthMeasureSpec, childState), - resolveSizeAndStateFixed(maxHeight, heightMeasureSpec, childState << MEASURED_HEIGHT_STATE_SHIFT)); + resolveSizeAndStateFixed(maxHeight, heightMeasureSpec, childState << 16)); count = mMatchParentChildren.size(); if (count > 1) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ProgressView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ProgressView.java index adaa786e2..b6f2561b6 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ProgressView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ProgressView.java @@ -14,6 +14,7 @@ import android.graphics.Paint; import org.telegram.android.AndroidUtilities; public class ProgressView { + private Paint innerPaint; private Paint outerPaint; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/SizeNotifierRelativeLayout.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/SizeNotifierRelativeLayout.java index d0d4187e2..54ec83b9a 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/SizeNotifierRelativeLayout.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/SizeNotifierRelativeLayout.java @@ -33,14 +33,17 @@ public class SizeNotifierRelativeLayout extends RelativeLayout { public SizeNotifierRelativeLayout(Context context) { super(context); + setWillNotDraw(false); } public SizeNotifierRelativeLayout(android.content.Context context, android.util.AttributeSet attrs) { super(context, attrs); + setWillNotDraw(false); } public SizeNotifierRelativeLayout(android.content.Context context, android.util.AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); + setWillNotDraw(false); } public void setBackgroundImage(int resourceId) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/SlideView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/SlideView.java index 6464ce5f9..a1ae84c65 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/SlideView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/SlideView.java @@ -49,4 +49,8 @@ public class SlideView extends LinearLayout { public void restoreStateParams(Bundle bundle) { } + + public boolean needBackButton() { + return false; + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/StaticLayoutEx.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/StaticLayoutEx.java new file mode 100644 index 000000000..4700a15e6 --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/StaticLayoutEx.java @@ -0,0 +1,119 @@ +/* + * This is the source code of Telegram for Android v. 2.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-2015. + */ + +package org.telegram.ui.Components; + +import android.os.Build; +import android.text.Layout; +import android.text.StaticLayout; +import android.text.TextDirectionHeuristic; +import android.text.TextDirectionHeuristics; +import android.text.TextPaint; +import android.text.TextUtils; + +import org.telegram.messenger.FileLog; + +import java.lang.reflect.Constructor; + +public class StaticLayoutEx { + + private static final String TEXT_DIR_CLASS = "android.text.TextDirectionHeuristic"; + private static final String TEXT_DIRS_CLASS = "android.text.TextDirectionHeuristics"; + private static final String TEXT_DIR_FIRSTSTRONG_LTR = "FIRSTSTRONG_LTR"; + private static boolean initialized; + + private static Constructor sConstructor; + private static Object[] sConstructorArgs; + private static Object sTextDirection; + + public static void init() { + if (initialized) { + return; + } + + try { + final Class textDirClass; + if (Build.VERSION.SDK_INT >= 18) { + textDirClass = TextDirectionHeuristic.class; + sTextDirection = TextDirectionHeuristics.FIRSTSTRONG_LTR; + } else { + ClassLoader loader = StaticLayoutEx.class.getClassLoader(); + textDirClass = loader.loadClass(TEXT_DIR_CLASS); + Class textDirsClass = loader.loadClass(TEXT_DIRS_CLASS); + sTextDirection = textDirsClass.getField(TEXT_DIR_FIRSTSTRONG_LTR).get(textDirsClass); + } + + final Class[] signature = new Class[]{ + CharSequence.class, + int.class, + int.class, + TextPaint.class, + int.class, + Layout.Alignment.class, + textDirClass, + float.class, + float.class, + boolean.class, + TextUtils.TruncateAt.class, + int.class, + int.class + }; + + sConstructor = StaticLayout.class.getDeclaredConstructor(signature); + sConstructor.setAccessible(true); + sConstructorArgs = new Object[signature.length]; + initialized = true; + } catch (Throwable e) { + FileLog.e("tmessages", e); + } + } + + public static StaticLayout createStaticLayout(CharSequence source, TextPaint paint, int width, Layout.Alignment align, float spacingmult, float spacingadd, boolean includepad, TextUtils.TruncateAt ellipsize, int ellipsisWidth, int maxLines) { + return createStaticLayout(source, 0, source.length(), paint, width, align, spacingmult, spacingadd, includepad, ellipsize, ellipsisWidth, maxLines); + } + + public static StaticLayout createStaticLayout(CharSequence source, int bufstart, int bufend, TextPaint paint, int outerWidth, Layout.Alignment align, float spacingMult, float spacingAdd, boolean includePad, TextUtils.TruncateAt ellipsize, int ellipsisWidth, int maxLines) { + if (Build.VERSION.SDK_INT >= 14) { + init(); + try { + sConstructorArgs[0] = source; + sConstructorArgs[1] = bufstart; + sConstructorArgs[2] = bufend; + sConstructorArgs[3] = paint; + sConstructorArgs[4] = outerWidth; + sConstructorArgs[5] = align; + sConstructorArgs[6] = sTextDirection; + sConstructorArgs[7] = spacingMult; + sConstructorArgs[8] = spacingAdd; + sConstructorArgs[9] = includePad; + sConstructorArgs[10] = ellipsize; + sConstructorArgs[11] = ellipsisWidth; + sConstructorArgs[12] = maxLines; + return sConstructor.newInstance(sConstructorArgs); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + try { + if (maxLines == 1) { + return new StaticLayout(source, bufstart, bufend, paint, outerWidth, align, spacingMult, spacingAdd, includePad, ellipsize, ellipsisWidth); + } else { + StaticLayout layout = new StaticLayout(source, paint, outerWidth, align, spacingMult, spacingAdd, includePad); + if (layout.getLineCount() <= maxLines) { + return layout; + } else { + int off = layout.getOffsetForHorizontal(maxLines - 1, layout.getLineWidth(maxLines - 1)); + return new StaticLayout(source.subSequence(0, off), paint, outerWidth, align, spacingMult, spacingAdd, includePad); + } + } + } catch (Exception e) { + FileLog.e("tmessages", e); + } + return null; + } +} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/VideoTimelineView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/VideoTimelineView.java index 74da7e49f..d562cc6bb 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/VideoTimelineView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/VideoTimelineView.java @@ -29,6 +29,7 @@ import java.util.ArrayList; @TargetApi(10) public class VideoTimelineView extends View { + private long videoLength = 0; private float progressLeft = 0; private float progressRight = 1; @@ -39,7 +40,7 @@ public class VideoTimelineView extends View { private float pressDx = 0; private MediaMetadataRetriever mediaMetadataRetriever = null; private VideoTimelineViewDelegate delegate = null; - private ArrayList frames = new ArrayList(); + private ArrayList frames = new ArrayList<>(); private AsyncTask currentTask = null; private static final Object sync = new Object(); private long frameTimeOffset = 0; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ContactAddActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ContactAddActivity.java index 288690a30..cf56dd75b 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ContactAddActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ContactAddActivity.java @@ -9,6 +9,7 @@ package org.telegram.ui; import android.app.Activity; +import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.text.InputType; @@ -19,7 +20,6 @@ import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; -import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.FrameLayout; @@ -74,198 +74,186 @@ public class ContactAddActivity extends BaseFragment implements NotificationCent @Override public void onFragmentDestroy() { super.onFragmentDestroy(); - if (avatarImage != null) { - avatarImage.setImageDrawable(null); - } NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces); } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - if (addContact) { - actionBar.setTitle(LocaleController.getString("AddContactTitle", R.string.AddContactTitle)); - } else { - actionBar.setTitle(LocaleController.getString("EditName", R.string.EditName)); - } - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setAllowOverlayTitle(true); + if (addContact) { + actionBar.setTitle(LocaleController.getString("AddContactTitle", R.string.AddContactTitle)); + } else { + actionBar.setTitle(LocaleController.getString("EditName", R.string.EditName)); + } + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); + } else if (id == done_button) { + if (firstNameField.getText().length() != 0) { + TLRPC.User user = MessagesController.getInstance().getUser(user_id); + user.first_name = firstNameField.getText().toString(); + user.last_name = lastNameField.getText().toString(); + ContactsController.getInstance().addContact(user); finishFragment(); - } else if (id == done_button) { - if (firstNameField.getText().length() != 0) { - TLRPC.User user = MessagesController.getInstance().getUser(user_id); - user.first_name = firstNameField.getText().toString(); - user.last_name = lastNameField.getText().toString(); - ContactsController.getInstance().addContact(user); - finishFragment(); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_NAME); - } + NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_NAME); } } - }); + } + }); - ActionBarMenu menu = actionBar.createMenu(); - doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); + ActionBarMenu menu = actionBar.createMenu(); + doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); - fragmentView = new ScrollView(getParentActivity()); + fragmentView = new ScrollView(context); - LinearLayout linearLayout = new LinearLayout(getParentActivity()); - linearLayout.setOrientation(LinearLayout.VERTICAL); - ((ScrollView) fragmentView).addView(linearLayout); - ScrollView.LayoutParams layoutParams2 = (ScrollView.LayoutParams) linearLayout.getLayoutParams(); - layoutParams2.width = ScrollView.LayoutParams.MATCH_PARENT; - layoutParams2.height = ScrollView.LayoutParams.WRAP_CONTENT; - linearLayout.setLayoutParams(layoutParams2); - linearLayout.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { + LinearLayout linearLayout = new LinearLayout(context); + linearLayout.setOrientation(LinearLayout.VERTICAL); + ((ScrollView) fragmentView).addView(linearLayout); + ScrollView.LayoutParams layoutParams2 = (ScrollView.LayoutParams) linearLayout.getLayoutParams(); + layoutParams2.width = ScrollView.LayoutParams.MATCH_PARENT; + layoutParams2.height = ScrollView.LayoutParams.WRAP_CONTENT; + linearLayout.setLayoutParams(layoutParams2); + linearLayout.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + + FrameLayout frameLayout = new FrameLayout(context); + linearLayout.addView(frameLayout); + LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) frameLayout.getLayoutParams(); + layoutParams.topMargin = AndroidUtilities.dp(24); + layoutParams.leftMargin = AndroidUtilities.dp(24); + layoutParams.rightMargin = AndroidUtilities.dp(24); + layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT; + frameLayout.setLayoutParams(layoutParams); + + avatarImage = new BackupImageView(context); + avatarImage.setRoundRadius(AndroidUtilities.dp(30)); + frameLayout.addView(avatarImage); + FrameLayout.LayoutParams layoutParams3 = (FrameLayout.LayoutParams) avatarImage.getLayoutParams(); + layoutParams3.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP; + layoutParams3.width = AndroidUtilities.dp(60); + layoutParams3.height = AndroidUtilities.dp(60); + avatarImage.setLayoutParams(layoutParams3); + + nameTextView = new TextView(context); + nameTextView.setTextColor(0xff212121); + nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); + nameTextView.setLines(1); + nameTextView.setMaxLines(1); + nameTextView.setSingleLine(true); + nameTextView.setEllipsize(TextUtils.TruncateAt.END); + nameTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); + nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); + frameLayout.addView(nameTextView); + layoutParams3 = (FrameLayout.LayoutParams) nameTextView.getLayoutParams(); + layoutParams3.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams3.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams3.leftMargin = AndroidUtilities.dp(LocaleController.isRTL ? 0 : 80); + layoutParams3.rightMargin = AndroidUtilities.dp(LocaleController.isRTL ? 80 : 0); + layoutParams3.topMargin = AndroidUtilities.dp(3); + layoutParams3.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP; + nameTextView.setLayoutParams(layoutParams3); + + onlineTextView = new TextView(context); + onlineTextView.setTextColor(0xff999999); + onlineTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + onlineTextView.setLines(1); + onlineTextView.setMaxLines(1); + onlineTextView.setSingleLine(true); + onlineTextView.setEllipsize(TextUtils.TruncateAt.END); + onlineTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); + frameLayout.addView(onlineTextView); + layoutParams3 = (FrameLayout.LayoutParams) onlineTextView.getLayoutParams(); + layoutParams3.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams3.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams3.leftMargin = AndroidUtilities.dp(LocaleController.isRTL ? 0 : 80); + layoutParams3.rightMargin = AndroidUtilities.dp(LocaleController.isRTL ? 80 : 0); + layoutParams3.topMargin = AndroidUtilities.dp(32); + layoutParams3.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP; + onlineTextView.setLayoutParams(layoutParams3); + + firstNameField = new EditText(context); + firstNameField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); + firstNameField.setHintTextColor(0xff979797); + firstNameField.setTextColor(0xff212121); + firstNameField.setMaxLines(1); + firstNameField.setLines(1); + firstNameField.setSingleLine(true); + firstNameField.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); + firstNameField.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); + firstNameField.setImeOptions(EditorInfo.IME_ACTION_NEXT); + firstNameField.setHint(LocaleController.getString("FirstName", R.string.FirstName)); + AndroidUtilities.clearCursorDrawable(firstNameField); + linearLayout.addView(firstNameField); + layoutParams = (LinearLayout.LayoutParams) firstNameField.getLayoutParams(); + layoutParams.topMargin = AndroidUtilities.dp(24); + layoutParams.height = AndroidUtilities.dp(36); + layoutParams.leftMargin = AndroidUtilities.dp(24); + layoutParams.rightMargin = AndroidUtilities.dp(24); + layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; + firstNameField.setLayoutParams(layoutParams); + firstNameField.setOnEditorActionListener(new TextView.OnEditorActionListener() { + @Override + public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { + if (i == EditorInfo.IME_ACTION_NEXT) { + lastNameField.requestFocus(); + lastNameField.setSelection(lastNameField.length()); return true; } - }); - - FrameLayout frameLayout = new FrameLayout(getParentActivity()); - linearLayout.addView(frameLayout); - LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) frameLayout.getLayoutParams(); - layoutParams.topMargin = AndroidUtilities.dp(24); - layoutParams.leftMargin = AndroidUtilities.dp(24); - layoutParams.rightMargin = AndroidUtilities.dp(24); - layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT; - frameLayout.setLayoutParams(layoutParams); - - avatarImage = new BackupImageView(getParentActivity()); - avatarImage.imageReceiver.setRoundRadius(AndroidUtilities.dp(30)); - avatarImage.processDetach = false; - frameLayout.addView(avatarImage); - FrameLayout.LayoutParams layoutParams3 = (FrameLayout.LayoutParams) avatarImage.getLayoutParams(); - layoutParams3.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP; - layoutParams3.width = AndroidUtilities.dp(60); - layoutParams3.height = AndroidUtilities.dp(60); - avatarImage.setLayoutParams(layoutParams3); - - nameTextView = new TextView(getParentActivity()); - nameTextView.setTextColor(0xff212121); - nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); - nameTextView.setLines(1); - nameTextView.setMaxLines(1); - nameTextView.setSingleLine(true); - nameTextView.setEllipsize(TextUtils.TruncateAt.END); - nameTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); - nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - frameLayout.addView(nameTextView); - layoutParams3 = (FrameLayout.LayoutParams) nameTextView.getLayoutParams(); - layoutParams3.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams3.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams3.leftMargin = AndroidUtilities.dp(LocaleController.isRTL ? 0 : 80); - layoutParams3.rightMargin = AndroidUtilities.dp(LocaleController.isRTL ? 80 : 0); - layoutParams3.topMargin = AndroidUtilities.dp(3); - layoutParams3.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP; - nameTextView.setLayoutParams(layoutParams3); - - onlineTextView = new TextView(getParentActivity()); - onlineTextView.setTextColor(0xff999999); - onlineTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - onlineTextView.setLines(1); - onlineTextView.setMaxLines(1); - onlineTextView.setSingleLine(true); - onlineTextView.setEllipsize(TextUtils.TruncateAt.END); - onlineTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); - frameLayout.addView(onlineTextView); - layoutParams3 = (FrameLayout.LayoutParams) onlineTextView.getLayoutParams(); - layoutParams3.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams3.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams3.leftMargin = AndroidUtilities.dp(LocaleController.isRTL ? 0 : 80); - layoutParams3.rightMargin = AndroidUtilities.dp(LocaleController.isRTL ? 80 : 0); - layoutParams3.topMargin = AndroidUtilities.dp(32); - layoutParams3.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP; - onlineTextView.setLayoutParams(layoutParams3); - - firstNameField = new EditText(getParentActivity()); - firstNameField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - firstNameField.setHintTextColor(0xff979797); - firstNameField.setTextColor(0xff212121); - firstNameField.setMaxLines(1); - firstNameField.setLines(1); - firstNameField.setSingleLine(true); - firstNameField.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); - firstNameField.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); - firstNameField.setImeOptions(EditorInfo.IME_ACTION_NEXT); - firstNameField.setHint(LocaleController.getString("FirstName", R.string.FirstName)); - AndroidUtilities.clearCursorDrawable(firstNameField); - linearLayout.addView(firstNameField); - layoutParams = (LinearLayout.LayoutParams) firstNameField.getLayoutParams(); - layoutParams.topMargin = AndroidUtilities.dp(24); - layoutParams.height = AndroidUtilities.dp(36); - layoutParams.leftMargin = AndroidUtilities.dp(24); - layoutParams.rightMargin = AndroidUtilities.dp(24); - layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; - firstNameField.setLayoutParams(layoutParams); - firstNameField.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { - if (i == EditorInfo.IME_ACTION_NEXT) { - lastNameField.requestFocus(); - lastNameField.setSelection(lastNameField.length()); - return true; - } - return false; - } - }); - - lastNameField = new EditText(getParentActivity()); - lastNameField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - lastNameField.setHintTextColor(0xff979797); - lastNameField.setTextColor(0xff212121); - lastNameField.setMaxLines(1); - lastNameField.setLines(1); - lastNameField.setSingleLine(true); - lastNameField.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); - lastNameField.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); - lastNameField.setImeOptions(EditorInfo.IME_ACTION_DONE); - lastNameField.setHint(LocaleController.getString("LastName", R.string.LastName)); - AndroidUtilities.clearCursorDrawable(lastNameField); - linearLayout.addView(lastNameField); - layoutParams = (LinearLayout.LayoutParams) lastNameField.getLayoutParams(); - layoutParams.topMargin = AndroidUtilities.dp(16); - layoutParams.height = AndroidUtilities.dp(36); - layoutParams.leftMargin = AndroidUtilities.dp(24); - layoutParams.rightMargin = AndroidUtilities.dp(24); - layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; - lastNameField.setLayoutParams(layoutParams); - lastNameField.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { - if (i == EditorInfo.IME_ACTION_DONE) { - doneButton.performClick(); - return true; - } - return false; - } - }); - - TLRPC.User user = MessagesController.getInstance().getUser(user_id); - if (user != null) { - if (user.phone == null) { - if (phone != null) { - user.phone = PhoneFormat.stripExceptNumbers(phone); - } - } - firstNameField.setText(user.first_name); - firstNameField.setSelection(firstNameField.length()); - lastNameField.setText(user.last_name); + return false; } + }); - updateAvatarLayout(); - } else { - ViewGroup parent = (ViewGroup) fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); + lastNameField = new EditText(context); + lastNameField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); + lastNameField.setHintTextColor(0xff979797); + lastNameField.setTextColor(0xff212121); + lastNameField.setMaxLines(1); + lastNameField.setLines(1); + lastNameField.setSingleLine(true); + lastNameField.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); + lastNameField.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT); + lastNameField.setImeOptions(EditorInfo.IME_ACTION_DONE); + lastNameField.setHint(LocaleController.getString("LastName", R.string.LastName)); + AndroidUtilities.clearCursorDrawable(lastNameField); + linearLayout.addView(lastNameField); + layoutParams = (LinearLayout.LayoutParams) lastNameField.getLayoutParams(); + layoutParams.topMargin = AndroidUtilities.dp(16); + layoutParams.height = AndroidUtilities.dp(36); + layoutParams.leftMargin = AndroidUtilities.dp(24); + layoutParams.rightMargin = AndroidUtilities.dp(24); + layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; + lastNameField.setLayoutParams(layoutParams); + lastNameField.setOnEditorActionListener(new TextView.OnEditorActionListener() { + @Override + public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { + if (i == EditorInfo.IME_ACTION_DONE) { + doneButton.performClick(); + return true; + } + return false; } + }); + + TLRPC.User user = MessagesController.getInstance().getUser(user_id); + if (user != null) { + if (user.phone == null) { + if (phone != null) { + user.phone = PhoneFormat.stripExceptNumbers(phone); + } + } + firstNameField.setText(user.first_name); + firstNameField.setSelection(firstNameField.length()); + lastNameField.setText(user.last_name); } + return fragmentView; } @@ -299,6 +287,7 @@ public class ContactAddActivity extends BaseFragment implements NotificationCent @Override public void onResume() { super.onResume(); + updateAvatarLayout(); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); boolean animations = preferences.getBoolean("view_animations", true); if (!animations) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ContactsActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ContactsActivity.java index 559766f5b..39b4310bc 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ContactsActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ContactsActivity.java @@ -9,6 +9,7 @@ package org.telegram.ui; import android.app.AlertDialog; +import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; @@ -116,286 +117,281 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - searching = false; - searchWas = false; + public View createView(Context context, LayoutInflater inflater) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - if (destroyAfterSelect) { - if (returnAsResult) { - actionBar.setTitle(LocaleController.getString("SelectContact", R.string.SelectContact)); - } else { - if (createSecretChat) { - actionBar.setTitle(LocaleController.getString("NewSecretChat", R.string.NewSecretChat)); - } else { - actionBar.setTitle(LocaleController.getString("NewMessageTitle", R.string.NewMessageTitle)); - } - } + searching = false; + searchWas = false; + + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setAllowOverlayTitle(true); + if (destroyAfterSelect) { + if (returnAsResult) { + actionBar.setTitle(LocaleController.getString("SelectContact", R.string.SelectContact)); } else { - actionBar.setTitle(LocaleController.getString("Contacts", R.string.Contacts)); + if (createSecretChat) { + actionBar.setTitle(LocaleController.getString("NewSecretChat", R.string.NewSecretChat)); + } else { + actionBar.setTitle(LocaleController.getString("NewMessageTitle", R.string.NewMessageTitle)); + } + } + } else { + actionBar.setTitle(LocaleController.getString("Contacts", R.string.Contacts)); + } + + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); + } + } + }); + + ActionBarMenu menu = actionBar.createMenu(); + ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() { + @Override + public void onSearchExpand() { + searching = true; } - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); + @Override + public boolean onSearchCollapse() { + searchListViewAdapter.searchDialogs(null); + searching = false; + searchWas = false; + listView.setAdapter(listViewAdapter); + listViewAdapter.notifyDataSetChanged(); + if (android.os.Build.VERSION.SDK_INT >= 11) { + listView.setFastScrollAlwaysVisible(true); + } + listView.setFastScrollEnabled(true); + listView.setVerticalScrollBarEnabled(false); + emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts)); + return true; + } + + @Override + public void onTextChanged(EditText editText) { + if (searchListViewAdapter == null) { + return; + } + String text = editText.getText().toString(); + if (text.length() != 0) { + searchWas = true; + if (listView != null) { + listView.setAdapter(searchListViewAdapter); + searchListViewAdapter.notifyDataSetChanged(); + if (android.os.Build.VERSION.SDK_INT >= 11) { + listView.setFastScrollAlwaysVisible(false); + } + listView.setFastScrollEnabled(false); + listView.setVerticalScrollBarEnabled(true); + } + if (emptyTextView != null) { + emptyTextView.setText(LocaleController.getString("NoResult", R.string.NoResult)); } } - }); + searchListViewAdapter.searchDialogs(text); + } + }); + item.getSearchField().setHint(LocaleController.getString("Search", R.string.Search)); - ActionBarMenu menu = actionBar.createMenu(); - ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() { - @Override - public void onSearchExpand() { - searching = true; - } + searchListViewAdapter = new SearchAdapter(context, ignoreUsers, allowUsernameSearch); + listViewAdapter = new ContactsAdapter(context, onlyUsers, needPhonebook, ignoreUsers); - @Override - public boolean onSearchCollapse() { - searchListViewAdapter.searchDialogs(null); - searching = false; - searchWas = false; - listView.setAdapter(listViewAdapter); - listViewAdapter.notifyDataSetChanged(); - if (android.os.Build.VERSION.SDK_INT >= 11) { - listView.setFastScrollAlwaysVisible(true); - } - listView.setFastScrollEnabled(true); - listView.setVerticalScrollBarEnabled(false); - emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts)); - return true; - } + fragmentView = new FrameLayout(context); - @Override - public void onTextChanged(EditText editText) { - if (searchListViewAdapter == null) { + LinearLayout emptyTextLayout = new LinearLayout(context); + emptyTextLayout.setVisibility(View.INVISIBLE); + emptyTextLayout.setOrientation(LinearLayout.VERTICAL); + ((FrameLayout) fragmentView).addView(emptyTextLayout); + FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) emptyTextLayout.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.gravity = Gravity.TOP; + emptyTextLayout.setLayoutParams(layoutParams); + emptyTextLayout.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + + emptyTextView = new TextView(context); + emptyTextView.setTextColor(0xff808080); + emptyTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); + emptyTextView.setGravity(Gravity.CENTER); + emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts)); + emptyTextLayout.addView(emptyTextView); + LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) emptyTextView.getLayoutParams(); + layoutParams1.width = LinearLayout.LayoutParams.MATCH_PARENT; + layoutParams1.height = LinearLayout.LayoutParams.MATCH_PARENT; + layoutParams1.weight = 0.5f; + emptyTextView.setLayoutParams(layoutParams1); + + FrameLayout frameLayout = new FrameLayout(context); + emptyTextLayout.addView(frameLayout); + layoutParams1 = (LinearLayout.LayoutParams) frameLayout.getLayoutParams(); + layoutParams1.width = LinearLayout.LayoutParams.MATCH_PARENT; + layoutParams1.height = LinearLayout.LayoutParams.MATCH_PARENT; + layoutParams1.weight = 0.5f; + frameLayout.setLayoutParams(layoutParams1); + + listView = new LetterSectionsListView(context); + listView.setEmptyView(emptyTextLayout); + listView.setVerticalScrollBarEnabled(false); + listView.setDivider(null); + listView.setDividerHeight(0); + listView.setFastScrollEnabled(true); + listView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY); + listView.setAdapter(listViewAdapter); + if (Build.VERSION.SDK_INT >= 11) { + listView.setFastScrollAlwaysVisible(true); + listView.setVerticalScrollbarPosition(LocaleController.isRTL ? ListView.SCROLLBAR_POSITION_LEFT : ListView.SCROLLBAR_POSITION_RIGHT); + } + ((FrameLayout) fragmentView).addView(listView); + layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + listView.setLayoutParams(layoutParams); + + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, int i, long l) { + if (searching && searchWas) { + TLRPC.User user = searchListViewAdapter.getItem(i); + if (user == null) { return; } - String text = editText.getText().toString(); - if (text.length() != 0) { - searchWas = true; - if (listView != null) { - listView.setAdapter(searchListViewAdapter); - searchListViewAdapter.notifyDataSetChanged(); - if(android.os.Build.VERSION.SDK_INT >= 11) { - listView.setFastScrollAlwaysVisible(false); - } - listView.setFastScrollEnabled(false); - listView.setVerticalScrollBarEnabled(true); - } - if (emptyTextView != null) { - emptyTextView.setText(LocaleController.getString("NoResult", R.string.NoResult)); - } + if (searchListViewAdapter.isGlobalSearch(i)) { + ArrayList users = new ArrayList<>(); + users.add(user); + MessagesController.getInstance().putUsers(users, false); + MessagesStorage.getInstance().putUsersAndChats(users, null, false, true); } - searchListViewAdapter.searchDialogs(text); - } - }); - item.getSearchField().setHint(LocaleController.getString("Search", R.string.Search)); - - searchListViewAdapter = new SearchAdapter(getParentActivity(), ignoreUsers, allowUsernameSearch); - listViewAdapter = new ContactsAdapter(getParentActivity(), onlyUsers, needPhonebook, ignoreUsers); - - fragmentView = new FrameLayout(getParentActivity()); - - LinearLayout emptyTextLayout = new LinearLayout(getParentActivity()); - emptyTextLayout.setVisibility(View.INVISIBLE); - emptyTextLayout.setOrientation(LinearLayout.VERTICAL); - ((FrameLayout) fragmentView).addView(emptyTextLayout); - FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) emptyTextLayout.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.gravity = Gravity.TOP; - emptyTextLayout.setLayoutParams(layoutParams); - emptyTextLayout.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - return true; - } - }); - - emptyTextView = new TextView(getParentActivity()); - emptyTextView.setTextColor(0xff808080); - emptyTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); - emptyTextView.setGravity(Gravity.CENTER); - emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts)); - emptyTextLayout.addView(emptyTextView); - LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) emptyTextView.getLayoutParams(); - layoutParams1.width = LinearLayout.LayoutParams.MATCH_PARENT; - layoutParams1.height = LinearLayout.LayoutParams.MATCH_PARENT; - layoutParams1.weight = 0.5f; - emptyTextView.setLayoutParams(layoutParams1); - - FrameLayout frameLayout = new FrameLayout(getParentActivity()); - emptyTextLayout.addView(frameLayout); - layoutParams1 = (LinearLayout.LayoutParams) frameLayout.getLayoutParams(); - layoutParams1.width = LinearLayout.LayoutParams.MATCH_PARENT; - layoutParams1.height = LinearLayout.LayoutParams.MATCH_PARENT; - layoutParams1.weight = 0.5f; - frameLayout.setLayoutParams(layoutParams1); - - listView = new LetterSectionsListView(getParentActivity()); - listView.setEmptyView(emptyTextLayout); - listView.setVerticalScrollBarEnabled(false); - listView.setDivider(null); - listView.setDividerHeight(0); - listView.setFastScrollEnabled(true); - listView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY); - listView.setAdapter(listViewAdapter); - if (Build.VERSION.SDK_INT >= 11) { - listView.setFastScrollAlwaysVisible(true); - listView.setVerticalScrollbarPosition(LocaleController.isRTL ? ListView.SCROLLBAR_POSITION_LEFT : ListView.SCROLLBAR_POSITION_RIGHT); - } - ((FrameLayout) fragmentView).addView(listView); - layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - listView.setLayoutParams(layoutParams); - - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, int i, long l) { - if (searching && searchWas) { - TLRPC.User user = searchListViewAdapter.getItem(i); - if (user == null) { + if (returnAsResult) { + if (ignoreUsers != null && ignoreUsers.containsKey(user.id)) { return; } - if (searchListViewAdapter.isGlobalSearch(i)) { - ArrayList users = new ArrayList<>(); - users.add(user); - MessagesController.getInstance().putUsers(users, false); - MessagesStorage.getInstance().putUsersAndChats(users, null, false, true); - } - if (returnAsResult) { - if (ignoreUsers != null && ignoreUsers.containsKey(user.id)) { - return; - } - didSelectResult(user, true, null); + didSelectResult(user, true, null); + } else { + if (createSecretChat) { + creatingChat = true; + SecretChatHelper.getInstance().startSecretChat(getParentActivity(), user); } else { - if (createSecretChat) { - creatingChat = true; - SecretChatHelper.getInstance().startSecretChat(getParentActivity(), user); - } else { + Bundle args = new Bundle(); + args.putInt("user_id", user.id); + presentFragment(new ChatActivity(args), true); + } + } + } else { + int section = listViewAdapter.getSectionForPosition(i); + int row = listViewAdapter.getPositionInSectionForPosition(i); + if (row < 0 || section < 0) { + return; + } + if (!onlyUsers && section == 0) { + if (needPhonebook) { + if (row == 0) { + try { + Intent intent = new Intent(Intent.ACTION_SEND); + intent.setType("text/plain"); + intent.putExtra(Intent.EXTRA_TEXT, ContactsController.getInstance().getInviteText()); + getParentActivity().startActivityForResult(Intent.createChooser(intent, LocaleController.getString("InviteFriends", R.string.InviteFriends)), 500); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } + } else { + if (row == 0) { + if (!MessagesController.isFeatureEnabled("chat_create", ContactsActivity.this)) { + return; + } + presentFragment(new GroupCreateActivity(), false); + } else if (row == 1) { Bundle args = new Bundle(); - args.putInt("user_id", user.id); - presentFragment(new ChatActivity(args), true); + args.putBoolean("onlyUsers", true); + args.putBoolean("destroyAfterSelect", true); + args.putBoolean("createSecretChat", true); + presentFragment(new ContactsActivity(args), false); + } else if (row == 2) { + if (!MessagesController.isFeatureEnabled("broadcast_create", ContactsActivity.this)) { + return; + } + Bundle args = new Bundle(); + args.putBoolean("broadcast", true); + presentFragment(new GroupCreateActivity(args), false); } } } else { - int section = listViewAdapter.getSectionForPosition(i); - int row = listViewAdapter.getPositionInSectionForPosition(i); - if (row < 0 || section < 0) { - return; - } - if (!onlyUsers && section == 0) { - if (needPhonebook) { - if (row == 0) { + Object item = listViewAdapter.getItem(section, row); + + if (item instanceof TLRPC.User) { + TLRPC.User user = (TLRPC.User) item; + if (returnAsResult) { + if (ignoreUsers != null && ignoreUsers.containsKey(user.id)) { + return; + } + didSelectResult(user, true, null); + } else { + if (createSecretChat) { + creatingChat = true; + SecretChatHelper.getInstance().startSecretChat(getParentActivity(), user); + } else { + Bundle args = new Bundle(); + args.putInt("user_id", user.id); + presentFragment(new ChatActivity(args), true); + } + } + } else if (item instanceof ContactsController.Contact) { + ContactsController.Contact contact = (ContactsController.Contact) item; + String usePhone = null; + if (!contact.phones.isEmpty()) { + usePhone = contact.phones.get(0); + } + if (usePhone == null || getParentActivity() == null) { + return; + } + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setMessage(LocaleController.getString("InviteUser", R.string.InviteUser)); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + final String arg1 = usePhone; + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { try { - Intent intent = new Intent(Intent.ACTION_SEND); - intent.setType("text/plain"); - intent.putExtra(Intent.EXTRA_TEXT, ContactsController.getInstance().getInviteText()); - getParentActivity().startActivityForResult(Intent.createChooser(intent, LocaleController.getString("InviteFriends", R.string.InviteFriends)), 500); + Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", arg1, null)); + intent.putExtra("sms_body", LocaleController.getString("InviteText", R.string.InviteText)); + getParentActivity().startActivityForResult(intent, 500); } catch (Exception e) { FileLog.e("tmessages", e); } } - } else { - if (row == 0) { - if (!MessagesController.isFeatureEnabled("chat_create", ContactsActivity.this)) { - return; - } - presentFragment(new GroupCreateActivity(), false); - } else if (row == 1) { - Bundle args = new Bundle(); - args.putBoolean("onlyUsers", true); - args.putBoolean("destroyAfterSelect", true); - args.putBoolean("createSecretChat", true); - presentFragment(new ContactsActivity(args), false); - } else if (row == 2) { - if (!MessagesController.isFeatureEnabled("broadcast_create", ContactsActivity.this)) { - return; - } - Bundle args = new Bundle(); - args.putBoolean("broadcast", true); - presentFragment(new GroupCreateActivity(args), false); - } - } - } else { - Object item = listViewAdapter.getItem(section, row); - - if (item instanceof TLRPC.User) { - TLRPC.User user = (TLRPC.User) item; - if (returnAsResult) { - if (ignoreUsers != null && ignoreUsers.containsKey(user.id)) { - return; - } - didSelectResult(user, true, null); - } else { - if (createSecretChat) { - creatingChat = true; - SecretChatHelper.getInstance().startSecretChat(getParentActivity(), user); - } else { - Bundle args = new Bundle(); - args.putInt("user_id", user.id); - presentFragment(new ChatActivity(args), true); - } - } - } else if (item instanceof ContactsController.Contact) { - ContactsController.Contact contact = (ContactsController.Contact) item; - String usePhone = null; - if (!contact.phones.isEmpty()) { - usePhone = contact.phones.get(0); - } - if (usePhone == null || getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setMessage(LocaleController.getString("InviteUser", R.string.InviteUser)); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - final String arg1 = usePhone; - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - try { - Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", arg1, null)); - intent.putExtra("sms_body", LocaleController.getString("InviteText", R.string.InviteText)); - getParentActivity().startActivityForResult(intent, 500); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); } } } - }); - - listView.setOnScrollListener(new AbsListView.OnScrollListener() { - @Override - public void onScrollStateChanged(AbsListView absListView, int i) { - if (i == SCROLL_STATE_TOUCH_SCROLL && searching && searchWas) { - AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus()); - } - } - - @Override - public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - if (absListView.isFastScrollEnabled()) { - AndroidUtilities.clearDrawableAnimation(absListView); - } - } - }); - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); } - } + }); + + listView.setOnScrollListener(new AbsListView.OnScrollListener() { + @Override + public void onScrollStateChanged(AbsListView absListView, int i) { + if (i == SCROLL_STATE_TOUCH_SCROLL && searching && searchWas) { + AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus()); + } + } + + @Override + public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + if (absListView.isFastScrollEnabled()) { + AndroidUtilities.clearDrawableAnimation(absListView); + } + } + }); + return fragmentView; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/CountrySelectActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/CountrySelectActivity.java index 414f93456..2eb56da69 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/CountrySelectActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/CountrySelectActivity.java @@ -8,12 +8,12 @@ package org.telegram.ui; +import android.content.Context; import android.os.Build; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; -import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.EditText; @@ -61,174 +61,168 @@ public class CountrySelectActivity extends BaseFragment { } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - actionBar.setTitle(LocaleController.getString("ChooseCountry", R.string.ChooseCountry)); + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setAllowOverlayTitle(true); + actionBar.setTitle(LocaleController.getString("ChooseCountry", R.string.ChooseCountry)); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } - } - }); - - ActionBarMenu menu = actionBar.createMenu(); - ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() { - @Override - public void onSearchExpand() { - searching = true; - } - - @Override - public boolean onSearchCollapse() { - searchListViewAdapter.search(null); - searching = false; - searchWas = false; - listView.setAdapter(listViewAdapter); - if (android.os.Build.VERSION.SDK_INT >= 11) { - listView.setFastScrollAlwaysVisible(true); - } - listView.setFastScrollEnabled(true); - listView.setVerticalScrollBarEnabled(false); - - emptyTextView.setText(LocaleController.getString("ChooseCountry", R.string.ChooseCountry)); - - return true; - } - - @Override - public void onTextChanged(EditText editText) { - String text = editText.getText().toString(); - searchListViewAdapter.search(text); - if (text.length() != 0) { - searchWas = true; - if (listView != null) { - listView.setAdapter(searchListViewAdapter); - if(android.os.Build.VERSION.SDK_INT >= 11) { - listView.setFastScrollAlwaysVisible(false); - } - listView.setFastScrollEnabled(false); - listView.setVerticalScrollBarEnabled(true); - } - if (emptyTextView != null) { - - } - } - } - }); - item.getSearchField().setHint(LocaleController.getString("Search", R.string.Search)); - - searching = false; - searchWas = false; - - listViewAdapter = new CountryAdapter(getParentActivity()); - searchListViewAdapter = new CountrySearchAdapter(getParentActivity(), listViewAdapter.getCountries()); - - fragmentView = new FrameLayout(getParentActivity()); - - LinearLayout emptyTextLayout = new LinearLayout(getParentActivity()); - emptyTextLayout.setVisibility(View.INVISIBLE); - emptyTextLayout.setOrientation(LinearLayout.VERTICAL); - ((FrameLayout) fragmentView).addView(emptyTextLayout); - FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) emptyTextLayout.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.gravity = Gravity.TOP; - emptyTextLayout.setLayoutParams(layoutParams); - emptyTextLayout.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - return true; - } - }); - - emptyTextView = new TextView(getParentActivity()); - emptyTextView.setTextColor(0xff808080); - emptyTextView.setTextSize(20); - emptyTextView.setGravity(Gravity.CENTER); - emptyTextView.setText(LocaleController.getString("NoResult", R.string.NoResult)); - emptyTextLayout.addView(emptyTextView); - LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) emptyTextView.getLayoutParams(); - layoutParams1.width = LinearLayout.LayoutParams.MATCH_PARENT; - layoutParams1.height = LinearLayout.LayoutParams.MATCH_PARENT; - layoutParams1.weight = 0.5f; - emptyTextView.setLayoutParams(layoutParams1); - - FrameLayout frameLayout = new FrameLayout(getParentActivity()); - emptyTextLayout.addView(frameLayout); - layoutParams1 = (LinearLayout.LayoutParams) frameLayout.getLayoutParams(); - layoutParams1.width = LinearLayout.LayoutParams.MATCH_PARENT; - layoutParams1.height = LinearLayout.LayoutParams.MATCH_PARENT; - layoutParams1.weight = 0.5f; - frameLayout.setLayoutParams(layoutParams1); - - listView = new LetterSectionsListView(getParentActivity()); - listView.setEmptyView(emptyTextLayout); - listView.setVerticalScrollBarEnabled(false); - listView.setDivider(null); - listView.setDividerHeight(0); - listView.setFastScrollEnabled(true); - listView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY); - listView.setAdapter(listViewAdapter); - if (Build.VERSION.SDK_INT >= 11) { - listView.setFastScrollAlwaysVisible(true); - listView.setVerticalScrollbarPosition(LocaleController.isRTL ? ListView.SCROLLBAR_POSITION_LEFT : ListView.SCROLLBAR_POSITION_RIGHT); - } - ((FrameLayout) fragmentView).addView(listView); - layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - listView.setLayoutParams(layoutParams); - - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, int i, long l) { - Country country = null; - if (searching && searchWas) { - country = searchListViewAdapter.getItem(i); - } else { - int section = listViewAdapter.getSectionForPosition(i); - int row = listViewAdapter.getPositionInSectionForPosition(i); - if (row < 0 || section < 0) { - return; - } - country = listViewAdapter.getItem(section, row); - } - if (i < 0) { - return; - } - if (country != null && delegate != null) { - delegate.didSelectCountry(country.name); - } + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { finishFragment(); } - }); - - listView.setOnScrollListener(new AbsListView.OnScrollListener() { - @Override - public void onScrollStateChanged(AbsListView absListView, int i) { - if (i == SCROLL_STATE_TOUCH_SCROLL && searching && searchWas) { - AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus()); - } - } - - @Override - public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - if (absListView.isFastScrollEnabled()) { - AndroidUtilities.clearDrawableAnimation(absListView); - } - } - }); - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); } + }); + + ActionBarMenu menu = actionBar.createMenu(); + ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() { + @Override + public void onSearchExpand() { + searching = true; + } + + @Override + public boolean onSearchCollapse() { + searchListViewAdapter.search(null); + searching = false; + searchWas = false; + listView.setAdapter(listViewAdapter); + if (android.os.Build.VERSION.SDK_INT >= 11) { + listView.setFastScrollAlwaysVisible(true); + } + listView.setFastScrollEnabled(true); + listView.setVerticalScrollBarEnabled(false); + + emptyTextView.setText(LocaleController.getString("ChooseCountry", R.string.ChooseCountry)); + + return true; + } + + @Override + public void onTextChanged(EditText editText) { + String text = editText.getText().toString(); + searchListViewAdapter.search(text); + if (text.length() != 0) { + searchWas = true; + if (listView != null) { + listView.setAdapter(searchListViewAdapter); + if (android.os.Build.VERSION.SDK_INT >= 11) { + listView.setFastScrollAlwaysVisible(false); + } + listView.setFastScrollEnabled(false); + listView.setVerticalScrollBarEnabled(true); + } + if (emptyTextView != null) { + + } + } + } + }); + item.getSearchField().setHint(LocaleController.getString("Search", R.string.Search)); + + searching = false; + searchWas = false; + + listViewAdapter = new CountryAdapter(context); + searchListViewAdapter = new CountrySearchAdapter(context, listViewAdapter.getCountries()); + + fragmentView = new FrameLayout(context); + + LinearLayout emptyTextLayout = new LinearLayout(context); + emptyTextLayout.setVisibility(View.INVISIBLE); + emptyTextLayout.setOrientation(LinearLayout.VERTICAL); + ((FrameLayout) fragmentView).addView(emptyTextLayout); + FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) emptyTextLayout.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.gravity = Gravity.TOP; + emptyTextLayout.setLayoutParams(layoutParams); + emptyTextLayout.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + + emptyTextView = new TextView(context); + emptyTextView.setTextColor(0xff808080); + emptyTextView.setTextSize(20); + emptyTextView.setGravity(Gravity.CENTER); + emptyTextView.setText(LocaleController.getString("NoResult", R.string.NoResult)); + emptyTextLayout.addView(emptyTextView); + LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) emptyTextView.getLayoutParams(); + layoutParams1.width = LinearLayout.LayoutParams.MATCH_PARENT; + layoutParams1.height = LinearLayout.LayoutParams.MATCH_PARENT; + layoutParams1.weight = 0.5f; + emptyTextView.setLayoutParams(layoutParams1); + + FrameLayout frameLayout = new FrameLayout(context); + emptyTextLayout.addView(frameLayout); + layoutParams1 = (LinearLayout.LayoutParams) frameLayout.getLayoutParams(); + layoutParams1.width = LinearLayout.LayoutParams.MATCH_PARENT; + layoutParams1.height = LinearLayout.LayoutParams.MATCH_PARENT; + layoutParams1.weight = 0.5f; + frameLayout.setLayoutParams(layoutParams1); + + listView = new LetterSectionsListView(context); + listView.setEmptyView(emptyTextLayout); + listView.setVerticalScrollBarEnabled(false); + listView.setDivider(null); + listView.setDividerHeight(0); + listView.setFastScrollEnabled(true); + listView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY); + listView.setAdapter(listViewAdapter); + if (Build.VERSION.SDK_INT >= 11) { + listView.setFastScrollAlwaysVisible(true); + listView.setVerticalScrollbarPosition(LocaleController.isRTL ? ListView.SCROLLBAR_POSITION_LEFT : ListView.SCROLLBAR_POSITION_RIGHT); } + ((FrameLayout) fragmentView).addView(listView); + layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + listView.setLayoutParams(layoutParams); + + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, int i, long l) { + Country country = null; + if (searching && searchWas) { + country = searchListViewAdapter.getItem(i); + } else { + int section = listViewAdapter.getSectionForPosition(i); + int row = listViewAdapter.getPositionInSectionForPosition(i); + if (row < 0 || section < 0) { + return; + } + country = listViewAdapter.getItem(section, row); + } + if (i < 0) { + return; + } + if (country != null && delegate != null) { + delegate.didSelectCountry(country.name); + } + finishFragment(); + } + }); + + listView.setOnScrollListener(new AbsListView.OnScrollListener() { + @Override + public void onScrollStateChanged(AbsListView absListView, int i) { + if (i == SCROLL_STATE_TOUCH_SCROLL && searching && searchWas) { + AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus()); + } + } + + @Override + public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + if (absListView.isFastScrollEnabled()) { + AndroidUtilities.clearDrawableAnimation(absListView); + } + } + }); + return fragmentView; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/DocumentSelectActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/DocumentSelectActivity.java index 1d7cc0920..1daa1499b 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/DocumentSelectActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/DocumentSelectActivity.java @@ -125,7 +125,7 @@ public class DocumentSelectActivity extends BaseFragment { } @Override - public View createView(LayoutInflater inflater) { + public View createView(Context context, LayoutInflater inflater) { if (!receiverRegistered) { receiverRegistered = true; IntentFilter filter = new IntentFilter(); @@ -142,217 +142,211 @@ public class DocumentSelectActivity extends BaseFragment { getParentActivity().registerReceiver(receiver, filter); } - if (fragmentView == null) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - actionBar.setTitle(LocaleController.getString("SelectFile", R.string.SelectFile)); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } else if (id == -2) { - selectedFiles.clear(); - actionBar.hideActionMode(); - listView.invalidateViews(); - } else if (id == done) { + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setAllowOverlayTitle(true); + actionBar.setTitle(LocaleController.getString("SelectFile", R.string.SelectFile)); + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); + } else if (id == -2) { + selectedFiles.clear(); + actionBar.hideActionMode(); + listView.invalidateViews(); + } else if (id == done) { + if (delegate != null) { + ArrayList files = new ArrayList<>(); + files.addAll(selectedFiles.keySet()); + delegate.didSelectFiles(DocumentSelectActivity.this, files); + } + } + } + }); + selectedFiles.clear(); + actionModeViews.clear(); + + final ActionBarMenu actionMode = actionBar.createActionMode(); + actionModeViews.add(actionMode.addItem(-2, R.drawable.ic_ab_back_grey, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); + + selectedMessagesCountTextView = new TextView(actionMode.getContext()); + selectedMessagesCountTextView.setTextSize(18); + selectedMessagesCountTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); + selectedMessagesCountTextView.setTextColor(0xff737373); + selectedMessagesCountTextView.setSingleLine(true); + selectedMessagesCountTextView.setLines(1); + selectedMessagesCountTextView.setEllipsize(TextUtils.TruncateAt.END); + selectedMessagesCountTextView.setPadding(AndroidUtilities.dp(11), 0, 0, AndroidUtilities.dp(2)); + selectedMessagesCountTextView.setGravity(Gravity.CENTER_VERTICAL); + selectedMessagesCountTextView.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + actionMode.addView(selectedMessagesCountTextView); + LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) selectedMessagesCountTextView.getLayoutParams(); + layoutParams.weight = 1; + layoutParams.width = 0; + layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT; + selectedMessagesCountTextView.setLayoutParams(layoutParams); + + actionModeViews.add(actionMode.addItem(done, R.drawable.ic_ab_done_gray, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); + + fragmentView = inflater.inflate(R.layout.document_select_layout, null, false); + listAdapter = new ListAdapter(context); + emptyView = (TextView) fragmentView.findViewById(R.id.searchEmptyView); + emptyView.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + listView = (ListView) fragmentView.findViewById(R.id.listView); + listView.setEmptyView(emptyView); + listView.setAdapter(listAdapter); + + listView.setOnScrollListener(new AbsListView.OnScrollListener() { + @Override + public void onScrollStateChanged(AbsListView view, int scrollState) { + scrolling = scrollState != SCROLL_STATE_IDLE; + } + + @Override + public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + + } + }); + + listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { + @Override + public boolean onItemLongClick(AdapterView parent, View view, int i, long id) { + if (actionBar.isActionModeShowed() || i < 0 || i >= items.size()) { + return false; + } + ListItem item = items.get(i); + File file = item.file; + if (file != null && !file.isDirectory()) { + if (!file.canRead()) { + showErrorBox(LocaleController.getString("AccessError", R.string.AccessError)); + return false; + } + if (sizeLimit != 0) { + if (file.length() > sizeLimit) { + showErrorBox(LocaleController.formatString("FileUploadLimit", R.string.FileUploadLimit, Utilities.formatFileSize(sizeLimit))); + return false; + } + } + if (file.length() == 0) { + return false; + } + selectedFiles.put(file.toString(), item); + selectedMessagesCountTextView.setText(String.format("%d", selectedFiles.size())); + if (Build.VERSION.SDK_INT >= 11) { + AnimatorSetProxy animatorSet = new AnimatorSetProxy(); + ArrayList animators = new ArrayList<>(); + for (int a = 0; a < actionModeViews.size(); a++) { + View view2 = actionModeViews.get(a); + AndroidUtilities.clearDrawableAnimation(view2); + if (a < 1) { + animators.add(ObjectAnimatorProxy.ofFloat(view2, "translationX", -AndroidUtilities.dp(56), 0)); + } else { + animators.add(ObjectAnimatorProxy.ofFloat(view2, "scaleY", 0.1f, 1.0f)); + } + } + animatorSet.playTogether(animators); + animatorSet.setDuration(250); + animatorSet.start(); + } + scrolling = false; + if (view instanceof SharedDocumentCell) { + ((SharedDocumentCell) view).setChecked(true, true); + } + actionBar.showActionMode(); + } + return true; + } + }); + + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, int i, long l) { + if (i < 0 || i >= items.size()) { + return; + } + ListItem item = items.get(i); + File file = item.file; + if (file == null) { + if (item.icon == R.drawable.ic_storage_gallery) { + if (delegate != null) { + delegate.startDocumentSelectActivity(); + } + finishFragment(false); + } else { + HistoryEntry he = history.remove(history.size() - 1); + actionBar.setTitle(he.title); + if (he.dir != null) { + listFiles(he.dir); + } else { + listRoots(); + } + listView.setSelectionFromTop(he.scrollItem, he.scrollOffset); + } + } else if (file.isDirectory()) { + HistoryEntry he = new HistoryEntry(); + he.scrollItem = listView.getFirstVisiblePosition(); + he.scrollOffset = listView.getChildAt(0).getTop(); + he.dir = currentDir; + he.title = actionBar.getTitle().toString(); + history.add(he); + if (!listFiles(file)) { + history.remove(he); + return; + } + actionBar.setTitle(item.title); + listView.setSelection(0); + } else { + if (!file.canRead()) { + showErrorBox(LocaleController.getString("AccessError", R.string.AccessError)); + return; + } + if (sizeLimit != 0) { + if (file.length() > sizeLimit) { + showErrorBox(LocaleController.formatString("FileUploadLimit", R.string.FileUploadLimit, Utilities.formatFileSize(sizeLimit))); + return; + } + } + if (file.length() == 0) { + return; + } + if (actionBar.isActionModeShowed()) { + if (selectedFiles.containsKey(file.toString())) { + selectedFiles.remove(file.toString()); + } else { + selectedFiles.put(file.toString(), item); + } + if (selectedFiles.isEmpty()) { + actionBar.hideActionMode(); + } else { + selectedMessagesCountTextView.setText(String.format("%d", selectedFiles.size())); + } + scrolling = false; + if (view instanceof SharedDocumentCell) { + ((SharedDocumentCell) view).setChecked(selectedFiles.containsKey(item.file.toString()), true); + } + } else { if (delegate != null) { ArrayList files = new ArrayList<>(); - files.addAll(selectedFiles.keySet()); + files.add(file.getAbsolutePath()); delegate.didSelectFiles(DocumentSelectActivity.this, files); } } } - }); - selectedFiles.clear(); - actionModeViews.clear(); - - final ActionBarMenu actionMode = actionBar.createActionMode(); - actionModeViews.add(actionMode.addItem(-2, R.drawable.ic_ab_back_grey, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); - - selectedMessagesCountTextView = new TextView(actionMode.getContext()); - selectedMessagesCountTextView.setTextSize(18); - selectedMessagesCountTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - selectedMessagesCountTextView.setTextColor(0xff737373); - selectedMessagesCountTextView.setSingleLine(true); - selectedMessagesCountTextView.setLines(1); - selectedMessagesCountTextView.setEllipsize(TextUtils.TruncateAt.END); - selectedMessagesCountTextView.setPadding(AndroidUtilities.dp(11), 0, 0, AndroidUtilities.dp(2)); - selectedMessagesCountTextView.setGravity(Gravity.CENTER_VERTICAL); - selectedMessagesCountTextView.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - return true; - } - }); - actionMode.addView(selectedMessagesCountTextView); - LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams)selectedMessagesCountTextView.getLayoutParams(); - layoutParams.weight = 1; - layoutParams.width = 0; - layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT; - selectedMessagesCountTextView.setLayoutParams(layoutParams); - - actionModeViews.add(actionMode.addItem(done, R.drawable.ic_ab_done_gray, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); - - fragmentView = inflater.inflate(R.layout.document_select_layout, null, false); - listAdapter = new ListAdapter(getParentActivity()); - emptyView = (TextView)fragmentView.findViewById(R.id.searchEmptyView); - emptyView.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - return true; - } - }); - listView = (ListView)fragmentView.findViewById(R.id.listView); - listView.setEmptyView(emptyView); - listView.setAdapter(listAdapter); - - listView.setOnScrollListener(new AbsListView.OnScrollListener() { - @Override - public void onScrollStateChanged(AbsListView view, int scrollState) { - scrolling = scrollState != SCROLL_STATE_IDLE; - } - - @Override - public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - - } - }); - - listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { - @Override - public boolean onItemLongClick(AdapterView parent, View view, int i, long id) { - if (actionBar.isActionModeShowed() || i < 0 || i >= items.size()) { - return false; - } - ListItem item = items.get(i); - File file = item.file; - if (file != null && !file.isDirectory()) { - if (!file.canRead()) { - showErrorBox(LocaleController.getString("AccessError", R.string.AccessError)); - return false; - } - if (sizeLimit != 0) { - if (file.length() > sizeLimit) { - showErrorBox(LocaleController.formatString("FileUploadLimit", R.string.FileUploadLimit, Utilities.formatFileSize(sizeLimit))); - return false; - } - } - if (file.length() == 0) { - return false; - } - selectedFiles.put(file.toString(), item); - selectedMessagesCountTextView.setText(String.format("%d", selectedFiles.size())); - if (Build.VERSION.SDK_INT >= 11) { - AnimatorSetProxy animatorSet = new AnimatorSetProxy(); - ArrayList animators = new ArrayList<>(); - for (int a = 0; a < actionModeViews.size(); a++) { - View view2 = actionModeViews.get(a); - AndroidUtilities.clearDrawableAnimation(view2); - if (a < 1) { - animators.add(ObjectAnimatorProxy.ofFloat(view2, "translationX", -AndroidUtilities.dp(56), 0)); - } else { - animators.add(ObjectAnimatorProxy.ofFloat(view2, "scaleY", 0.1f, 1.0f)); - } - } - animatorSet.playTogether(animators); - animatorSet.setDuration(250); - animatorSet.start(); - } - scrolling = false; - if (view instanceof SharedDocumentCell) { - ((SharedDocumentCell) view).setChecked(true, true); - } - actionBar.showActionMode(); - } - return true; - } - }); - - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, int i, long l) { - if (i < 0 || i >= items.size()) { - return; - } - ListItem item = items.get(i); - File file = item.file; - if (file == null) { - if (item.icon == R.drawable.ic_storage_gallery) { - if (delegate != null) { - delegate.startDocumentSelectActivity(); - } - finishFragment(false); - } else { - HistoryEntry he = history.remove(history.size() - 1); - actionBar.setTitle(he.title); - if (he.dir != null) { - listFiles(he.dir); - } else { - listRoots(); - } - listView.setSelectionFromTop(he.scrollItem, he.scrollOffset); - } - } else if (file.isDirectory()) { - HistoryEntry he = new HistoryEntry(); - he.scrollItem = listView.getFirstVisiblePosition(); - he.scrollOffset = listView.getChildAt(0).getTop(); - he.dir = currentDir; - he.title = actionBar.getTitle().toString(); - history.add(he); - if (!listFiles(file)) { - history.remove(he); - return; - } - actionBar.setTitle(item.title); - listView.setSelection(0); - } else { - if (!file.canRead()) { - showErrorBox(LocaleController.getString("AccessError", R.string.AccessError)); - return; - } - if (sizeLimit != 0) { - if (file.length() > sizeLimit) { - showErrorBox(LocaleController.formatString("FileUploadLimit", R.string.FileUploadLimit, Utilities.formatFileSize(sizeLimit))); - return; - } - } - if (file.length() == 0) { - return; - } - if (actionBar.isActionModeShowed()) { - if (selectedFiles.containsKey(file.toString())) { - selectedFiles.remove(file.toString()); - } else { - selectedFiles.put(file.toString(), item); - } - if (selectedFiles.isEmpty()) { - actionBar.hideActionMode(); - } else { - selectedMessagesCountTextView.setText(String.format("%d", selectedFiles.size())); - } - scrolling = false; - if (view instanceof SharedDocumentCell) { - ((SharedDocumentCell) view).setChecked(selectedFiles.containsKey(item.file.toString()), true); - } - } else { - if (delegate != null) { - ArrayList files = new ArrayList<>(); - files.add(file.getAbsolutePath()); - delegate.didSelectFiles(DocumentSelectActivity.this, files); - } - } - } - } - }); - - listRoots(); - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); } - } + }); + + listRoots(); + return fragmentView; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateActivity.java index f675fd7d8..5f18cf414 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateActivity.java @@ -9,6 +9,7 @@ package org.telegram.ui; import android.app.Activity; +import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; @@ -28,7 +29,6 @@ import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; -import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.AbsListView; import android.widget.AdapterView; @@ -141,337 +141,331 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - searching = false; - searchWas = false; + public View createView(Context context, LayoutInflater inflater) { + searching = false; + searchWas = false; - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - if (isAlwaysShare) { - actionBar.setTitle(LocaleController.getString("AlwaysShareWithTitle", R.string.AlwaysShareWithTitle)); - } else if (isNeverShare) { - actionBar.setTitle(LocaleController.getString("NeverShareWithTitle", R.string.NeverShareWithTitle)); - } else { - actionBar.setTitle(isBroadcast ? LocaleController.getString("NewBroadcastList", R.string.NewBroadcastList) : LocaleController.getString("NewGroup", R.string.NewGroup)); - actionBar.setSubtitle(LocaleController.formatString("MembersCount", R.string.MembersCount, selectedContacts.size(), maxCount)); - } + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setAllowOverlayTitle(true); + if (isAlwaysShare) { + actionBar.setTitle(LocaleController.getString("AlwaysShareWithTitle", R.string.AlwaysShareWithTitle)); + } else if (isNeverShare) { + actionBar.setTitle(LocaleController.getString("NeverShareWithTitle", R.string.NeverShareWithTitle)); + } else { + actionBar.setTitle(isBroadcast ? LocaleController.getString("NewBroadcastList", R.string.NewBroadcastList) : LocaleController.getString("NewGroup", R.string.NewGroup)); + actionBar.setSubtitle(LocaleController.formatString("MembersCount", R.string.MembersCount, selectedContacts.size(), maxCount)); + } - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } else if (id == done_button) { - if (selectedContacts.isEmpty()) { - return; - } - ArrayList result = new ArrayList<>(); - result.addAll(selectedContacts.keySet()); - if (isAlwaysShare || isNeverShare) { - if (delegate != null) { - delegate.didSelectUsers(result); - } - finishFragment(); - } else { - Bundle args = new Bundle(); - args.putIntegerArrayList("result", result); - args.putBoolean("broadcast", isBroadcast); - presentFragment(new GroupCreateFinalActivity(args)); - } - } - } - }); - ActionBarMenu menu = actionBar.createMenu(); - menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); - - searchListViewAdapter = new SearchAdapter(getParentActivity(), null, false); - searchListViewAdapter.setCheckedMap(selectedContacts); - searchListViewAdapter.setUseUserCell(true); - listViewAdapter = new ContactsAdapter(getParentActivity(), true, false, null); - listViewAdapter.setCheckedMap(selectedContacts); - - fragmentView = new LinearLayout(getParentActivity()); - LinearLayout linearLayout = (LinearLayout) fragmentView; - linearLayout.setOrientation(LinearLayout.VERTICAL); - - FrameLayout frameLayout = new FrameLayout(getParentActivity()); - linearLayout.addView(frameLayout); - LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) frameLayout.getLayoutParams(); - layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT; - layoutParams.gravity = Gravity.TOP; - frameLayout.setLayoutParams(layoutParams); - - userSelectEditText = new EditText(getParentActivity()); - userSelectEditText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - userSelectEditText.setHintTextColor(0xff979797); - userSelectEditText.setTextColor(0xff212121); - userSelectEditText.setInputType(InputType.TYPE_TEXT_VARIATION_FILTER | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_FLAG_MULTI_LINE); - userSelectEditText.setMinimumHeight(AndroidUtilities.dp(54)); - userSelectEditText.setSingleLine(false); - userSelectEditText.setLines(2); - userSelectEditText.setMaxLines(2); - userSelectEditText.setVerticalScrollBarEnabled(true); - userSelectEditText.setHorizontalScrollBarEnabled(false); - userSelectEditText.setPadding(0, 0, 0, 0); - userSelectEditText.setImeOptions(EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI); - userSelectEditText.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL); - AndroidUtilities.clearCursorDrawable(userSelectEditText); - frameLayout.addView(userSelectEditText); - FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) userSelectEditText.getLayoutParams(); - layoutParams1.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams1.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams1.leftMargin = AndroidUtilities.dp(10); - layoutParams1.rightMargin = AndroidUtilities.dp(10); - layoutParams1.gravity = Gravity.TOP; - userSelectEditText.setLayoutParams(layoutParams1); - - if (isAlwaysShare) { - userSelectEditText.setHint(LocaleController.getString("AlwaysShareWithPlaceholder", R.string.AlwaysShareWithPlaceholder)); - } else if (isNeverShare) { - userSelectEditText.setHint(LocaleController.getString("NeverShareWithPlaceholder", R.string.NeverShareWithPlaceholder)); - } else { - userSelectEditText.setHint(LocaleController.getString("SendMessageTo", R.string.SendMessageTo)); - } - if (Build.VERSION.SDK_INT >= 11) { - userSelectEditText.setTextIsSelectable(false); - } - userSelectEditText.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) { - if (!ignoreChange) { - beforeChangeIndex = userSelectEditText.getSelectionStart(); - changeString = new SpannableString(charSequence); - } - } - - @Override - public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { - - } - - @Override - public void afterTextChanged(Editable editable) { - if (!ignoreChange) { - boolean search = false; - int afterChangeIndex = userSelectEditText.getSelectionEnd(); - if (editable.toString().length() < changeString.toString().length()) { - String deletedString = ""; - try { - deletedString = changeString.toString().substring(afterChangeIndex, beforeChangeIndex); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - if (deletedString.length() > 0) { - if (searching && searchWas) { - search = true; - } - Spannable span = userSelectEditText.getText(); - for (int a = 0; a < allSpans.size(); a++) { - XImageSpan sp = allSpans.get(a); - if (span.getSpanStart(sp) == -1) { - allSpans.remove(sp); - selectedContacts.remove(sp.uid); - } - } - if (!isAlwaysShare && !isNeverShare) { - actionBar.setSubtitle(LocaleController.formatString("MembersCount", R.string.MembersCount, selectedContacts.size(), maxCount)); - } - listView.invalidateViews(); - } else { - search = true; - } - } else { - search = true; - } - if (search) { - String text = userSelectEditText.getText().toString().replace("<", ""); - if (text.length() != 0) { - searching = true; - searchWas = true; - if (listView != null) { - listView.setAdapter(searchListViewAdapter); - searchListViewAdapter.notifyDataSetChanged(); - if(android.os.Build.VERSION.SDK_INT >= 11) { - listView.setFastScrollAlwaysVisible(false); - } - listView.setFastScrollEnabled(false); - listView.setVerticalScrollBarEnabled(true); - } - if (emptyTextView != null) { - emptyTextView.setText(LocaleController.getString("NoResult", R.string.NoResult)); - } - searchListViewAdapter.searchDialogs(text); - } else { - searchListViewAdapter.searchDialogs(null); - searching = false; - searchWas = false; - listView.setAdapter(listViewAdapter); - listViewAdapter.notifyDataSetChanged(); - if (android.os.Build.VERSION.SDK_INT >= 11) { - listView.setFastScrollAlwaysVisible(true); - } - listView.setFastScrollEnabled(true); - listView.setVerticalScrollBarEnabled(false); - emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts)); - } - } - } - } - }); - - LinearLayout emptyTextLayout = new LinearLayout(getParentActivity()); - emptyTextLayout.setVisibility(View.INVISIBLE); - emptyTextLayout.setOrientation(LinearLayout.VERTICAL); - linearLayout.addView(emptyTextLayout); - layoutParams = (LinearLayout.LayoutParams) emptyTextLayout.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - emptyTextLayout.setLayoutParams(layoutParams); - emptyTextLayout.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - return true; - } - }); - - emptyTextView = new TextView(getParentActivity()); - emptyTextView.setTextColor(0xff808080); - emptyTextView.setTextSize(20); - emptyTextView.setGravity(Gravity.CENTER); - emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts)); - emptyTextLayout.addView(emptyTextView); - layoutParams = (LinearLayout.LayoutParams) emptyTextView.getLayoutParams(); - layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT; - layoutParams.weight = 0.5f; - emptyTextView.setLayoutParams(layoutParams); - - FrameLayout frameLayout2 = new FrameLayout(getParentActivity()); - emptyTextLayout.addView(frameLayout2); - layoutParams = (LinearLayout.LayoutParams) frameLayout2.getLayoutParams(); - layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT; - layoutParams.weight = 0.5f; - frameLayout2.setLayoutParams(layoutParams); - - listView = new LetterSectionsListView(getParentActivity()); - listView.setEmptyView(emptyTextLayout); - listView.setVerticalScrollBarEnabled(false); - listView.setDivider(null); - listView.setDividerHeight(0); - listView.setFastScrollEnabled(true); - listView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY); - listView.setAdapter(listViewAdapter); - if (Build.VERSION.SDK_INT >= 11) { - listView.setFastScrollAlwaysVisible(true); - listView.setVerticalScrollbarPosition(LocaleController.isRTL ? ListView.SCROLLBAR_POSITION_LEFT : ListView.SCROLLBAR_POSITION_RIGHT); - } - linearLayout.addView(listView); - layoutParams = (LinearLayout.LayoutParams) listView.getLayoutParams(); - layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT; - listView.setLayoutParams(layoutParams); - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, int i, long l) { - TLRPC.User user = null; - if (searching && searchWas) { - user = searchListViewAdapter.getItem(i); - } else { - int section = listViewAdapter.getSectionForPosition(i); - int row = listViewAdapter.getPositionInSectionForPosition(i); - if (row < 0 || section < 0) { - return; - } - user = (TLRPC.User) listViewAdapter.getItem(section, row); - } - if (user == null) { + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); + } else if (id == done_button) { + if (selectedContacts.isEmpty()) { return; } + ArrayList result = new ArrayList<>(); + result.addAll(selectedContacts.keySet()); + if (isAlwaysShare || isNeverShare) { + if (delegate != null) { + delegate.didSelectUsers(result); + } + finishFragment(); + } else { + Bundle args = new Bundle(); + args.putIntegerArrayList("result", result); + args.putBoolean("broadcast", isBroadcast); + presentFragment(new GroupCreateFinalActivity(args)); + } + } + } + }); + ActionBarMenu menu = actionBar.createMenu(); + menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); - boolean check = true; - if (selectedContacts.containsKey(user.id)) { - check = false; + searchListViewAdapter = new SearchAdapter(context, null, false); + searchListViewAdapter.setCheckedMap(selectedContacts); + searchListViewAdapter.setUseUserCell(true); + listViewAdapter = new ContactsAdapter(context, true, false, null); + listViewAdapter.setCheckedMap(selectedContacts); + + fragmentView = new LinearLayout(context); + LinearLayout linearLayout = (LinearLayout) fragmentView; + linearLayout.setOrientation(LinearLayout.VERTICAL); + + FrameLayout frameLayout = new FrameLayout(context); + linearLayout.addView(frameLayout); + LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) frameLayout.getLayoutParams(); + layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams.gravity = Gravity.TOP; + frameLayout.setLayoutParams(layoutParams); + + userSelectEditText = new EditText(context); + userSelectEditText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); + userSelectEditText.setHintTextColor(0xff979797); + userSelectEditText.setTextColor(0xff212121); + userSelectEditText.setInputType(InputType.TYPE_TEXT_VARIATION_FILTER | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_FLAG_MULTI_LINE); + userSelectEditText.setMinimumHeight(AndroidUtilities.dp(54)); + userSelectEditText.setSingleLine(false); + userSelectEditText.setLines(2); + userSelectEditText.setMaxLines(2); + userSelectEditText.setVerticalScrollBarEnabled(true); + userSelectEditText.setHorizontalScrollBarEnabled(false); + userSelectEditText.setPadding(0, 0, 0, 0); + userSelectEditText.setImeOptions(EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI); + userSelectEditText.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL); + AndroidUtilities.clearCursorDrawable(userSelectEditText); + frameLayout.addView(userSelectEditText); + FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) userSelectEditText.getLayoutParams(); + layoutParams1.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams1.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams1.leftMargin = AndroidUtilities.dp(10); + layoutParams1.rightMargin = AndroidUtilities.dp(10); + layoutParams1.gravity = Gravity.TOP; + userSelectEditText.setLayoutParams(layoutParams1); + + if (isAlwaysShare) { + userSelectEditText.setHint(LocaleController.getString("AlwaysShareWithPlaceholder", R.string.AlwaysShareWithPlaceholder)); + } else if (isNeverShare) { + userSelectEditText.setHint(LocaleController.getString("NeverShareWithPlaceholder", R.string.NeverShareWithPlaceholder)); + } else { + userSelectEditText.setHint(LocaleController.getString("SendMessageTo", R.string.SendMessageTo)); + } + if (Build.VERSION.SDK_INT >= 11) { + userSelectEditText.setTextIsSelectable(false); + } + userSelectEditText.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) { + if (!ignoreChange) { + beforeChangeIndex = userSelectEditText.getSelectionStart(); + changeString = new SpannableString(charSequence); + } + } + + @Override + public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { + + } + + @Override + public void afterTextChanged(Editable editable) { + if (!ignoreChange) { + boolean search = false; + int afterChangeIndex = userSelectEditText.getSelectionEnd(); + if (editable.toString().length() < changeString.toString().length()) { + String deletedString = ""; try { - XImageSpan span = selectedContacts.get(user.id); - selectedContacts.remove(user.id); - SpannableStringBuilder text = new SpannableStringBuilder(userSelectEditText.getText()); - text.delete(text.getSpanStart(span), text.getSpanEnd(span)); - allSpans.remove(span); - ignoreChange = true; - userSelectEditText.setText(text); - userSelectEditText.setSelection(text.length()); - ignoreChange = false; + deletedString = changeString.toString().substring(afterChangeIndex, beforeChangeIndex); } catch (Exception e) { FileLog.e("tmessages", e); } + if (deletedString.length() > 0) { + if (searching && searchWas) { + search = true; + } + Spannable span = userSelectEditText.getText(); + for (int a = 0; a < allSpans.size(); a++) { + XImageSpan sp = allSpans.get(a); + if (span.getSpanStart(sp) == -1) { + allSpans.remove(sp); + selectedContacts.remove(sp.uid); + } + } + if (!isAlwaysShare && !isNeverShare) { + actionBar.setSubtitle(LocaleController.formatString("MembersCount", R.string.MembersCount, selectedContacts.size(), maxCount)); + } + listView.invalidateViews(); + } else { + search = true; + } } else { - if (selectedContacts.size() == maxCount) { - return; - } - ignoreChange = true; - XImageSpan span = createAndPutChipForUser(user); - span.uid = user.id; - ignoreChange = false; + search = true; } - if (!isAlwaysShare && !isNeverShare) { - actionBar.setSubtitle(LocaleController.formatString("MembersCount", R.string.MembersCount, selectedContacts.size(), maxCount)); - } - if (searching || searchWas) { - ignoreChange = true; - SpannableStringBuilder ssb = new SpannableStringBuilder(""); - for (ImageSpan sp : allSpans) { - ssb.append("<<"); - ssb.setSpan(sp, ssb.length() - 2, ssb.length(), SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE); - } - userSelectEditText.setText(ssb); - userSelectEditText.setSelection(ssb.length()); - ignoreChange = false; - - searchListViewAdapter.searchDialogs(null); - searching = false; - searchWas = false; - listView.setAdapter(listViewAdapter); - listViewAdapter.notifyDataSetChanged(); - if (android.os.Build.VERSION.SDK_INT >= 11) { - listView.setFastScrollAlwaysVisible(true); - } - listView.setFastScrollEnabled(true); - listView.setVerticalScrollBarEnabled(false); - emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts)); - } else { - if (view instanceof UserCell) { - ((UserCell) view).setChecked(check, true); + if (search) { + String text = userSelectEditText.getText().toString().replace("<", ""); + if (text.length() != 0) { + searching = true; + searchWas = true; + if (listView != null) { + listView.setAdapter(searchListViewAdapter); + searchListViewAdapter.notifyDataSetChanged(); + if (android.os.Build.VERSION.SDK_INT >= 11) { + listView.setFastScrollAlwaysVisible(false); + } + listView.setFastScrollEnabled(false); + listView.setVerticalScrollBarEnabled(true); + } + if (emptyTextView != null) { + emptyTextView.setText(LocaleController.getString("NoResult", R.string.NoResult)); + } + searchListViewAdapter.searchDialogs(text); + } else { + searchListViewAdapter.searchDialogs(null); + searching = false; + searchWas = false; + listView.setAdapter(listViewAdapter); + listViewAdapter.notifyDataSetChanged(); + if (android.os.Build.VERSION.SDK_INT >= 11) { + listView.setFastScrollAlwaysVisible(true); + } + listView.setFastScrollEnabled(true); + listView.setVerticalScrollBarEnabled(false); + emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts)); } } } - }); - listView.setOnScrollListener(new AbsListView.OnScrollListener() { - @Override - public void onScrollStateChanged(AbsListView absListView, int i) { - if (i == SCROLL_STATE_TOUCH_SCROLL) { - AndroidUtilities.hideKeyboard(userSelectEditText); - } - if (listViewAdapter != null) { - listViewAdapter.setIsScrolling(i != SCROLL_STATE_IDLE); - } - } - - @Override - public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - if (absListView.isFastScrollEnabled()) { - AndroidUtilities.clearDrawableAnimation(absListView); - } - } - }); - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); } + }); + + LinearLayout emptyTextLayout = new LinearLayout(context); + emptyTextLayout.setVisibility(View.INVISIBLE); + emptyTextLayout.setOrientation(LinearLayout.VERTICAL); + linearLayout.addView(emptyTextLayout); + layoutParams = (LinearLayout.LayoutParams) emptyTextLayout.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + emptyTextLayout.setLayoutParams(layoutParams); + emptyTextLayout.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + + emptyTextView = new TextView(context); + emptyTextView.setTextColor(0xff808080); + emptyTextView.setTextSize(20); + emptyTextView.setGravity(Gravity.CENTER); + emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts)); + emptyTextLayout.addView(emptyTextView); + layoutParams = (LinearLayout.LayoutParams) emptyTextView.getLayoutParams(); + layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT; + layoutParams.weight = 0.5f; + emptyTextView.setLayoutParams(layoutParams); + + FrameLayout frameLayout2 = new FrameLayout(context); + emptyTextLayout.addView(frameLayout2); + layoutParams = (LinearLayout.LayoutParams) frameLayout2.getLayoutParams(); + layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT; + layoutParams.weight = 0.5f; + frameLayout2.setLayoutParams(layoutParams); + + listView = new LetterSectionsListView(context); + listView.setEmptyView(emptyTextLayout); + listView.setVerticalScrollBarEnabled(false); + listView.setDivider(null); + listView.setDividerHeight(0); + listView.setFastScrollEnabled(true); + listView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY); + listView.setAdapter(listViewAdapter); + if (Build.VERSION.SDK_INT >= 11) { + listView.setFastScrollAlwaysVisible(true); + listView.setVerticalScrollbarPosition(LocaleController.isRTL ? ListView.SCROLLBAR_POSITION_LEFT : ListView.SCROLLBAR_POSITION_RIGHT); } + linearLayout.addView(listView); + layoutParams = (LinearLayout.LayoutParams) listView.getLayoutParams(); + layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT; + listView.setLayoutParams(layoutParams); + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, int i, long l) { + TLRPC.User user = null; + if (searching && searchWas) { + user = searchListViewAdapter.getItem(i); + } else { + int section = listViewAdapter.getSectionForPosition(i); + int row = listViewAdapter.getPositionInSectionForPosition(i); + if (row < 0 || section < 0) { + return; + } + user = (TLRPC.User) listViewAdapter.getItem(section, row); + } + if (user == null) { + return; + } + + boolean check = true; + if (selectedContacts.containsKey(user.id)) { + check = false; + try { + XImageSpan span = selectedContacts.get(user.id); + selectedContacts.remove(user.id); + SpannableStringBuilder text = new SpannableStringBuilder(userSelectEditText.getText()); + text.delete(text.getSpanStart(span), text.getSpanEnd(span)); + allSpans.remove(span); + ignoreChange = true; + userSelectEditText.setText(text); + userSelectEditText.setSelection(text.length()); + ignoreChange = false; + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } else { + if (selectedContacts.size() == maxCount) { + return; + } + ignoreChange = true; + XImageSpan span = createAndPutChipForUser(user); + span.uid = user.id; + ignoreChange = false; + } + if (!isAlwaysShare && !isNeverShare) { + actionBar.setSubtitle(LocaleController.formatString("MembersCount", R.string.MembersCount, selectedContacts.size(), maxCount)); + } + if (searching || searchWas) { + ignoreChange = true; + SpannableStringBuilder ssb = new SpannableStringBuilder(""); + for (ImageSpan sp : allSpans) { + ssb.append("<<"); + ssb.setSpan(sp, ssb.length() - 2, ssb.length(), SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE); + } + userSelectEditText.setText(ssb); + userSelectEditText.setSelection(ssb.length()); + ignoreChange = false; + + searchListViewAdapter.searchDialogs(null); + searching = false; + searchWas = false; + listView.setAdapter(listViewAdapter); + listViewAdapter.notifyDataSetChanged(); + if (android.os.Build.VERSION.SDK_INT >= 11) { + listView.setFastScrollAlwaysVisible(true); + } + listView.setFastScrollEnabled(true); + listView.setVerticalScrollBarEnabled(false); + emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts)); + } else { + if (view instanceof UserCell) { + ((UserCell) view).setChecked(check, true); + } + } + } + }); + listView.setOnScrollListener(new AbsListView.OnScrollListener() { + @Override + public void onScrollStateChanged(AbsListView absListView, int i) { + if (i == SCROLL_STATE_TOUCH_SCROLL) { + AndroidUtilities.hideKeyboard(userSelectEditText); + } + if (listViewAdapter != null) { + listViewAdapter.setIsScrolling(i != SCROLL_STATE_IDLE); + } + } + + @Override + public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + if (absListView.isFastScrollEnabled()) { + AndroidUtilities.clearDrawableAnimation(absListView); + } + } + }); + return fragmentView; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateFinalActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateFinalActivity.java index c5974180b..6436ef0ce 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateFinalActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateFinalActivity.java @@ -138,191 +138,185 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - if (isBroadcast) { - actionBar.setTitle(LocaleController.getString("NewBroadcastList", R.string.NewBroadcastList)); - } else { - actionBar.setTitle(LocaleController.getString("NewGroup", R.string.NewGroup)); - } + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setAllowOverlayTitle(true); + if (isBroadcast) { + actionBar.setTitle(LocaleController.getString("NewBroadcastList", R.string.NewBroadcastList)); + } else { + actionBar.setTitle(LocaleController.getString("NewGroup", R.string.NewGroup)); + } - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } else if (id == done_button) { - if (donePressed) { - return; - } - if (nameTextView.getText().length() == 0) { - return; - } - donePressed = true; + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); + } else if (id == done_button) { + if (donePressed) { + return; + } + if (nameTextView.getText().length() == 0) { + return; + } + donePressed = true; - if (isBroadcast) { - MessagesController.getInstance().createChat(nameTextView.getText().toString(), selectedContacts, uploadedAvatar, isBroadcast); + if (isBroadcast) { + MessagesController.getInstance().createChat(nameTextView.getText().toString(), selectedContacts, isBroadcast); + } else { + if (avatarUpdater.uploadingAvatar != null) { + createAfterUpload = true; } else { - if (avatarUpdater.uploadingAvatar != null) { - createAfterUpload = true; - } else { - progressDialog = new ProgressDialog(getParentActivity()); - progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading)); - progressDialog.setCanceledOnTouchOutside(false); - progressDialog.setCancelable(false); + progressDialog = new ProgressDialog(getParentActivity()); + progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading)); + progressDialog.setCanceledOnTouchOutside(false); + progressDialog.setCancelable(false); - final long reqId = MessagesController.getInstance().createChat(nameTextView.getText().toString(), selectedContacts, uploadedAvatar, isBroadcast); + final long reqId = MessagesController.getInstance().createChat(nameTextView.getText().toString(), selectedContacts, isBroadcast); - progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, LocaleController.getString("Cancel", R.string.Cancel), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - ConnectionsManager.getInstance().cancelRpc(reqId, true); - donePressed = false; - try { - dialog.dismiss(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } + progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, LocaleController.getString("Cancel", R.string.Cancel), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + ConnectionsManager.getInstance().cancelRpc(reqId, true); + donePressed = false; + try { + dialog.dismiss(); + } catch (Exception e) { + FileLog.e("tmessages", e); } - }); - progressDialog.show(); - } + } + }); + progressDialog.show(); } } } - }); + } + }); - ActionBarMenu menu = actionBar.createMenu(); - menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); + ActionBarMenu menu = actionBar.createMenu(); + menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); - fragmentView = new LinearLayout(getParentActivity()); - LinearLayout linearLayout = (LinearLayout) fragmentView; - linearLayout.setOrientation(LinearLayout.VERTICAL); + fragmentView = new LinearLayout(context); + LinearLayout linearLayout = (LinearLayout) fragmentView; + linearLayout.setOrientation(LinearLayout.VERTICAL); - FrameLayout frameLayout = new FrameLayoutFixed(getParentActivity()); - linearLayout.addView(frameLayout); - LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) frameLayout.getLayoutParams(); - layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT; - layoutParams.gravity = Gravity.TOP | Gravity.LEFT; - frameLayout.setLayoutParams(layoutParams); + FrameLayout frameLayout = new FrameLayoutFixed(context); + linearLayout.addView(frameLayout); + LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) frameLayout.getLayoutParams(); + layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams.gravity = Gravity.TOP | Gravity.LEFT; + frameLayout.setLayoutParams(layoutParams); - avatarImage = new BackupImageView(getParentActivity()); - avatarImage.imageReceiver.setRoundRadius(AndroidUtilities.dp(32)); - avatarDrawable.setInfo(5, null, null, isBroadcast); - avatarImage.setImageDrawable(avatarDrawable); - frameLayout.addView(avatarImage); - FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) avatarImage.getLayoutParams(); - layoutParams1.width = AndroidUtilities.dp(64); - layoutParams1.height = AndroidUtilities.dp(64); - layoutParams1.topMargin = AndroidUtilities.dp(12); - layoutParams1.bottomMargin = AndroidUtilities.dp(12); - layoutParams1.leftMargin = LocaleController.isRTL ? 0 : AndroidUtilities.dp(16); - layoutParams1.rightMargin = LocaleController.isRTL ? AndroidUtilities.dp(16) : 0; - layoutParams1.gravity = Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); - avatarImage.setLayoutParams(layoutParams1); - if (!isBroadcast) { - avatarDrawable.setDrawPhoto(true); - avatarImage.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + avatarImage = new BackupImageView(context); + avatarImage.setRoundRadius(AndroidUtilities.dp(32)); + avatarDrawable.setInfo(5, null, null, isBroadcast); + avatarImage.setImageDrawable(avatarDrawable); + frameLayout.addView(avatarImage); + FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) avatarImage.getLayoutParams(); + layoutParams1.width = AndroidUtilities.dp(64); + layoutParams1.height = AndroidUtilities.dp(64); + layoutParams1.topMargin = AndroidUtilities.dp(12); + layoutParams1.bottomMargin = AndroidUtilities.dp(12); + layoutParams1.leftMargin = LocaleController.isRTL ? 0 : AndroidUtilities.dp(16); + layoutParams1.rightMargin = LocaleController.isRTL ? AndroidUtilities.dp(16) : 0; + layoutParams1.gravity = Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); + avatarImage.setLayoutParams(layoutParams1); + if (!isBroadcast) { + avatarDrawable.setDrawPhoto(true); + avatarImage.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + if (getParentActivity() == null) { + return; + } + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - CharSequence[] items; + CharSequence[] items; - if (avatar != null) { - items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("DeletePhoto", R.string.DeletePhoto)}; - } else { - items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley)}; - } + if (avatar != null) { + items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("DeletePhoto", R.string.DeletePhoto)}; + } else { + items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley)}; + } - builder.setItems(items, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - if (i == 0) { - avatarUpdater.openCamera(); - } else if (i == 1) { - avatarUpdater.openGallery(); - } else if (i == 2) { - avatar = null; - uploadedAvatar = null; - avatarImage.setImage(avatar, "50_50", avatarDrawable); - } + builder.setItems(items, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + if (i == 0) { + avatarUpdater.openCamera(); + } else if (i == 1) { + avatarUpdater.openGallery(); + } else if (i == 2) { + avatar = null; + uploadedAvatar = null; + avatarImage.setImage(avatar, "50_50", avatarDrawable); } - }); - showAlertDialog(builder); - } - }); - } - - nameTextView = new EditText(getParentActivity()); - nameTextView.setHint(isBroadcast ? LocaleController.getString("EnterListName", R.string.EnterListName) : LocaleController.getString("EnterGroupNamePlaceholder", R.string.EnterGroupNamePlaceholder)); - if (nameToSet != null) { - nameTextView.setText(nameToSet); - nameToSet = null; - } - nameTextView.setMaxLines(4); - nameTextView.setGravity(Gravity.CENTER_VERTICAL | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); - nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - nameTextView.setHintTextColor(0xff979797); - nameTextView.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI); - nameTextView.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); - nameTextView.setPadding(0, 0, 0, AndroidUtilities.dp(8)); - AndroidUtilities.clearCursorDrawable(nameTextView); - nameTextView.setTextColor(0xff212121); - frameLayout.addView(nameTextView); - layoutParams1 = (FrameLayout.LayoutParams) nameTextView.getLayoutParams(); - layoutParams1.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams1.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams1.leftMargin = LocaleController.isRTL ? AndroidUtilities.dp(16) : AndroidUtilities.dp(96); - layoutParams1.rightMargin = LocaleController.isRTL ? AndroidUtilities.dp(96) : AndroidUtilities.dp(16); - layoutParams1.gravity = Gravity.CENTER_VERTICAL; - nameTextView.setLayoutParams(layoutParams1); - if (!isBroadcast) { - nameTextView.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - - } - - @Override - public void afterTextChanged(Editable s) { - avatarDrawable.setInfo(5, nameTextView.length() > 0 ? nameTextView.getText().toString() : null, null, isBroadcast); - avatarImage.invalidate(); - } - }); - } - - GreySectionCell sectionCell = new GreySectionCell(getParentActivity()); - sectionCell.setText(LocaleController.formatPluralString("Members", selectedContacts.size())); - linearLayout.addView(sectionCell); - - listView = new ListView(getParentActivity()); - listView.setDivider(null); - listView.setDividerHeight(0); - listView.setVerticalScrollBarEnabled(false); - listView.setAdapter(listAdapter = new ListAdapter(getParentActivity())); - linearLayout.addView(listView); - layoutParams = (LinearLayout.LayoutParams) listView.getLayoutParams(); - layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT; - listView.setLayoutParams(layoutParams); - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); - } + } + }); + showAlertDialog(builder); + } + }); } + + nameTextView = new EditText(context); + nameTextView.setHint(isBroadcast ? LocaleController.getString("EnterListName", R.string.EnterListName) : LocaleController.getString("EnterGroupNamePlaceholder", R.string.EnterGroupNamePlaceholder)); + if (nameToSet != null) { + nameTextView.setText(nameToSet); + nameToSet = null; + } + nameTextView.setMaxLines(4); + nameTextView.setGravity(Gravity.CENTER_VERTICAL | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); + nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); + nameTextView.setHintTextColor(0xff979797); + nameTextView.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI); + nameTextView.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); + nameTextView.setPadding(0, 0, 0, AndroidUtilities.dp(8)); + AndroidUtilities.clearCursorDrawable(nameTextView); + nameTextView.setTextColor(0xff212121); + frameLayout.addView(nameTextView); + layoutParams1 = (FrameLayout.LayoutParams) nameTextView.getLayoutParams(); + layoutParams1.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams1.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams1.leftMargin = LocaleController.isRTL ? AndroidUtilities.dp(16) : AndroidUtilities.dp(96); + layoutParams1.rightMargin = LocaleController.isRTL ? AndroidUtilities.dp(96) : AndroidUtilities.dp(16); + layoutParams1.gravity = Gravity.CENTER_VERTICAL; + nameTextView.setLayoutParams(layoutParams1); + if (!isBroadcast) { + nameTextView.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + + } + + @Override + public void afterTextChanged(Editable s) { + avatarDrawable.setInfo(5, nameTextView.length() > 0 ? nameTextView.getText().toString() : null, null, isBroadcast); + avatarImage.invalidate(); + } + }); + } + + GreySectionCell sectionCell = new GreySectionCell(context); + sectionCell.setText(LocaleController.formatPluralString("Members", selectedContacts.size())); + linearLayout.addView(sectionCell); + + listView = new ListView(context); + listView.setDivider(null); + listView.setDividerHeight(0); + listView.setVerticalScrollBarEnabled(false); + listView.setAdapter(listAdapter = new ListAdapter(context)); + linearLayout.addView(listView); + layoutParams = (LinearLayout.LayoutParams) listView.getLayoutParams(); + layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT; + listView.setLayoutParams(layoutParams); + return fragmentView; } @@ -336,7 +330,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati avatarImage.setImage(avatar, "50_50", avatarDrawable); if (createAfterUpload) { FileLog.e("tmessages", "avatar did uploaded"); - MessagesController.getInstance().createChat(nameTextView.getText().toString(), selectedContacts, uploadedAvatar, false); + MessagesController.getInstance().createChat(nameTextView.getText().toString(), selectedContacts, false); } } }); @@ -402,10 +396,14 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati FileLog.e("tmessages", e); } } + int chat_id = (Integer)args[0]; NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); Bundle args2 = new Bundle(); - args2.putInt("chat_id", (Integer)args[0]); + args2.putInt("chat_id", chat_id); presentFragment(new ChatActivity(args2), true); + if (uploadedAvatar != null) { + MessagesController.getInstance().changeChatAvatar(chat_id, uploadedAvatar); + } } }); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/IdenticonActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/IdenticonActivity.java index 88ae3a8b7..10181960b 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/IdenticonActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/IdenticonActivity.java @@ -10,18 +10,17 @@ package org.telegram.ui; import android.content.Context; import android.os.Bundle; -import android.text.Html; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.Surface; import android.view.View; -import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.WindowManager; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; +import org.telegram.android.AndroidUtilities; import org.telegram.android.LocaleController; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.TLRPC; @@ -45,45 +44,39 @@ public class IdenticonActivity extends BaseFragment { } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - actionBar.setTitle(LocaleController.getString("EncryptionKey", R.string.EncryptionKey)); + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setAllowOverlayTitle(true); + actionBar.setTitle(LocaleController.getString("EncryptionKey", R.string.EncryptionKey)); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); } - }); - - fragmentView = inflater.inflate(R.layout.identicon_layout, null, false); - ImageView identiconView = (ImageView) fragmentView.findViewById(R.id.identicon_view); - TextView textView = (TextView)fragmentView.findViewById(R.id.identicon_text); - TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance().getEncryptedChat(chat_id); - if (encryptedChat != null) { - IdenticonDrawable drawable = new IdenticonDrawable(); - identiconView.setImageDrawable(drawable); - drawable.setEncryptedChat(encryptedChat); - TLRPC.User user = MessagesController.getInstance().getUser(encryptedChat.user_id); - textView.setText(Html.fromHtml(LocaleController.formatString("EncryptionKeyDescription", R.string.EncryptionKeyDescription, user.first_name, user.first_name))); } + }); - fragmentView.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - return true; - } - }); - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); - } + fragmentView = inflater.inflate(R.layout.identicon_layout, null, false); + ImageView identiconView = (ImageView) fragmentView.findViewById(R.id.identicon_view); + TextView textView = (TextView) fragmentView.findViewById(R.id.identicon_text); + TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance().getEncryptedChat(chat_id); + if (encryptedChat != null) { + IdenticonDrawable drawable = new IdenticonDrawable(); + identiconView.setImageDrawable(drawable); + drawable.setEncryptedChat(encryptedChat); + TLRPC.User user = MessagesController.getInstance().getUser(encryptedChat.user_id); + textView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("EncryptionKeyDescription", R.string.EncryptionKeyDescription, user.first_name, user.first_name))); } + + fragmentView.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + return fragmentView; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/IntroActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/IntroActivity.java index 983d43cd9..2d3599521 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/IntroActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/IntroActivity.java @@ -19,7 +19,6 @@ import android.os.Bundle; import android.os.Parcelable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; -import android.text.Html; import android.view.View; import android.view.ViewGroup; import android.view.Window; @@ -255,7 +254,7 @@ public class IntroActivity extends Activity { container.addView(view, 0); headerTextView.setText(getString(titles[position])); - messageTextView.setText(Html.fromHtml(getString(messages[position]))); + messageTextView.setText(AndroidUtilities.replaceTags(getString(messages[position]))); return view; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LanguageSelectActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/LanguageSelectActivity.java index 0ff48eb81..a6efe56be 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LanguageSelectActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LanguageSelectActivity.java @@ -52,192 +52,186 @@ public class LanguageSelectActivity extends BaseFragment { public ArrayList searchResult; @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - searching = false; - searchWas = false; + public View createView(Context context, LayoutInflater inflater) { + searching = false; + searchWas = false; - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - actionBar.setTitle(LocaleController.getString("Language", R.string.Language)); + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setAllowOverlayTitle(true); + actionBar.setTitle(LocaleController.getString("Language", R.string.Language)); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } - } - }); - - ActionBarMenu menu = actionBar.createMenu(); - ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() { - @Override - public void onSearchExpand() { - searching = true; - } - - @Override - public boolean onSearchCollapse() { - search(null); - searching = false; - searchWas = false; - if (listView != null) { - emptyTextView.setVisibility(View.GONE); - listView.setAdapter(listAdapter); - } - - return true; - } - - @Override - public void onTextChanged(EditText editText) { - String text = editText.getText().toString(); - search(text); - if (text.length() != 0) { - searchWas = true; - if (listView != null) { - listView.setAdapter(searchListViewAdapter); - } - } - } - }); - item.getSearchField().setHint(LocaleController.getString("Search", R.string.Search)); - - listAdapter = new ListAdapter(getParentActivity()); - searchListViewAdapter = new SearchAdapter(getParentActivity()); - - fragmentView = new FrameLayout(getParentActivity()); - - LinearLayout emptyTextLayout = new LinearLayout(getParentActivity()); - emptyTextLayout.setVisibility(View.INVISIBLE); - emptyTextLayout.setOrientation(LinearLayout.VERTICAL); - ((FrameLayout) fragmentView).addView(emptyTextLayout); - FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) emptyTextLayout.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.gravity = Gravity.TOP; - emptyTextLayout.setLayoutParams(layoutParams); - emptyTextLayout.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - return true; - } - }); - - emptyTextView = new TextView(getParentActivity()); - emptyTextView.setTextColor(0xff808080); - emptyTextView.setTextSize(20); - emptyTextView.setGravity(Gravity.CENTER); - emptyTextView.setText(LocaleController.getString("NoResult", R.string.NoResult)); - emptyTextLayout.addView(emptyTextView); - LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) emptyTextView.getLayoutParams(); - layoutParams1.width = LinearLayout.LayoutParams.MATCH_PARENT; - layoutParams1.height = LinearLayout.LayoutParams.MATCH_PARENT; - layoutParams1.weight = 0.5f; - emptyTextView.setLayoutParams(layoutParams1); - - FrameLayout frameLayout = new FrameLayout(getParentActivity()); - emptyTextLayout.addView(frameLayout); - layoutParams1 = (LinearLayout.LayoutParams) frameLayout.getLayoutParams(); - layoutParams1.width = LinearLayout.LayoutParams.MATCH_PARENT; - layoutParams1.height = LinearLayout.LayoutParams.MATCH_PARENT; - layoutParams1.weight = 0.5f; - frameLayout.setLayoutParams(layoutParams1); - - listView = new ListView(getParentActivity()); - listView.setEmptyView(emptyTextLayout); - listView.setVerticalScrollBarEnabled(false); - listView.setDivider(null); - listView.setDividerHeight(0); - listView.setAdapter(listAdapter); - ((FrameLayout) fragmentView).addView(listView); - layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - listView.setLayoutParams(layoutParams); - - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, int i, long l) { - LocaleController.LocaleInfo localeInfo = null; - if (searching && searchWas) { - if (i >= 0 && i < searchResult.size()) { - localeInfo = searchResult.get(i); - } - } else { - if (i >= 0 && i < LocaleController.getInstance().sortedLanguages.size()) { - localeInfo = LocaleController.getInstance().sortedLanguages.get(i); - } - } - if (localeInfo != null) { - LocaleController.getInstance().applyLanguage(localeInfo, true); - parentLayout.rebuildAllFragmentViews(false); - } + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { finishFragment(); } - }); + } + }); - listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { - @Override - public boolean onItemLongClick(AdapterView adapterView, View view, int i, long l) { - LocaleController.LocaleInfo localeInfo = null; - if (searching && searchWas) { - if (i >= 0 && i < searchResult.size()) { - localeInfo = searchResult.get(i); - } - } else { - if (i >= 0 && i < LocaleController.getInstance().sortedLanguages.size()) { - localeInfo = LocaleController.getInstance().sortedLanguages.get(i); - } + ActionBarMenu menu = actionBar.createMenu(); + ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() { + @Override + public void onSearchExpand() { + searching = true; + } + + @Override + public boolean onSearchCollapse() { + search(null); + searching = false; + searchWas = false; + if (listView != null) { + emptyTextView.setVisibility(View.GONE); + listView.setAdapter(listAdapter); + } + + return true; + } + + @Override + public void onTextChanged(EditText editText) { + String text = editText.getText().toString(); + search(text); + if (text.length() != 0) { + searchWas = true; + if (listView != null) { + listView.setAdapter(searchListViewAdapter); } - if (localeInfo == null || localeInfo.pathToFile == null || getParentActivity() == null) { - return false; + } + } + }); + item.getSearchField().setHint(LocaleController.getString("Search", R.string.Search)); + + listAdapter = new ListAdapter(context); + searchListViewAdapter = new SearchAdapter(context); + + fragmentView = new FrameLayout(context); + + LinearLayout emptyTextLayout = new LinearLayout(context); + emptyTextLayout.setVisibility(View.INVISIBLE); + emptyTextLayout.setOrientation(LinearLayout.VERTICAL); + ((FrameLayout) fragmentView).addView(emptyTextLayout); + FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) emptyTextLayout.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.gravity = Gravity.TOP; + emptyTextLayout.setLayoutParams(layoutParams); + emptyTextLayout.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + + emptyTextView = new TextView(context); + emptyTextView.setTextColor(0xff808080); + emptyTextView.setTextSize(20); + emptyTextView.setGravity(Gravity.CENTER); + emptyTextView.setText(LocaleController.getString("NoResult", R.string.NoResult)); + emptyTextLayout.addView(emptyTextView); + LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) emptyTextView.getLayoutParams(); + layoutParams1.width = LinearLayout.LayoutParams.MATCH_PARENT; + layoutParams1.height = LinearLayout.LayoutParams.MATCH_PARENT; + layoutParams1.weight = 0.5f; + emptyTextView.setLayoutParams(layoutParams1); + + FrameLayout frameLayout = new FrameLayout(context); + emptyTextLayout.addView(frameLayout); + layoutParams1 = (LinearLayout.LayoutParams) frameLayout.getLayoutParams(); + layoutParams1.width = LinearLayout.LayoutParams.MATCH_PARENT; + layoutParams1.height = LinearLayout.LayoutParams.MATCH_PARENT; + layoutParams1.weight = 0.5f; + frameLayout.setLayoutParams(layoutParams1); + + listView = new ListView(context); + listView.setEmptyView(emptyTextLayout); + listView.setVerticalScrollBarEnabled(false); + listView.setDivider(null); + listView.setDividerHeight(0); + listView.setAdapter(listAdapter); + ((FrameLayout) fragmentView).addView(listView); + layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + listView.setLayoutParams(layoutParams); + + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, int i, long l) { + LocaleController.LocaleInfo localeInfo = null; + if (searching && searchWas) { + if (i >= 0 && i < searchResult.size()) { + localeInfo = searchResult.get(i); } - final LocaleController.LocaleInfo finalLocaleInfo = localeInfo; - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setMessage(LocaleController.getString("DeleteLocalization", R.string.DeleteLocalization)); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setPositiveButton(LocaleController.getString("Delete", R.string.Delete), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - if (LocaleController.getInstance().deleteLanguage(finalLocaleInfo)) { - if (searchResult != null) { - searchResult.remove(finalLocaleInfo); - } - if (listAdapter != null) { - listAdapter.notifyDataSetChanged(); - } - if (searchListViewAdapter != null) { - searchListViewAdapter.notifyDataSetChanged(); - } + } else { + if (i >= 0 && i < LocaleController.getInstance().sortedLanguages.size()) { + localeInfo = LocaleController.getInstance().sortedLanguages.get(i); + } + } + if (localeInfo != null) { + LocaleController.getInstance().applyLanguage(localeInfo, true); + parentLayout.rebuildAllFragmentViews(false); + } + finishFragment(); + } + }); + + listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { + @Override + public boolean onItemLongClick(AdapterView adapterView, View view, int i, long l) { + LocaleController.LocaleInfo localeInfo = null; + if (searching && searchWas) { + if (i >= 0 && i < searchResult.size()) { + localeInfo = searchResult.get(i); + } + } else { + if (i >= 0 && i < LocaleController.getInstance().sortedLanguages.size()) { + localeInfo = LocaleController.getInstance().sortedLanguages.get(i); + } + } + if (localeInfo == null || localeInfo.pathToFile == null || getParentActivity() == null) { + return false; + } + final LocaleController.LocaleInfo finalLocaleInfo = localeInfo; + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setMessage(LocaleController.getString("DeleteLocalization", R.string.DeleteLocalization)); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + builder.setPositiveButton(LocaleController.getString("Delete", R.string.Delete), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + if (LocaleController.getInstance().deleteLanguage(finalLocaleInfo)) { + if (searchResult != null) { + searchResult.remove(finalLocaleInfo); + } + if (listAdapter != null) { + listAdapter.notifyDataSetChanged(); + } + if (searchListViewAdapter != null) { + searchListViewAdapter.notifyDataSetChanged(); } } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - return true; - } - }); - - listView.setOnScrollListener(new AbsListView.OnScrollListener() { - @Override - public void onScrollStateChanged(AbsListView absListView, int i) { - if (i == SCROLL_STATE_TOUCH_SCROLL && searching && searchWas) { - AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus()); } - } - - @Override - public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - } - }); - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + return true; } - } + }); + + listView.setOnScrollListener(new AbsListView.OnScrollListener() { + @Override + public void onScrollStateChanged(AbsListView absListView, int i) { + if (i == SCROLL_STATE_TOUCH_SCROLL && searching && searchWas) { + AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus()); + } + } + + @Override + public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + } + }); + return fragmentView; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LastSeenActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/LastSeenActivity.java index 79cd7c00f..b2c6096be 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LastSeenActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LastSeenActivity.java @@ -99,150 +99,144 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - actionBar.setTitle(LocaleController.getString("PrivacyLastSeen", R.string.PrivacyLastSeen)); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } else if (id == done_button) { - if (getParentActivity() == null) { - return; - } - - if (currentType != 0) { - final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); - boolean showed = preferences.getBoolean("privacyAlertShowed", false); - if (!showed) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setMessage(LocaleController.getString("CustomHelp", R.string.CustomHelp)); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - applyCurrentPrivacySettings(); - preferences.edit().putBoolean("privacyAlertShowed", true).commit(); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - return; - } - } - applyCurrentPrivacySettings(); + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setAllowOverlayTitle(true); + actionBar.setTitle(LocaleController.getString("PrivacyLastSeen", R.string.PrivacyLastSeen)); + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); + } else if (id == done_button) { + if (getParentActivity() == null) { + return; } - } - }); - ActionBarMenu menu = actionBar.createMenu(); - doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); - doneButton.setVisibility(View.GONE); - - listAdapter = new ListAdapter(getParentActivity()); - - fragmentView = new FrameLayout(getParentActivity()); - FrameLayout frameLayout = (FrameLayout) fragmentView; - frameLayout.setBackgroundColor(0xfff0f0f0); - - ListView listView = new ListView(getParentActivity()); - listView.setDivider(null); - listView.setDividerHeight(0); - listView.setVerticalScrollBarEnabled(false); - listView.setDrawSelectorOnTop(true); - frameLayout.addView(listView); - FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.gravity = Gravity.TOP; - listView.setLayoutParams(layoutParams); - listView.setAdapter(listAdapter); - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, final int i, long l) { - if (i == nobodyRow || i == everybodyRow || i == myContactsRow) { - int newType = currentType; - if (i == nobodyRow) { - newType = 1; - } else if (i == everybodyRow) { - newType = 0; - } else if (i == myContactsRow) { - newType = 2; - } - if (newType == currentType) { + if (currentType != 0) { + final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); + boolean showed = preferences.getBoolean("privacyAlertShowed", false); + if (!showed) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setMessage(LocaleController.getString("CustomHelp", R.string.CustomHelp)); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + applyCurrentPrivacySettings(); + preferences.edit().putBoolean("privacyAlertShowed", true).commit(); + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); return; } - doneButton.setVisibility(View.VISIBLE); - currentType = newType; - updateRows(); - } else if (i == neverShareRow || i == alwaysShareRow) { - ArrayList createFromArray = null; - if (i == neverShareRow) { - createFromArray = currentMinus; - } else { - createFromArray = currentPlus; - } - if (createFromArray.isEmpty()) { - Bundle args = new Bundle(); - args.putBoolean(i == neverShareRow ? "isNeverShare" : "isAlwaysShare", true); - GroupCreateActivity fragment = new GroupCreateActivity(args); - fragment.setDelegate(new GroupCreateActivity.GroupCreateActivityDelegate() { - @Override - public void didSelectUsers(ArrayList ids) { - if (i == neverShareRow) { - currentMinus = ids; + } + applyCurrentPrivacySettings(); + } + } + }); + + ActionBarMenu menu = actionBar.createMenu(); + doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); + doneButton.setVisibility(View.GONE); + + listAdapter = new ListAdapter(context); + + fragmentView = new FrameLayout(context); + FrameLayout frameLayout = (FrameLayout) fragmentView; + frameLayout.setBackgroundColor(0xfff0f0f0); + + ListView listView = new ListView(context); + listView.setDivider(null); + listView.setDividerHeight(0); + listView.setVerticalScrollBarEnabled(false); + listView.setDrawSelectorOnTop(true); + frameLayout.addView(listView); + FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.gravity = Gravity.TOP; + listView.setLayoutParams(layoutParams); + listView.setAdapter(listAdapter); + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, final int i, long l) { + if (i == nobodyRow || i == everybodyRow || i == myContactsRow) { + int newType = currentType; + if (i == nobodyRow) { + newType = 1; + } else if (i == everybodyRow) { + newType = 0; + } else if (i == myContactsRow) { + newType = 2; + } + if (newType == currentType) { + return; + } + doneButton.setVisibility(View.VISIBLE); + currentType = newType; + updateRows(); + } else if (i == neverShareRow || i == alwaysShareRow) { + ArrayList createFromArray = null; + if (i == neverShareRow) { + createFromArray = currentMinus; + } else { + createFromArray = currentPlus; + } + if (createFromArray.isEmpty()) { + Bundle args = new Bundle(); + args.putBoolean(i == neverShareRow ? "isNeverShare" : "isAlwaysShare", true); + GroupCreateActivity fragment = new GroupCreateActivity(args); + fragment.setDelegate(new GroupCreateActivity.GroupCreateActivityDelegate() { + @Override + public void didSelectUsers(ArrayList ids) { + if (i == neverShareRow) { + currentMinus = ids; + for (Integer id : currentMinus) { + currentPlus.remove(id); + } + } else { + currentPlus = ids; + for (Integer id : currentPlus) { + currentMinus.remove(id); + } + } + doneButton.setVisibility(View.VISIBLE); + listAdapter.notifyDataSetChanged(); + } + }); + presentFragment(fragment); + } else { + LastSeenUsersActivity fragment = new LastSeenUsersActivity(createFromArray, i == alwaysShareRow); + fragment.setDelegate(new LastSeenUsersActivity.LastSeenUsersActivityDelegate() { + @Override + public void didUpdatedUserList(ArrayList ids, boolean added) { + if (i == neverShareRow) { + currentMinus = ids; + if (added) { for (Integer id : currentMinus) { currentPlus.remove(id); } - } else { - currentPlus = ids; + } + } else { + currentPlus = ids; + if (added) { for (Integer id : currentPlus) { currentMinus.remove(id); } } - doneButton.setVisibility(View.VISIBLE); - listAdapter.notifyDataSetChanged(); } - }); - presentFragment(fragment); - } else { - LastSeenUsersActivity fragment = new LastSeenUsersActivity(createFromArray, i == alwaysShareRow); - fragment.setDelegate(new LastSeenUsersActivity.LastSeenUsersActivityDelegate() { - @Override - public void didUpdatedUserList(ArrayList ids, boolean added) { - if (i == neverShareRow) { - currentMinus = ids; - if (added) { - for (Integer id : currentMinus) { - currentPlus.remove(id); - } - } - } else { - currentPlus = ids; - if (added) { - for (Integer id : currentPlus) { - currentMinus.remove(id); - } - } - } - doneButton.setVisibility(View.VISIBLE); - listAdapter.notifyDataSetChanged(); - } - }); - presentFragment(fragment); - } + doneButton.setVisibility(View.VISIBLE); + listAdapter.notifyDataSetChanged(); + } + }); + presentFragment(fragment); } } - }); - } else { - ViewGroup parent = (ViewGroup) fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); } - } + }); + return fragmentView; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LastSeenUsersActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/LastSeenUsersActivity.java index db8badfc5..a0ce4a77e 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LastSeenUsersActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LastSeenUsersActivity.java @@ -75,127 +75,121 @@ public class LastSeenUsersActivity extends BaseFragment implements NotificationC } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - if (isAlwaysShare) { - actionBar.setTitle(LocaleController.getString("AlwaysShareWithTitle", R.string.AlwaysShareWithTitle)); - } else { - actionBar.setTitle(LocaleController.getString("NeverShareWithTitle", R.string.NeverShareWithTitle)); - } - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } else if (id == block_user) { - Bundle args = new Bundle(); - args.putBoolean(isAlwaysShare ? "isAlwaysShare" : "isNeverShare", true); - GroupCreateActivity fragment = new GroupCreateActivity(args); - fragment.setDelegate(new GroupCreateActivity.GroupCreateActivityDelegate() { - @Override - public void didSelectUsers(ArrayList ids) { - for (Integer id : ids) { - if (uidArray.contains(id)) { - continue; - } - uidArray.add(id); - } - listViewAdapter.notifyDataSetChanged(); - if (delegate != null) { - delegate.didUpdatedUserList(uidArray, true); - } - } - }); - presentFragment(fragment); - } - } - }); - - ActionBarMenu menu = actionBar.createMenu(); - menu.addItem(block_user, R.drawable.plus); - - fragmentView = new FrameLayout(getParentActivity()); - FrameLayout frameLayout = (FrameLayout) fragmentView; - - TextView emptyTextView = new TextView(getParentActivity()); - emptyTextView.setTextColor(0xff808080); - emptyTextView.setTextSize(20); - emptyTextView.setGravity(Gravity.CENTER); - emptyTextView.setVisibility(View.INVISIBLE); - emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts)); - frameLayout.addView(emptyTextView); - FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) emptyTextView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.gravity = Gravity.TOP; - emptyTextView.setLayoutParams(layoutParams); - emptyTextView.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - return true; - } - }); - - listView = new ListView(getParentActivity()); - listView.setEmptyView(emptyTextView); - listView.setVerticalScrollBarEnabled(false); - listView.setDivider(null); - listView.setDividerHeight(0); - listView.setAdapter(listViewAdapter = new ListAdapter(getParentActivity())); - if (Build.VERSION.SDK_INT >= 11) { - listView.setVerticalScrollbarPosition(LocaleController.isRTL ? ListView.SCROLLBAR_POSITION_LEFT : ListView.SCROLLBAR_POSITION_RIGHT); - } - frameLayout.addView(listView); - layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - listView.setLayoutParams(layoutParams); - - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, int i, long l) { - if (i < uidArray.size()) { - Bundle args = new Bundle(); - args.putInt("user_id", uidArray.get(i)); - presentFragment(new ProfileActivity(args)); - } - } - }); - - listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { - @Override - public boolean onItemLongClick(AdapterView adapterView, View view, int i, long l) { - if (i < 0 || i >= uidArray.size() || getParentActivity() == null) { - return true; - } - selectedUserId = uidArray.get(i); - - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - CharSequence[] items = new CharSequence[] {LocaleController.getString("Delete", R.string.Delete)}; - builder.setItems(items, new DialogInterface.OnClickListener() { + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setAllowOverlayTitle(true); + if (isAlwaysShare) { + actionBar.setTitle(LocaleController.getString("AlwaysShareWithTitle", R.string.AlwaysShareWithTitle)); + } else { + actionBar.setTitle(LocaleController.getString("NeverShareWithTitle", R.string.NeverShareWithTitle)); + } + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); + } else if (id == block_user) { + Bundle args = new Bundle(); + args.putBoolean(isAlwaysShare ? "isAlwaysShare" : "isNeverShare", true); + GroupCreateActivity fragment = new GroupCreateActivity(args); + fragment.setDelegate(new GroupCreateActivity.GroupCreateActivityDelegate() { @Override - public void onClick(DialogInterface dialogInterface, int i) { - if (i == 0) { - uidArray.remove((Integer)selectedUserId); - listViewAdapter.notifyDataSetChanged(); - if (delegate != null) { - delegate.didUpdatedUserList(uidArray, false); + public void didSelectUsers(ArrayList ids) { + for (Integer id : ids) { + if (uidArray.contains(id)) { + continue; } + uidArray.add(id); + } + listViewAdapter.notifyDataSetChanged(); + if (delegate != null) { + delegate.didUpdatedUserList(uidArray, true); } } }); - showAlertDialog(builder); + presentFragment(fragment); + } + } + }); + + ActionBarMenu menu = actionBar.createMenu(); + menu.addItem(block_user, R.drawable.plus); + + fragmentView = new FrameLayout(context); + FrameLayout frameLayout = (FrameLayout) fragmentView; + + TextView emptyTextView = new TextView(context); + emptyTextView.setTextColor(0xff808080); + emptyTextView.setTextSize(20); + emptyTextView.setGravity(Gravity.CENTER); + emptyTextView.setVisibility(View.INVISIBLE); + emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts)); + frameLayout.addView(emptyTextView); + FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) emptyTextView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.gravity = Gravity.TOP; + emptyTextView.setLayoutParams(layoutParams); + emptyTextView.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + + listView = new ListView(context); + listView.setEmptyView(emptyTextView); + listView.setVerticalScrollBarEnabled(false); + listView.setDivider(null); + listView.setDividerHeight(0); + listView.setAdapter(listViewAdapter = new ListAdapter(context)); + if (Build.VERSION.SDK_INT >= 11) { + listView.setVerticalScrollbarPosition(LocaleController.isRTL ? ListView.SCROLLBAR_POSITION_LEFT : ListView.SCROLLBAR_POSITION_RIGHT); + } + frameLayout.addView(listView); + layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + listView.setLayoutParams(layoutParams); + + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, int i, long l) { + if (i < uidArray.size()) { + Bundle args = new Bundle(); + args.putInt("user_id", uidArray.get(i)); + presentFragment(new ProfileActivity(args)); + } + } + }); + + listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { + @Override + public boolean onItemLongClick(AdapterView adapterView, View view, int i, long l) { + if (i < 0 || i >= uidArray.size() || getParentActivity() == null) { return true; } - }); - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); + selectedUserId = uidArray.get(i); + + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + CharSequence[] items = new CharSequence[]{LocaleController.getString("Delete", R.string.Delete)}; + builder.setItems(items, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + if (i == 0) { + uidArray.remove((Integer) selectedUserId); + listViewAdapter.notifyDataSetChanged(); + if (delegate != null) { + delegate.didUpdatedUserList(uidArray, false); + } + } + } + }); + showAlertDialog(builder); + return true; } - } + }); + return fragmentView; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java index ce359b74f..e75d44830 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java @@ -104,7 +104,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa protected void onCreate(Bundle savedInstanceState) { ApplicationLoader.postInitApplication(); - if (!UserConfig.isClientActivated() && !UserConfig.isWaitingForPasswordEnter()) { + if (!UserConfig.isClientActivated()) { Intent intent = getIntent(); if (intent != null && intent.getAction() != null && (Intent.ACTION_SEND.equals(intent.getAction()) || intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE))) { super.onCreate(savedInstanceState); @@ -205,7 +205,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa int viewX = location[0]; int viewY = location[1]; - if (x > viewX && x < viewX + layersActionBarLayout.getWidth() && y > viewY && y < viewY + layersActionBarLayout.getHeight()) { + if (layersActionBarLayout.checkTransitionAnimation() || x > viewX && x < viewX + layersActionBarLayout.getWidth() && y > viewY && y < viewY + layersActionBarLayout.getHeight()) { return false; } else { if (!layersActionBarLayout.fragmentsStack.isEmpty()) { @@ -335,7 +335,6 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa NotificationCenter.getInstance().addObserver(this, NotificationCenter.mainUserInfoChanged); NotificationCenter.getInstance().addObserver(this, NotificationCenter.closeOtherAppActivities); NotificationCenter.getInstance().addObserver(this, NotificationCenter.didUpdatedConnectionState); - NotificationCenter.getInstance().addObserver(this, NotificationCenter.needPasswordEnter); if (Build.VERSION.SDK_INT < 14) { NotificationCenter.getInstance().addObserver(this, NotificationCenter.screenStateChanged); } else { @@ -343,17 +342,12 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } if (actionBarLayout.fragmentsStack.isEmpty()) { - if (!UserConfig.isClientActivated() && !UserConfig.isWaitingForPasswordEnter()) { + if (!UserConfig.isClientActivated()) { actionBarLayout.addFragmentToStack(new LoginActivity()); drawerLayoutContainer.setAllowOpenDrawer(false, false); } else { - if (UserConfig.isWaitingForPasswordEnter()) { - actionBarLayout.addFragmentToStack(new AccountPasswordActivity(1)); - drawerLayoutContainer.setAllowOpenDrawer(false, false); - } else { - actionBarLayout.addFragmentToStack(new MessagesActivity(null)); - drawerLayoutContainer.setAllowOpenDrawer(true, false); - } + actionBarLayout.addFragmentToStack(new MessagesActivity(null)); + drawerLayoutContainer.setAllowOpenDrawer(true, false); } try { @@ -411,7 +405,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } else { allowOpen = actionBarLayout.fragmentsStack.size() <= 1; } - if (actionBarLayout.fragmentsStack.size() == 1 && (actionBarLayout.fragmentsStack.get(0) instanceof LoginActivity || actionBarLayout.fragmentsStack.get(0) instanceof AccountPasswordActivity)) { + if (actionBarLayout.fragmentsStack.size() == 1 && actionBarLayout.fragmentsStack.get(0) instanceof LoginActivity) { allowOpen = false; } drawerLayoutContainer.setAllowOpenDrawer(allowOpen, false); @@ -476,7 +470,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa documentsUrisArray = null; contactsToSend = null; - if (UserConfig.isClientActivated() && !UserConfig.isWaitingForPasswordEnter() && (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) { + if (UserConfig.isClientActivated() && (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) { if (intent != null && intent.getAction() != null && !restore) { if (Intent.ACTION_SEND.equals(intent.getAction())) { boolean error = false; @@ -864,35 +858,25 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa if (!pushOpened && !isNew) { if (AndroidUtilities.isTablet()) { - if (!UserConfig.isClientActivated() && !UserConfig.isWaitingForPasswordEnter()) { + if (!UserConfig.isClientActivated()) { if (layersActionBarLayout.fragmentsStack.isEmpty()) { layersActionBarLayout.addFragmentToStack(new LoginActivity()); drawerLayoutContainer.setAllowOpenDrawer(false, false); } } else { if (actionBarLayout.fragmentsStack.isEmpty()) { - if (UserConfig.isWaitingForPasswordEnter()) { - layersActionBarLayout.addFragmentToStack(new AccountPasswordActivity(1)); - drawerLayoutContainer.setAllowOpenDrawer(false, false); - } else { - actionBarLayout.addFragmentToStack(new MessagesActivity(null)); - drawerLayoutContainer.setAllowOpenDrawer(true, false); - } + actionBarLayout.addFragmentToStack(new MessagesActivity(null)); + drawerLayoutContainer.setAllowOpenDrawer(true, false); } } } else { if (actionBarLayout.fragmentsStack.isEmpty()) { - if (!UserConfig.isClientActivated() && !UserConfig.isWaitingForPasswordEnter()) { + if (!UserConfig.isClientActivated()) { actionBarLayout.addFragmentToStack(new LoginActivity()); drawerLayoutContainer.setAllowOpenDrawer(false, false); } else { - if (UserConfig.isWaitingForPasswordEnter()) { - actionBarLayout.addFragmentToStack(new AccountPasswordActivity(1)); - drawerLayoutContainer.setAllowOpenDrawer(false, false); - } else { - actionBarLayout.addFragmentToStack(new MessagesActivity(null)); - drawerLayoutContainer.setAllowOpenDrawer(true, false); - } + actionBarLayout.addFragmentToStack(new MessagesActivity(null)); + drawerLayoutContainer.setAllowOpenDrawer(true, false); } } } @@ -1001,7 +985,6 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa NotificationCenter.getInstance().removeObserver(this, NotificationCenter.mainUserInfoChanged); NotificationCenter.getInstance().removeObserver(this, NotificationCenter.closeOtherAppActivities); NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didUpdatedConnectionState); - NotificationCenter.getInstance().removeObserver(this, NotificationCenter.needPasswordEnter); if (Build.VERSION.SDK_INT < 14) { NotificationCenter.getInstance().removeObserver(this, NotificationCenter.screenStateChanged); } else { @@ -1218,28 +1201,6 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } } else if (id == NotificationCenter.mainUserInfoChanged) { drawerLayoutAdapter.notifyDataSetChanged(); - } else if (id == NotificationCenter.needPasswordEnter) { - if (AndroidUtilities.isTablet()) { - for (int a = 0; a < layersActionBarLayout.fragmentsStack.size() - 1; a++) { - layersActionBarLayout.removeFragmentFromStack(layersActionBarLayout.fragmentsStack.get(0)); - a--; - } - for (int a = 0; a < actionBarLayout.fragmentsStack.size() - 1; a++) { - actionBarLayout.removeFragmentFromStack(actionBarLayout.fragmentsStack.get(0)); - a--; - } - rightActionBarLayout.closeLastFragment(false); - actionBarLayout.closeLastFragment(false); - layersActionBarLayout.presentFragment(new AccountPasswordActivity(1), false, true, true); - drawerLayoutContainer.setAllowOpenDrawer(false, false); - } else { - for (int a = 0; a < actionBarLayout.fragmentsStack.size() - 1; a++) { - actionBarLayout.removeFragmentFromStack(actionBarLayout.fragmentsStack.get(0)); - a--; - } - actionBarLayout.presentFragment(new AccountPasswordActivity(1), true); - drawerLayoutContainer.setAllowOpenDrawer(false, false); - } } else if (id == NotificationCenter.screenStateChanged) { if (!ApplicationLoader.mainInterfacePaused) { if (!ApplicationLoader.isScreenOn) { @@ -1452,7 +1413,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa @Override public boolean needPresentFragment(BaseFragment fragment, boolean removeLast, boolean forceWithoutAnimation, ActionBarLayout layout) { if (AndroidUtilities.isTablet()) { - drawerLayoutContainer.setAllowOpenDrawer(!(fragment instanceof AccountPasswordActivity) && !(fragment instanceof LoginActivity) && layersActionBarLayout.getVisibility() != View.VISIBLE, true); + drawerLayoutContainer.setAllowOpenDrawer(!(fragment instanceof LoginActivity) && layersActionBarLayout.getVisibility() != View.VISIBLE, true); if (fragment instanceof MessagesActivity) { MessagesActivity messagesActivity = (MessagesActivity)fragment; if (messagesActivity.isMainDialogList() && layout != actionBarLayout) { @@ -1521,7 +1482,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } else if (layout != layersActionBarLayout) { layersActionBarLayout.setVisibility(View.VISIBLE); drawerLayoutContainer.setAllowOpenDrawer(false, true); - if (fragment instanceof LoginActivity || fragment instanceof AccountPasswordActivity) { + if (fragment instanceof LoginActivity) { backgroundTablet.setVisibility(View.VISIBLE); shadowTabletSide.setVisibility(View.GONE); shadowTablet.setBackgroundColor(0x00000000); @@ -1533,7 +1494,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } return true; } else { - drawerLayoutContainer.setAllowOpenDrawer(!(fragment instanceof LoginActivity) && !(fragment instanceof AccountPasswordActivity), false); + drawerLayoutContainer.setAllowOpenDrawer(!(fragment instanceof LoginActivity), false); return true; } } @@ -1541,7 +1502,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa @Override public boolean needAddFragmentToStack(BaseFragment fragment, ActionBarLayout layout) { if (AndroidUtilities.isTablet()) { - drawerLayoutContainer.setAllowOpenDrawer(!(fragment instanceof LoginActivity) && !(fragment instanceof AccountPasswordActivity) && layersActionBarLayout.getVisibility() != View.VISIBLE, true); + drawerLayoutContainer.setAllowOpenDrawer(!(fragment instanceof LoginActivity) && layersActionBarLayout.getVisibility() != View.VISIBLE, true); if (fragment instanceof MessagesActivity) { MessagesActivity messagesActivity = (MessagesActivity)fragment; if (messagesActivity.isMainDialogList() && layout != actionBarLayout) { @@ -1586,7 +1547,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } else if (layout != layersActionBarLayout) { layersActionBarLayout.setVisibility(View.VISIBLE); drawerLayoutContainer.setAllowOpenDrawer(false, true); - if (fragment instanceof LoginActivity || fragment instanceof AccountPasswordActivity) { + if (fragment instanceof LoginActivity) { backgroundTablet.setVisibility(View.VISIBLE); shadowTabletSide.setVisibility(View.GONE); shadowTablet.setBackgroundColor(0x00000000); @@ -1598,7 +1559,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } return true; } else { - drawerLayoutContainer.setAllowOpenDrawer(!(fragment instanceof LoginActivity) && !(fragment instanceof AccountPasswordActivity), false); + drawerLayoutContainer.setAllowOpenDrawer(!(fragment instanceof LoginActivity), false); return true; } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LocationActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/LocationActivity.java index e9c476fee..86e4b1cab 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LocationActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LocationActivity.java @@ -13,7 +13,6 @@ import android.location.Location; import android.location.LocationManager; import android.view.LayoutInflater; import android.view.View; -import android.view.ViewGroup; import android.widget.TextView; import com.google.android.gms.maps.CameraUpdate; @@ -47,6 +46,7 @@ import org.telegram.ui.ActionBar.BaseFragment; import java.util.List; public class LocationActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate { + private GoogleMap googleMap; private TextView distanceTextView; private Marker userMarker; @@ -88,170 +88,159 @@ public class LocationActivity extends BaseFragment implements NotificationCenter if (mapView != null) { mapView.onDestroy(); } - if (avatarImageView != null) { - avatarImageView.setImageDrawable(null); - } } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - if (messageObject != null) { - actionBar.setTitle(LocaleController.getString("ChatLocation", R.string.ChatLocation)); - } else { - actionBar.setTitle(LocaleController.getString("ShareLocation", R.string.ShareLocation)); - } + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setAllowOverlayTitle(true); + if (messageObject != null) { + actionBar.setTitle(LocaleController.getString("ChatLocation", R.string.ChatLocation)); + } else { + actionBar.setTitle(LocaleController.getString("ShareLocation", R.string.ShareLocation)); + } - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } else if (id == map_list_menu_map) { + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); + } else if (id == map_list_menu_map) { + if (googleMap != null) { + googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); + } + } else if (id == map_list_menu_satellite) { + if (googleMap != null) { + googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE); + } + } else if (id == map_list_menu_hybrid) { + if (googleMap != null) { + googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); + } + } else if (id == map_to_my_location) { + if (myLocation != null) { + LatLng latLng = new LatLng(myLocation.getLatitude(), myLocation.getLongitude()); if (googleMap != null) { - googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); - } - } else if (id == map_list_menu_satellite) { - if (googleMap != null) { - googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE); - } - } else if (id == map_list_menu_hybrid) { - if (googleMap != null) { - googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); - } - } else if (id == map_to_my_location) { - if (myLocation != null) { - LatLng latLng = new LatLng(myLocation.getLatitude(), myLocation.getLongitude()); - if (googleMap != null) { - CameraUpdate position = CameraUpdateFactory.newLatLngZoom(latLng, googleMap.getMaxZoomLevel() - 8); - googleMap.animateCamera(position); - } + CameraUpdate position = CameraUpdateFactory.newLatLngZoom(latLng, googleMap.getMaxZoomLevel() - 8); + googleMap.animateCamera(position); } } } + } + }); + + ActionBarMenu menu = actionBar.createMenu(); + menu.addItem(map_to_my_location, R.drawable.ic_ab_location); + + ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_other); + item.addSubItem(map_list_menu_map, LocaleController.getString("Map", R.string.Map), 0); + item.addSubItem(map_list_menu_satellite, LocaleController.getString("Satellite", R.string.Satellite), 0); + item.addSubItem(map_list_menu_hybrid, LocaleController.getString("Hybrid", R.string.Hybrid), 0); + + if (messageObject != null) { + fragmentView = inflater.inflate(R.layout.location_view_layout, null, false); + } else { + fragmentView = inflater.inflate(R.layout.location_attach_layout, null, false); + } + + avatarImageView = (BackupImageView) fragmentView.findViewById(R.id.location_avatar_view); + if (avatarImageView != null) { + avatarImageView.setRoundRadius(AndroidUtilities.dp(32)); + } + nameTextView = (TextView) fragmentView.findViewById(R.id.location_name_label); + distanceTextView = (TextView) fragmentView.findViewById(R.id.location_distance_label); + View bottomView = fragmentView.findViewById(R.id.location_bottom_view); + TextView sendButton = (TextView) fragmentView.findViewById(R.id.location_send_button); + if (sendButton != null) { + sendButton.setText(LocaleController.getString("SendLocation", R.string.SendLocation).toUpperCase()); + sendButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); + } + + mapView = (MapView) fragmentView.findViewById(R.id.map_view); + mapView.onCreate(null); + try { + MapsInitializer.initialize(context); + googleMap = mapView.getMap(); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + + if (googleMap != null) { + googleMap.setMyLocationEnabled(true); + googleMap.getUiSettings().setMyLocationButtonEnabled(false); + googleMap.getUiSettings().setZoomControlsEnabled(false); + googleMap.getUiSettings().setCompassEnabled(false); + googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() { + @Override + public void onMyLocationChange(Location location) { + positionMarker(location); + } }); + myLocation = getLastLocation(); - ActionBarMenu menu = actionBar.createMenu(); - menu.addItem(map_to_my_location, R.drawable.ic_ab_location); - - ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_other); - item.addSubItem(map_list_menu_map, LocaleController.getString("Map", R.string.Map), 0); - item.addSubItem(map_list_menu_satellite, LocaleController.getString("Satellite", R.string.Satellite), 0); - item.addSubItem(map_list_menu_hybrid, LocaleController.getString("Hybrid", R.string.Hybrid), 0); - - if (messageObject != null) { - fragmentView = inflater.inflate(R.layout.location_view_layout, null, false); - } else { - fragmentView = inflater.inflate(R.layout.location_attach_layout, null, false); - } - - avatarImageView = (BackupImageView)fragmentView.findViewById(R.id.location_avatar_view); - if (avatarImageView != null) { - avatarImageView.processDetach = false; - avatarImageView.imageReceiver.setRoundRadius(AndroidUtilities.dp(32)); - } - nameTextView = (TextView)fragmentView.findViewById(R.id.location_name_label); - distanceTextView = (TextView)fragmentView.findViewById(R.id.location_distance_label); - View bottomView = fragmentView.findViewById(R.id.location_bottom_view); - TextView sendButton = (TextView) fragmentView.findViewById(R.id.location_send_button); if (sendButton != null) { - sendButton.setText(LocaleController.getString("SendLocation", R.string.SendLocation).toUpperCase()); - sendButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - } + userLocation = new Location("network"); + userLocation.setLatitude(20.659322); + userLocation.setLongitude(-11.406250); + LatLng latLng = new LatLng(20.659322, -11.406250); + userMarker = googleMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_pin)).draggable(true)); - mapView = (MapView)fragmentView.findViewById(R.id.map_view); - mapView.onCreate(null); - try { - MapsInitializer.initialize(getParentActivity()); - googleMap = mapView.getMap(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - - if (googleMap != null) { - googleMap.setMyLocationEnabled(true); - googleMap.getUiSettings().setMyLocationButtonEnabled(false); - googleMap.getUiSettings().setZoomControlsEnabled(false); - googleMap.getUiSettings().setCompassEnabled(false); - googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() { + sendButton.setOnClickListener(new View.OnClickListener() { @Override - public void onMyLocationChange(Location location) { - positionMarker(location); + public void onClick(View view) { + if (delegate != null) { + delegate.didSelectLocation(userLocation.getLatitude(), userLocation.getLongitude()); + } + finishFragment(); } }); - myLocation = getLastLocation(); - if (sendButton != null) { - userLocation = new Location("network"); - userLocation.setLatitude(20.659322); - userLocation.setLongitude(-11.406250); - LatLng latLng = new LatLng(20.659322, -11.406250); - userMarker = googleMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_pin)).draggable(true)); + googleMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() { + @Override + public void onMarkerDragStart(Marker marker) { + } - sendButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (delegate != null) { - delegate.didSelectLocation(userLocation.getLatitude(), userLocation.getLongitude()); - } - finishFragment(); - } - }); + @Override + public void onMarkerDrag(Marker marker) { + userLocationMoved = true; + } - googleMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() { - @Override - public void onMarkerDragStart(Marker marker) { - } - - @Override - public void onMarkerDrag(Marker marker) { - userLocationMoved = true; - } - - @Override - public void onMarkerDragEnd(Marker marker) { - LatLng latLng = marker.getPosition(); - userLocation.setLatitude(latLng.latitude); - userLocation.setLongitude(latLng.longitude); - } - }); - } - - if (bottomView != null) { - bottomView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (userLocation != null) { - LatLng latLng = new LatLng(userLocation.getLatitude(), userLocation.getLongitude()); - CameraUpdate position = CameraUpdateFactory.newLatLngZoom(latLng, googleMap.getMaxZoomLevel() - 8); - googleMap.animateCamera(position); - } - } - }); - } - - if (messageObject != null) { - updateUserData(); - userLocation = new Location("network"); - userLocation.setLatitude(messageObject.messageOwner.media.geo.lat); - userLocation.setLongitude(messageObject.messageOwner.media.geo._long); - LatLng latLng = new LatLng(userLocation.getLatitude(), userLocation.getLongitude()); - userMarker = googleMap.addMarker(new MarkerOptions().position(latLng). - icon(BitmapDescriptorFactory.fromResource(R.drawable.map_pin))); - CameraUpdate position = CameraUpdateFactory.newLatLngZoom(latLng, googleMap.getMaxZoomLevel() - 8); - googleMap.moveCamera(position); - } - - positionMarker(myLocation); + @Override + public void onMarkerDragEnd(Marker marker) { + LatLng latLng = marker.getPosition(); + userLocation.setLatitude(latLng.latitude); + userLocation.setLongitude(latLng.longitude); + } + }); } - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); + + if (bottomView != null) { + bottomView.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + if (userLocation != null) { + LatLng latLng = new LatLng(userLocation.getLatitude(), userLocation.getLongitude()); + CameraUpdate position = CameraUpdateFactory.newLatLngZoom(latLng, googleMap.getMaxZoomLevel() - 8); + googleMap.animateCamera(position); + } + } + }); } + + if (messageObject != null) { + userLocation = new Location("network"); + userLocation.setLatitude(messageObject.messageOwner.media.geo.lat); + userLocation.setLongitude(messageObject.messageOwner.media.geo._long); + LatLng latLng = new LatLng(userLocation.getLatitude(), userLocation.getLongitude()); + userMarker = googleMap.addMarker(new MarkerOptions().position(latLng). + icon(BitmapDescriptorFactory.fromResource(R.drawable.map_pin))); + CameraUpdate position = CameraUpdateFactory.newLatLngZoom(latLng, googleMap.getMaxZoomLevel() - 8); + googleMap.moveCamera(position); + } + + positionMarker(myLocation); } + return fragmentView; } @@ -297,7 +286,7 @@ public class LocationActivity extends BaseFragment implements NotificationCenter if (userLocation != null && distanceTextView != null) { float distance = location.distanceTo(userLocation); if (distance < 1000) { - distanceTextView.setText(String.format("%d %s", (int)(distance), LocaleController.getString("MetersAway", R.string.MetersAway))); + distanceTextView.setText(String.format("%d %s", (int) (distance), LocaleController.getString("MetersAway", R.string.MetersAway))); } else { distanceTextView.setText(String.format("%.2f %s", distance / 1000.0f, LocaleController.getString("KMetersAway", R.string.KMetersAway))); } @@ -326,7 +315,7 @@ public class LocationActivity extends BaseFragment implements NotificationCenter @Override public void didReceivedNotification(int id, Object... args) { if (id == NotificationCenter.updateInterfaces) { - int mask = (Integer)args[0]; + int mask = (Integer) args[0]; if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0) { updateUserData(); } @@ -353,6 +342,7 @@ public class LocationActivity extends BaseFragment implements NotificationCenter if (mapView != null) { mapView.onResume(); } + updateUserData(); } @Override diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LoginActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/LoginActivity.java index 90b6a3fe1..b7b6fcf7c 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LoginActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LoginActivity.java @@ -16,8 +16,10 @@ import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; +import android.graphics.Typeface; import android.os.Build; import android.os.Bundle; +import android.os.Vibrator; import android.telephony.TelephonyManager; import android.text.Editable; import android.text.InputFilter; @@ -26,12 +28,12 @@ import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextUtils; import android.text.TextWatcher; +import android.text.method.PasswordTransformationMethod; import android.util.TypedValue; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; -import android.view.ViewGroup; import android.view.WindowManager; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.inputmethod.EditorInfo; @@ -80,7 +82,7 @@ import java.util.TimerTask; public class LoginActivity extends BaseFragment { private int currentViewNum = 0; - private SlideView[] views = new SlideView[3]; + private SlideView[] views = new SlideView[5]; private ProgressDialog progressDialog; private final static int done_button = 1; @@ -104,104 +106,72 @@ public class LoginActivity extends BaseFragment { } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setTitle(LocaleController.getString("AppName", R.string.AppName)); + public View createView(Context context, LayoutInflater inflater) { + actionBar.setTitle(LocaleController.getString("AppName", R.string.AppName)); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == done_button) { - views[currentViewNum].onNextPressed(); - } + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == done_button) { + views[currentViewNum].onNextPressed(); + } else if (id == -1) { + onBackPressed(); } - }); - - ActionBarMenu menu = actionBar.createMenu(); - menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); - - fragmentView = new ScrollView(getParentActivity()); - ScrollView scrollView = (ScrollView) fragmentView; - scrollView.setFillViewport(true); - - FrameLayout frameLayout = new FrameLayout(getParentActivity()); - scrollView.addView(frameLayout); - ScrollView.LayoutParams layoutParams = (ScrollView.LayoutParams) frameLayout.getLayoutParams(); - layoutParams.width = ScrollView.LayoutParams.MATCH_PARENT; - layoutParams.height = ScrollView.LayoutParams.WRAP_CONTENT; - layoutParams.gravity = Gravity.TOP | Gravity.LEFT; - frameLayout.setLayoutParams(layoutParams); - - views[0] = new PhoneView(getParentActivity()); - views[0].setVisibility(View.VISIBLE); - frameLayout.addView(views[0]); - FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) views[0].getLayoutParams(); - layoutParams1.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams1.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams1.leftMargin = AndroidUtilities.dp(16); - layoutParams1.rightMargin = AndroidUtilities.dp(16); - layoutParams1.topMargin = AndroidUtilities.dp(30); - layoutParams1.gravity = Gravity.TOP | Gravity.LEFT; - views[0].setLayoutParams(layoutParams1); - - views[1] = new LoginActivitySmsView(getParentActivity()); - views[1].setVisibility(View.GONE); - frameLayout.addView(views[1]); - layoutParams1 = (FrameLayout.LayoutParams) views[1].getLayoutParams(); - layoutParams1.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams1.height = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams1.leftMargin = AndroidUtilities.dp(16); - layoutParams1.rightMargin = AndroidUtilities.dp(16); - layoutParams1.topMargin = AndroidUtilities.dp(30); - layoutParams1.gravity = Gravity.TOP | Gravity.LEFT; - views[1].setLayoutParams(layoutParams1); - - views[2] = new RegisterView(getParentActivity()); - views[2].setVisibility(View.GONE); - frameLayout.addView(views[2]); - layoutParams1 = (FrameLayout.LayoutParams) views[2].getLayoutParams(); - layoutParams1.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams1.height = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams1.leftMargin = AndroidUtilities.dp(16); - layoutParams1.rightMargin = AndroidUtilities.dp(16); - layoutParams1.topMargin = AndroidUtilities.dp(30); - layoutParams1.gravity = Gravity.TOP | Gravity.LEFT; - views[2].setLayoutParams(layoutParams1); - - try { - if (views[0] == null || views[1] == null || views[2] == null) { - FrameLayout parent = (FrameLayout)((ScrollView) fragmentView).getChildAt(0); - for (int a = 0; a < views.length; a++) { - if (views[a] == null) { - views[a] = (SlideView)parent.getChildAt(a); - } - } - } - } catch (Exception e) { - FileLog.e("tmessages", e); } + }); - actionBar.setTitle(views[0].getHeaderName()); + ActionBarMenu menu = actionBar.createMenu(); + menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); - Bundle savedInstanceState = loadCurrentState(); + fragmentView = new ScrollView(context); + ScrollView scrollView = (ScrollView) fragmentView; + scrollView.setFillViewport(true); + + FrameLayout frameLayout = new FrameLayout(context); + scrollView.addView(frameLayout); + ScrollView.LayoutParams layoutParams = (ScrollView.LayoutParams) frameLayout.getLayoutParams(); + layoutParams.width = ScrollView.LayoutParams.MATCH_PARENT; + layoutParams.height = ScrollView.LayoutParams.WRAP_CONTENT; + layoutParams.gravity = Gravity.TOP | Gravity.LEFT; + frameLayout.setLayoutParams(layoutParams); + + views[0] = new PhoneView(context); + views[1] = new LoginActivitySmsView(context); + views[2] = new LoginActivityRegisterView(context); + views[3] = new LoginActivityPasswordView(context); + views[4] = new LoginActivityRecoverView(context); + + for (int a = 0; a < 5; a++) { + views[a].setVisibility(a == 0 ? View.VISIBLE : View.GONE); + frameLayout.addView(views[a]); + FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) views[a].getLayoutParams(); + layoutParams1.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams1.height = a == 0 ? FrameLayout.LayoutParams.WRAP_CONTENT : FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams1.leftMargin = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 26 : 18); + layoutParams1.rightMargin = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 26 : 18); + layoutParams1.topMargin = AndroidUtilities.dp(30); + layoutParams1.gravity = Gravity.TOP | Gravity.LEFT; + views[a].setLayoutParams(layoutParams1); + } + + Bundle savedInstanceState = loadCurrentState(); + if (savedInstanceState != null) { + currentViewNum = savedInstanceState.getInt("currentViewNum", 0); + } + actionBar.setTitle(views[currentViewNum].getHeaderName()); + for (int a = 0; a < views.length; a++) { if (savedInstanceState != null) { - currentViewNum = savedInstanceState.getInt("currentViewNum", 0); + views[a].restoreStateParams(savedInstanceState); } - for (int a = 0; a < views.length; a++) { - SlideView v = views[a]; - if (v != null) { - if (savedInstanceState != null) { - v.restoreStateParams(savedInstanceState); - } - v.setVisibility(currentViewNum == a ? View.VISIBLE : View.GONE); - } - } - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); + if (currentViewNum == a) { + actionBar.setBackButtonImage(views[a].needBackButton() ? R.drawable.ic_ab_back : 0); + views[a].setVisibility(View.VISIBLE); + views[a].onShow(); + } else { + views[a].setVisibility(View.GONE); } } + return fragmentView; } @@ -280,7 +250,7 @@ public class LoginActivity extends BaseFragment { editor.putInt(key, (Integer) obj); } } else if (obj instanceof Bundle) { - putBundleToEditor((Bundle)obj, editor, key); + putBundleToEditor((Bundle) obj, editor, key); } } } @@ -295,18 +265,22 @@ public class LoginActivity extends BaseFragment { } clearCurrentState(); return true; - } else if (currentViewNum != 1 && currentViewNum != 2) { + } else if (currentViewNum == 3) { + views[currentViewNum].onBackPressed(); setPage(0, true, null, true); + } else if (currentViewNum == 4) { + views[currentViewNum].onBackPressed(); + setPage(3, true, null, true); } return false; } - public void needShowAlert(final String text) { + public void needShowAlert(String title, String text) { if (text == null || getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + builder.setTitle(title); builder.setMessage(text); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); showAlertDialog(builder); @@ -336,10 +310,11 @@ public class LoginActivity extends BaseFragment { } public void setPage(int page, boolean animated, Bundle params, boolean back) { - if(android.os.Build.VERSION.SDK_INT > 13) { + if (android.os.Build.VERSION.SDK_INT > 13) { final SlideView outView = views[currentViewNum]; final SlideView newView = views[page]; currentViewNum = page; + actionBar.setBackButtonImage(newView.needBackButton() ? R.drawable.ic_ab_back : 0); newView.setParams(params); actionBar.setTitle(newView.getHeaderName()); @@ -383,6 +358,7 @@ public class LoginActivity extends BaseFragment { } }).setDuration(300).translationX(0).start(); } else { + actionBar.setBackButtonImage(views[page].needBackButton() ? R.drawable.ic_ab_back : 0); views[currentViewNum].setVisibility(View.GONE); currentViewNum = page; views[page].setParams(params); @@ -415,12 +391,8 @@ public class LoginActivity extends BaseFragment { public void needFinishActivity() { clearCurrentState(); - if (UserConfig.isWaitingForPasswordEnter()) { - presentFragment(new AccountPasswordActivity(1), true); - } else { - presentFragment(new MessagesActivity(null), true); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.mainUserInfoChanged); - } + presentFragment(new MessagesActivity(null), true); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.mainUserInfoChanged); } public class PhoneView extends SlideView implements AdapterView.OnItemSelectedListener { @@ -458,8 +430,6 @@ public class LoginActivity extends BaseFragment { LayoutParams layoutParams = (LayoutParams) countryButton.getLayoutParams(); layoutParams.width = LayoutParams.MATCH_PARENT; layoutParams.height = AndroidUtilities.dp(36); - layoutParams.leftMargin = AndroidUtilities.dp(20); - layoutParams.rightMargin = AndroidUtilities.dp(20); layoutParams.bottomMargin = AndroidUtilities.dp(14); countryButton.setLayoutParams(layoutParams); countryButton.setOnClickListener(new OnClickListener() { @@ -484,9 +454,9 @@ public class LoginActivity extends BaseFragment { layoutParams = (LayoutParams) view.getLayoutParams(); layoutParams.width = LayoutParams.MATCH_PARENT; layoutParams.height = 1; - layoutParams.leftMargin = AndroidUtilities.dp(24); - layoutParams.rightMargin = AndroidUtilities.dp(24); layoutParams.topMargin = AndroidUtilities.dp(-17.5f); + layoutParams.leftMargin = AndroidUtilities.dp(4); + layoutParams.rightMargin = AndroidUtilities.dp(4); view.setLayoutParams(layoutParams); LinearLayout linearLayout = new LinearLayout(context); @@ -506,7 +476,6 @@ public class LoginActivity extends BaseFragment { layoutParams = (LayoutParams) textView.getLayoutParams(); layoutParams.width = LayoutParams.WRAP_CONTENT; layoutParams.height = LayoutParams.WRAP_CONTENT; - layoutParams.leftMargin = AndroidUtilities.dp(24); textView.setLayoutParams(layoutParams); codeField = new EditText(context); @@ -598,7 +567,6 @@ public class LoginActivity extends BaseFragment { layoutParams = (LayoutParams) phoneField.getLayoutParams(); layoutParams.width = LayoutParams.MATCH_PARENT; layoutParams.height = AndroidUtilities.dp(36); - layoutParams.rightMargin = AndroidUtilities.dp(24); phoneField.setLayoutParams(layoutParams); phoneField.addTextChangedListener(new TextWatcher() { @Override @@ -616,7 +584,7 @@ public class LoginActivity extends BaseFragment { int toDelete = 0; for (int a = start; a >= 0; a--) { substr = str.substring(a, a + 1); - if(phoneChars.contains(substr)) { + if (phoneChars.contains(substr)) { break; } toDelete++; @@ -668,8 +636,6 @@ public class LoginActivity extends BaseFragment { layoutParams = (LayoutParams) textView.getLayoutParams(); layoutParams.width = LayoutParams.WRAP_CONTENT; layoutParams.height = LayoutParams.WRAP_CONTENT; - layoutParams.leftMargin = AndroidUtilities.dp(24); - layoutParams.rightMargin = AndroidUtilities.dp(24); layoutParams.topMargin = AndroidUtilities.dp(28); layoutParams.bottomMargin = AndroidUtilities.dp(10); layoutParams.gravity = Gravity.LEFT; @@ -701,7 +667,7 @@ public class LoginActivity extends BaseFragment { String country = null; try { - TelephonyManager telephonyManager = (TelephonyManager)ApplicationLoader.applicationContext.getSystemService(Context.TELEPHONY_SERVICE); + TelephonyManager telephonyManager = (TelephonyManager) ApplicationLoader.applicationContext.getSystemService(Context.TELEPHONY_SERVICE); if (telephonyManager != null) { country = telephonyManager.getSimCountryIso().toUpperCase(); } @@ -793,14 +759,14 @@ public class LoginActivity extends BaseFragment { return; } if (countryState == 1) { - needShowAlert(LocaleController.getString("ChooseCountry", R.string.ChooseCountry)); + needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.getString("ChooseCountry", R.string.ChooseCountry)); return; } else if (countryState == 2 && !BuildVars.DEBUG_VERSION) { - needShowAlert(LocaleController.getString("WrongCountry", R.string.WrongCountry)); + needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.getString("WrongCountry", R.string.WrongCountry)); return; } if (codeField.length() == 0) { - needShowAlert(LocaleController.getString("InvalidPhoneNumber", R.string.InvalidPhoneNumber)); + needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.getString("InvalidPhoneNumber", R.string.InvalidPhoneNumber)); return; } TLRPC.TL_auth_sendCode req = new TLRPC.TL_auth_sendCode(); @@ -834,22 +800,22 @@ public class LoginActivity extends BaseFragment { public void run() { nextPressed = false; if (error == null) { - final TLRPC.TL_auth_sentCode res = (TLRPC.TL_auth_sentCode)response; + final TLRPC.TL_auth_sentCode res = (TLRPC.TL_auth_sentCode) response; params.putString("phoneHash", res.phone_code_hash); params.putInt("calltime", res.send_call_timeout * 1000); setPage(1, true, params, false); } else { if (error.text != null) { if (error.text.contains("PHONE_NUMBER_INVALID")) { - needShowAlert(LocaleController.getString("InvalidPhoneNumber", R.string.InvalidPhoneNumber)); + needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.getString("InvalidPhoneNumber", R.string.InvalidPhoneNumber)); } else if (error.text.contains("PHONE_CODE_EMPTY") || error.text.contains("PHONE_CODE_INVALID")) { - needShowAlert(LocaleController.getString("InvalidCode", R.string.InvalidCode)); + needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.getString("InvalidCode", R.string.InvalidCode)); } else if (error.text.contains("PHONE_CODE_EXPIRED")) { - needShowAlert(LocaleController.getString("CodeExpired", R.string.CodeExpired)); + needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.getString("CodeExpired", R.string.CodeExpired)); } else if (error.text.startsWith("FLOOD_WAIT")) { - needShowAlert(LocaleController.getString("FloodWait", R.string.FloodWait)); + needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.getString("FloodWait", R.string.FloodWait)); } else if (error.code != -1000) { - needShowAlert(error.text); + needShowAlert(LocaleController.getString("AppName", R.string.AppName), error.text); } } } @@ -936,8 +902,6 @@ public class LoginActivity extends BaseFragment { layoutParams.width = LayoutParams.WRAP_CONTENT; layoutParams.height = LayoutParams.WRAP_CONTENT; layoutParams.gravity = Gravity.LEFT; - layoutParams.leftMargin = AndroidUtilities.dp(24); - layoutParams.rightMargin = AndroidUtilities.dp(24); confirmTextView.setLayoutParams(layoutParams); codeField = new EditText(context); @@ -956,8 +920,6 @@ public class LoginActivity extends BaseFragment { layoutParams.height = AndroidUtilities.dp(36); layoutParams.gravity = Gravity.CENTER_HORIZONTAL; layoutParams.topMargin = AndroidUtilities.dp(20); - layoutParams.leftMargin = AndroidUtilities.dp(24); - layoutParams.rightMargin = AndroidUtilities.dp(24); codeField.setLayoutParams(layoutParams); codeField.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override @@ -981,8 +943,6 @@ public class LoginActivity extends BaseFragment { layoutParams.height = LayoutParams.WRAP_CONTENT; layoutParams.gravity = Gravity.LEFT; layoutParams.topMargin = AndroidUtilities.dp(30); - layoutParams.leftMargin = AndroidUtilities.dp(24); - layoutParams.rightMargin = AndroidUtilities.dp(24); timeText.setLayoutParams(layoutParams); problemText = new TextView(context); @@ -999,8 +959,6 @@ public class LoginActivity extends BaseFragment { layoutParams.height = LayoutParams.WRAP_CONTENT; layoutParams.gravity = Gravity.LEFT; layoutParams.topMargin = AndroidUtilities.dp(20); - layoutParams.leftMargin = AndroidUtilities.dp(24); - layoutParams.rightMargin = AndroidUtilities.dp(24); problemText.setLayoutParams(layoutParams); problemText.setOnClickListener(new OnClickListener() { @Override @@ -1016,7 +974,7 @@ public class LoginActivity extends BaseFragment { mailer.putExtra(Intent.EXTRA_TEXT, "Phone: " + requestPhone + "\nApp version: " + version + "\nOS version: SDK " + Build.VERSION.SDK_INT + "\nDevice Name: " + Build.MANUFACTURER + Build.MODEL + "\nLocale: " + Locale.getDefault() + "\nError: " + lastError); getContext().startActivity(Intent.createChooser(mailer, "Send email...")); } catch (Exception e) { - needShowAlert(LocaleController.getString("NoMailInstalled", R.string.NoMailInstalled)); + needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.getString("NoMailInstalled", R.string.NoMailInstalled)); } } }); @@ -1041,8 +999,6 @@ public class LoginActivity extends BaseFragment { layoutParams.height = LayoutParams.WRAP_CONTENT; layoutParams.gravity = Gravity.BOTTOM | Gravity.LEFT; layoutParams.bottomMargin = AndroidUtilities.dp(10); - layoutParams.leftMargin = AndroidUtilities.dp(24); - layoutParams.rightMargin = AndroidUtilities.dp(24); wrongNumber.setLayoutParams(layoutParams); wrongNumber.setText(LocaleController.getString("WrongNumber", R.string.WrongNumber)); wrongNumber.setOnClickListener(new OnClickListener() { @@ -1133,7 +1089,7 @@ public class LoginActivity extends BaseFragment { private void destroyCodeTimer() { try { - synchronized(timerSync) { + synchronized (timerSync) { if (codeTimer != null) { codeTimer.cancel(); codeTimer = null; @@ -1192,7 +1148,7 @@ public class LoginActivity extends BaseFragment { private void destroyTimer() { try { - synchronized(timerSync) { + synchronized (timerSync) { if (timeTimer != null) { timeTimer.cancel(); timeTimer = null; @@ -1224,10 +1180,10 @@ public class LoginActivity extends BaseFragment { AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { - needHideProgress(); nextPressed = false; if (error == null) { - TLRPC.TL_auth_authorization res = (TLRPC.TL_auth_authorization)response; + needHideProgress(); + TLRPC.TL_auth_authorization res = (TLRPC.TL_auth_authorization) response; destroyTimer(); destroyCodeTimer(); UserConfig.clearConfig(); @@ -1253,6 +1209,7 @@ public class LoginActivity extends BaseFragment { lastError = error.text; if (error.text.contains("PHONE_NUMBER_UNOCCUPIED")) { + needHideProgress(); Bundle params = new Bundle(); params.putString("phoneFormated", requestPhone); params.putString("phoneHash", phoneHash); @@ -1261,21 +1218,47 @@ public class LoginActivity extends BaseFragment { destroyTimer(); destroyCodeTimer(); } else if (error.text.contains("SESSION_PASSWORD_NEEDED")) { - needFinishActivity(); + TLRPC.TL_account_getPassword req2 = new TLRPC.TL_account_getPassword(); + ConnectionsManager.getInstance().performRpc(req2, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(final TLObject response, final TLRPC.TL_error error) { + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + needHideProgress(); + if (error == null) { + TLRPC.TL_account_password password = (TLRPC.TL_account_password) response; + Bundle bundle = new Bundle(); + bundle.putString("current_salt", Utilities.bytesToHex(password.current_salt)); + bundle.putString("hint", password.hint); + bundle.putString("email_unconfirmed_pattern", password.email_unconfirmed_pattern); + bundle.putString("phoneFormated", requestPhone); + bundle.putString("phoneHash", phoneHash); + bundle.putString("code", req.phone_code); + bundle.putInt("has_recovery", password.has_recovery ? 1 : 0); + setPage(3, true, bundle, false); + } else { + needShowAlert(LocaleController.getString("AppName", R.string.AppName), error.text); + } + } + }); + } + }, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassWithoutLogin); destroyTimer(); destroyCodeTimer(); } else { + needHideProgress(); createTimer(); if (error.text.contains("PHONE_NUMBER_INVALID")) { - needShowAlert(LocaleController.getString("InvalidPhoneNumber", R.string.InvalidPhoneNumber)); + needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.getString("InvalidPhoneNumber", R.string.InvalidPhoneNumber)); } else if (error.text.contains("PHONE_CODE_EMPTY") || error.text.contains("PHONE_CODE_INVALID")) { - needShowAlert(LocaleController.getString("InvalidCode", R.string.InvalidCode)); + needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.getString("InvalidCode", R.string.InvalidCode)); } else if (error.text.contains("PHONE_CODE_EXPIRED")) { - needShowAlert(LocaleController.getString("CodeExpired", R.string.CodeExpired)); + needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.getString("CodeExpired", R.string.CodeExpired)); } else if (error.text.startsWith("FLOOD_WAIT")) { - needShowAlert(LocaleController.getString("FloodWait", R.string.FloodWait)); + needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.getString("FloodWait", R.string.FloodWait)); } else { - needShowAlert(error.text); + needShowAlert(LocaleController.getString("AppName", R.string.AppName), error.text); } } } @@ -1363,7 +1346,635 @@ public class LoginActivity extends BaseFragment { } } - public class RegisterView extends SlideView { + public class LoginActivityPasswordView extends SlideView { + + private EditText codeField; + private TextView confirmTextView; + private TextView resetAccountButton; + private TextView resetAccountText; + + private Bundle currentParams; + private boolean nextPressed; + private byte[] current_salt; + private String hint; + private String email_unconfirmed_pattern; + private boolean has_recovery; + private String requestPhone; + private String phoneHash; + private String phoneCode; + + public LoginActivityPasswordView(Context context) { + super(context); + + setOrientation(VERTICAL); + + confirmTextView = new TextView(context); + confirmTextView.setTextColor(0xff757575); + confirmTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + confirmTextView.setGravity(Gravity.LEFT); + confirmTextView.setLineSpacing(AndroidUtilities.dp(2), 1.0f); + confirmTextView.setText(LocaleController.getString("LoginPasswordText", R.string.LoginPasswordText)); + addView(confirmTextView); + LayoutParams layoutParams = (LayoutParams) confirmTextView.getLayoutParams(); + layoutParams.width = LayoutParams.WRAP_CONTENT; + layoutParams.height = LayoutParams.WRAP_CONTENT; + layoutParams.gravity = Gravity.LEFT; + confirmTextView.setLayoutParams(layoutParams); + + codeField = new EditText(context); + codeField.setTextColor(0xff212121); + AndroidUtilities.clearCursorDrawable(codeField); + codeField.setHintTextColor(0xff979797); + codeField.setHint(LocaleController.getString("LoginPassword", R.string.LoginPassword)); + codeField.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_EXTRACT_UI); + codeField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); + codeField.setMaxLines(1); + codeField.setPadding(0, 0, 0, 0); + codeField.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); + codeField.setTransformationMethod(PasswordTransformationMethod.getInstance()); + codeField.setTypeface(Typeface.DEFAULT); + addView(codeField); + layoutParams = (LayoutParams) codeField.getLayoutParams(); + layoutParams.width = LayoutParams.MATCH_PARENT; + layoutParams.height = AndroidUtilities.dp(36); + layoutParams.gravity = Gravity.CENTER_HORIZONTAL; + layoutParams.topMargin = AndroidUtilities.dp(20); + codeField.setLayoutParams(layoutParams); + codeField.setOnEditorActionListener(new TextView.OnEditorActionListener() { + @Override + public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { + if (i == EditorInfo.IME_ACTION_NEXT) { + onNextPressed(); + return true; + } + return false; + } + }); + + TextView cancelButton = new TextView(context); + cancelButton.setGravity(Gravity.LEFT | Gravity.TOP); + cancelButton.setTextColor(0xff4d83b3); + cancelButton.setText(LocaleController.getString("ForgotPassword", R.string.ForgotPassword)); + cancelButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + cancelButton.setLineSpacing(AndroidUtilities.dp(2), 1.0f); + cancelButton.setPadding(0, AndroidUtilities.dp(14), 0, 0); + addView(cancelButton); + layoutParams = (LayoutParams) cancelButton.getLayoutParams(); + layoutParams.width = LayoutParams.WRAP_CONTENT; + layoutParams.height = LayoutParams.WRAP_CONTENT; + layoutParams.gravity = Gravity.TOP | Gravity.LEFT; + cancelButton.setLayoutParams(layoutParams); + cancelButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View view) { + if (has_recovery) { + needShowProgress(); + TLRPC.TL_auth_requestPasswordRecovery req = new TLRPC.TL_auth_requestPasswordRecovery(); + ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(final TLObject response, final TLRPC.TL_error error) { + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + needHideProgress(); + if (error == null) { + final TLRPC.TL_auth_passwordRecovery res = (TLRPC.TL_auth_passwordRecovery) response; + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setMessage(LocaleController.formatString("RestoreEmailSent", R.string.RestoreEmailSent, res.email_pattern)); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + Bundle bundle = new Bundle(); + bundle.putString("email_unconfirmed_pattern", res.email_pattern); + setPage(4, true, bundle, false); + } + }); + AlertDialog dialog = showAlertDialog(builder); + if (dialog != null) { + dialog.setCanceledOnTouchOutside(false); + dialog.setCancelable(false); + } + } else { + if (error.text.startsWith("FLOOD_WAIT")) { + int time = Utilities.parseInt(error.text); + String timeString; + if (time < 60) { + timeString = LocaleController.formatPluralString("Seconds", time); + } else { + timeString = LocaleController.formatPluralString("Minutes", time / 60); + } + needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.formatString("FloodWaitTime", R.string.FloodWaitTime, timeString)); + } else { + needShowAlert(LocaleController.getString("AppName", R.string.AppName), error.text); + } + } + } + }); + } + }, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassWithoutLogin); + } else { + resetAccountText.setVisibility(VISIBLE); + resetAccountButton.setVisibility(VISIBLE); + AndroidUtilities.hideKeyboard(codeField); + needShowAlert(LocaleController.getString("RestorePasswordNoEmailTitle", R.string.RestorePasswordNoEmailTitle), LocaleController.getString("RestorePasswordNoEmailText", R.string.RestorePasswordNoEmailText)); + } + } + }); + + resetAccountButton = new TextView(context); + resetAccountButton.setGravity(Gravity.LEFT | Gravity.TOP); + resetAccountButton.setTextColor(0xffff6666); + resetAccountButton.setVisibility(GONE); + resetAccountButton.setText(LocaleController.getString("ResetMyAccount", R.string.ResetMyAccount)); + resetAccountButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); + resetAccountButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + resetAccountButton.setLineSpacing(AndroidUtilities.dp(2), 1.0f); + resetAccountButton.setPadding(0, AndroidUtilities.dp(14), 0, 0); + addView(resetAccountButton); + layoutParams = (LayoutParams) resetAccountButton.getLayoutParams(); + layoutParams.width = LayoutParams.WRAP_CONTENT; + layoutParams.height = LayoutParams.WRAP_CONTENT; + layoutParams.gravity = Gravity.TOP | Gravity.LEFT; + layoutParams.topMargin = AndroidUtilities.dp(34); + resetAccountButton.setLayoutParams(layoutParams); + resetAccountButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View view) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setMessage(LocaleController.getString("ResetMyAccountWarningText", R.string.ResetMyAccountWarningText)); + builder.setTitle(LocaleController.getString("ResetMyAccountWarning", R.string.ResetMyAccountWarning)); + builder.setPositiveButton(LocaleController.getString("ResetMyAccountWarningReset", R.string.ResetMyAccountWarningReset), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + needShowProgress(); + TLRPC.TL_account_deleteAccount req = new TLRPC.TL_account_deleteAccount(); + req.reason = "Forgot password"; + ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(TLObject response, final TLRPC.TL_error error) { + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + needHideProgress(); + if (error == null) { + Bundle params = new Bundle(); + params.putString("phoneFormated", requestPhone); + params.putString("phoneHash", phoneHash); + params.putString("code", phoneCode); + setPage(2, true, params, false); + } else { + needShowAlert(LocaleController.getString("AppName", R.string.AppName), error.text); + } + } + }); + } + }, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassWithoutLogin | RPCRequest.RPCRequestClassFailOnServerErrors); + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } + }); + + resetAccountText = new TextView(context); + resetAccountText.setGravity(Gravity.LEFT | Gravity.TOP); + resetAccountText.setVisibility(GONE); + resetAccountText.setTextColor(0xff757575); + resetAccountText.setText(LocaleController.getString("ResetMyAccountText", R.string.ResetMyAccountText)); + resetAccountText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + resetAccountText.setLineSpacing(AndroidUtilities.dp(2), 1.0f); + addView(resetAccountText); + layoutParams = (LayoutParams) resetAccountText.getLayoutParams(); + layoutParams.width = LayoutParams.WRAP_CONTENT; + layoutParams.height = LayoutParams.WRAP_CONTENT; + layoutParams.gravity = Gravity.TOP | Gravity.LEFT; + layoutParams.bottomMargin = AndroidUtilities.dp(14); + layoutParams.topMargin = AndroidUtilities.dp(7); + resetAccountText.setLayoutParams(layoutParams); + } + + @Override + public String getHeaderName() { + return LocaleController.getString("LoginPassword", R.string.LoginPassword); + } + + @Override + public void setParams(Bundle params) { + if (params == null) { + return; + } + if (params.isEmpty()) { + resetAccountButton.setVisibility(VISIBLE); + resetAccountText.setVisibility(VISIBLE); + AndroidUtilities.hideKeyboard(codeField); + return; + } + resetAccountButton.setVisibility(GONE); + resetAccountText.setVisibility(GONE); + codeField.setText(""); + currentParams = params; + current_salt = Utilities.hexToBytes(currentParams.getString("current_salt")); + hint = currentParams.getString("hint"); + has_recovery = currentParams.getInt("has_recovery") == 1; + email_unconfirmed_pattern = currentParams.getString("email_unconfirmed_pattern"); + requestPhone = params.getString("phoneFormated"); + phoneHash = params.getString("phoneHash"); + phoneCode = params.getString("code"); + + AndroidUtilities.showKeyboard(codeField); + codeField.requestFocus(); + + + if (hint != null && hint.length() > 0) { + codeField.setHint(hint); + } else { + codeField.setHint(LocaleController.getString("LoginPassword", R.string.LoginPassword)); + } + } + + private void onPasscodeError(boolean clear) { + if (getParentActivity() == null) { + return; + } + Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE); + if (v != null) { + v.vibrate(200); + } + if (clear) { + codeField.setText(""); + } + AndroidUtilities.shakeTextView(confirmTextView, 2, 0); + } + + @Override + public void onNextPressed() { + if (nextPressed) { + return; + } + + String oldPassword = codeField.getText().toString(); + if (oldPassword.length() == 0) { + onPasscodeError(false); + return; + } + nextPressed = true; + byte[] oldPasswordBytes = null; + try { + oldPasswordBytes = oldPassword.getBytes("UTF-8"); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + + needShowProgress(); + byte[] hash = new byte[current_salt.length * 2 + oldPasswordBytes.length]; + System.arraycopy(current_salt, 0, hash, 0, current_salt.length); + System.arraycopy(oldPasswordBytes, 0, hash, current_salt.length, oldPasswordBytes.length); + System.arraycopy(current_salt, 0, hash, hash.length - current_salt.length, current_salt.length); + + final TLRPC.TL_auth_checkPassword req = new TLRPC.TL_auth_checkPassword(); + req.password_hash = Utilities.computeSHA256(hash, 0, hash.length); + ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(final TLObject response, final TLRPC.TL_error error) { + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + needHideProgress(); + nextPressed = false; + if (error == null) { + TLRPC.TL_auth_authorization res = (TLRPC.TL_auth_authorization) response; + UserConfig.clearConfig(); + MessagesController.getInstance().cleanUp(); + UserConfig.setCurrentUser(res.user); + UserConfig.saveConfig(true); + MessagesStorage.getInstance().cleanUp(true); + ArrayList users = new ArrayList<>(); + users.add(res.user); + MessagesStorage.getInstance().putUsersAndChats(users, null, true, true); + MessagesController.getInstance().putUser(res.user, false); + ContactsController.getInstance().checkAppAccount(); + MessagesController.getInstance().getBlockedUsers(true); + needFinishActivity(); + ConnectionsManager.getInstance().initPushConnection(); + Utilities.stageQueue.postRunnable(new Runnable() { + @Override + public void run() { + ConnectionsManager.getInstance().updateDcSettings(0); + } + }); + } else { + if (error.text.equals("PASSWORD_HASH_INVALID")) { + onPasscodeError(true); + } else if (error.text.startsWith("FLOOD_WAIT")) { + int time = Utilities.parseInt(error.text); + String timeString; + if (time < 60) { + timeString = LocaleController.formatPluralString("Seconds", time); + } else { + timeString = LocaleController.formatPluralString("Minutes", time / 60); + } + needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.formatString("FloodWaitTime", R.string.FloodWaitTime, timeString)); + } else { + needShowAlert(LocaleController.getString("AppName", R.string.AppName), error.text); + } + } + } + }); + } + }, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassWithoutLogin); + } + + @Override + public boolean needBackButton() { + return true; + } + + @Override + public void onBackPressed() { + currentParams = null; + } + + @Override + public void onShow() { + super.onShow(); + if (codeField != null) { + codeField.requestFocus(); + codeField.setSelection(codeField.length()); + } + } + + @Override + public void saveStateParams(Bundle bundle) { + String code = codeField.getText().toString(); + if (code != null && code.length() != 0) { + bundle.putString("passview_code", code); + } + if (currentParams != null) { + bundle.putBundle("passview_params", currentParams); + } + } + + @Override + public void restoreStateParams(Bundle bundle) { + currentParams = bundle.getBundle("passview_params"); + if (currentParams != null) { + setParams(currentParams); + } + String code = bundle.getString("passview_code"); + if (code != null) { + codeField.setText(code); + } + } + } + + public class LoginActivityRecoverView extends SlideView { + + private EditText codeField; + private TextView confirmTextView; + private TextView cancelButton; + + private Bundle currentParams; + private boolean nextPressed; + private String email_unconfirmed_pattern; + + public LoginActivityRecoverView(Context context) { + super(context); + + setOrientation(VERTICAL); + + confirmTextView = new TextView(context); + confirmTextView.setTextColor(0xff757575); + confirmTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + confirmTextView.setGravity(Gravity.LEFT); + confirmTextView.setLineSpacing(AndroidUtilities.dp(2), 1.0f); + confirmTextView.setText(LocaleController.getString("RestoreEmailSentInfo", R.string.RestoreEmailSentInfo)); + addView(confirmTextView); + LayoutParams layoutParams = (LayoutParams) confirmTextView.getLayoutParams(); + layoutParams.width = LayoutParams.WRAP_CONTENT; + layoutParams.height = LayoutParams.WRAP_CONTENT; + layoutParams.gravity = Gravity.LEFT; + confirmTextView.setLayoutParams(layoutParams); + + codeField = new EditText(context); + codeField.setTextColor(0xff212121); + AndroidUtilities.clearCursorDrawable(codeField); + codeField.setHintTextColor(0xff979797); + codeField.setHint(LocaleController.getString("PasswordCode", R.string.PasswordCode)); + codeField.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_EXTRACT_UI); + codeField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); + codeField.setMaxLines(1); + codeField.setPadding(0, 0, 0, 0); + codeField.setInputType(InputType.TYPE_CLASS_PHONE); + codeField.setTransformationMethod(PasswordTransformationMethod.getInstance()); + codeField.setTypeface(Typeface.DEFAULT); + addView(codeField); + layoutParams = (LayoutParams) codeField.getLayoutParams(); + layoutParams.width = LayoutParams.MATCH_PARENT; + layoutParams.height = AndroidUtilities.dp(36); + layoutParams.gravity = Gravity.CENTER_HORIZONTAL; + layoutParams.topMargin = AndroidUtilities.dp(20); + codeField.setLayoutParams(layoutParams); + codeField.setOnEditorActionListener(new TextView.OnEditorActionListener() { + @Override + public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { + if (i == EditorInfo.IME_ACTION_NEXT) { + onNextPressed(); + return true; + } + return false; + } + }); + + cancelButton = new TextView(context); + cancelButton.setGravity(Gravity.LEFT | Gravity.BOTTOM); + cancelButton.setTextColor(0xff4d83b3); + cancelButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + cancelButton.setLineSpacing(AndroidUtilities.dp(2), 1.0f); + cancelButton.setPadding(0, AndroidUtilities.dp(14), 0, 0); + addView(cancelButton); + layoutParams = (LayoutParams) cancelButton.getLayoutParams(); + layoutParams.width = LayoutParams.WRAP_CONTENT; + layoutParams.height = LayoutParams.WRAP_CONTENT; + layoutParams.gravity = Gravity.BOTTOM | Gravity.LEFT; + layoutParams.bottomMargin = AndroidUtilities.dp(14); + cancelButton.setLayoutParams(layoutParams); + cancelButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View view) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setMessage(LocaleController.getString("RestoreEmailTroubleText", R.string.RestoreEmailTroubleText)); + builder.setTitle(LocaleController.getString("RestorePasswordNoEmailTitle", R.string.RestorePasswordNoEmailTitle)); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + setPage(3, true, new Bundle(), true); + } + }); + AlertDialog dialog = showAlertDialog(builder); + if (dialog != null) { + dialog.setCanceledOnTouchOutside(false); + dialog.setCancelable(false); + } + } + }); + } + + @Override + public boolean needBackButton() { + return true; + } + + @Override + public String getHeaderName() { + return LocaleController.getString("LoginPassword", R.string.LoginPassword); + } + + @Override + public void setParams(Bundle params) { + if (params == null) { + return; + } + codeField.setText(""); + currentParams = params; + email_unconfirmed_pattern = currentParams.getString("email_unconfirmed_pattern"); + cancelButton.setText(LocaleController.formatString("RestoreEmailTrouble", R.string.RestoreEmailTrouble, email_unconfirmed_pattern)); + + AndroidUtilities.showKeyboard(codeField); + codeField.requestFocus(); + } + + private void onPasscodeError(boolean clear) { + if (getParentActivity() == null) { + return; + } + Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE); + if (v != null) { + v.vibrate(200); + } + if (clear) { + codeField.setText(""); + } + AndroidUtilities.shakeTextView(confirmTextView, 2, 0); + } + + @Override + public void onNextPressed() { + if (nextPressed) { + return; + } + + String oldPassword = codeField.getText().toString(); + if (oldPassword.length() == 0) { + onPasscodeError(false); + return; + } + nextPressed = true; + byte[] oldPasswordBytes = null; + try { + oldPasswordBytes = oldPassword.getBytes("UTF-8"); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + + String code = codeField.getText().toString(); + if (code.length() == 0) { + onPasscodeError(false); + return; + } + needShowProgress(); + TLRPC.TL_auth_recoverPassword req = new TLRPC.TL_auth_recoverPassword(); + req.code = code; + ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(final TLObject response, final TLRPC.TL_error error) { + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + needHideProgress(); + nextPressed = false; + if (error == null) { + TLRPC.TL_auth_authorization res = (TLRPC.TL_auth_authorization) response; + UserConfig.clearConfig(); + MessagesController.getInstance().cleanUp(); + UserConfig.setCurrentUser(res.user); + UserConfig.saveConfig(true); + MessagesStorage.getInstance().cleanUp(true); + ArrayList users = new ArrayList<>(); + users.add(res.user); + MessagesStorage.getInstance().putUsersAndChats(users, null, true, true); + MessagesController.getInstance().putUser(res.user, false); + ContactsController.getInstance().checkAppAccount(); + MessagesController.getInstance().getBlockedUsers(true); + needFinishActivity(); + ConnectionsManager.getInstance().initPushConnection(); + Utilities.stageQueue.postRunnable(new Runnable() { + @Override + public void run() { + ConnectionsManager.getInstance().updateDcSettings(0); + } + }); + } else { + if (error.text.startsWith("CODE_INVALID")) { + onPasscodeError(true); + } else if (error.text.startsWith("FLOOD_WAIT")) { + int time = Utilities.parseInt(error.text); + String timeString; + if (time < 60) { + timeString = LocaleController.formatPluralString("Seconds", time); + } else { + timeString = LocaleController.formatPluralString("Minutes", time / 60); + } + needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.formatString("FloodWaitTime", R.string.FloodWaitTime, timeString)); + } else { + needShowAlert(LocaleController.getString("AppName", R.string.AppName), error.text); + } + } + } + }); + } + }, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassWithoutLogin); + } + + @Override + public void onBackPressed() { + currentParams = null; + } + + @Override + public void onShow() { + super.onShow(); + if (codeField != null) { + codeField.requestFocus(); + codeField.setSelection(codeField.length()); + } + } + + @Override + public void saveStateParams(Bundle bundle) { + String code = codeField.getText().toString(); + if (code != null && code.length() != 0) { + bundle.putString("recoveryview_code", code); + } + if (currentParams != null) { + bundle.putBundle("recoveryview_params", currentParams); + } + } + + @Override + public void restoreStateParams(Bundle bundle) { + currentParams = bundle.getBundle("recoveryview_params"); + if (currentParams != null) { + setParams(currentParams); + } + String code = bundle.getString("recoveryview_code"); + if (code != null) { + codeField.setText(code); + } + } + } + + public class LoginActivityRegisterView extends SlideView { private EditText firstNameField; private EditText lastNameField; @@ -1373,7 +1984,7 @@ public class LoginActivity extends BaseFragment { private Bundle currentParams; private boolean nextPressed = false; - public RegisterView(Context context) { + public LoginActivityRegisterView(Context context) { super(context); setOrientation(VERTICAL); @@ -1388,8 +1999,6 @@ public class LoginActivity extends BaseFragment { layoutParams.width = LayoutParams.WRAP_CONTENT; layoutParams.height = LayoutParams.WRAP_CONTENT; layoutParams.topMargin = AndroidUtilities.dp(8); - layoutParams.leftMargin = AndroidUtilities.dp(24); - layoutParams.rightMargin = AndroidUtilities.dp(24); layoutParams.gravity = Gravity.LEFT; textView.setLayoutParams(layoutParams); @@ -1406,8 +2015,6 @@ public class LoginActivity extends BaseFragment { layoutParams = (LayoutParams) firstNameField.getLayoutParams(); layoutParams.width = LayoutParams.MATCH_PARENT; layoutParams.height = AndroidUtilities.dp(36); - layoutParams.leftMargin = AndroidUtilities.dp(24); - layoutParams.rightMargin = AndroidUtilities.dp(24); layoutParams.topMargin = AndroidUtilities.dp(26); firstNameField.setLayoutParams(layoutParams); firstNameField.setOnEditorActionListener(new TextView.OnEditorActionListener() { @@ -1434,8 +2041,6 @@ public class LoginActivity extends BaseFragment { layoutParams = (LayoutParams) lastNameField.getLayoutParams(); layoutParams.width = LayoutParams.MATCH_PARENT; layoutParams.height = AndroidUtilities.dp(36); - layoutParams.leftMargin = AndroidUtilities.dp(24); - layoutParams.rightMargin = AndroidUtilities.dp(24); layoutParams.topMargin = AndroidUtilities.dp(10); lastNameField.setLayoutParams(layoutParams); @@ -1460,8 +2065,6 @@ public class LoginActivity extends BaseFragment { layoutParams.height = LayoutParams.WRAP_CONTENT; layoutParams.gravity = Gravity.BOTTOM | Gravity.LEFT; layoutParams.bottomMargin = AndroidUtilities.dp(10); - layoutParams.leftMargin = AndroidUtilities.dp(24); - layoutParams.rightMargin = AndroidUtilities.dp(24); wrongNumber.setLayoutParams(layoutParams); wrongNumber.setOnClickListener(new OnClickListener() { @Override @@ -1560,23 +2163,23 @@ public class LoginActivity extends BaseFragment { }); } else { if (error.text.contains("PHONE_NUMBER_INVALID")) { - needShowAlert(LocaleController.getString("InvalidPhoneNumber", R.string.InvalidPhoneNumber)); + needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.getString("InvalidPhoneNumber", R.string.InvalidPhoneNumber)); } else if (error.text.contains("PHONE_CODE_EMPTY") || error.text.contains("PHONE_CODE_INVALID")) { - needShowAlert(LocaleController.getString("InvalidCode", R.string.InvalidCode)); + needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.getString("InvalidCode", R.string.InvalidCode)); } else if (error.text.contains("PHONE_CODE_EXPIRED")) { - needShowAlert(LocaleController.getString("CodeExpired", R.string.CodeExpired)); + needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.getString("CodeExpired", R.string.CodeExpired)); } else if (error.text.contains("FIRSTNAME_INVALID")) { - needShowAlert(LocaleController.getString("InvalidFirstName", R.string.InvalidFirstName)); + needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.getString("InvalidFirstName", R.string.InvalidFirstName)); } else if (error.text.contains("LASTNAME_INVALID")) { - needShowAlert(LocaleController.getString("InvalidLastName", R.string.InvalidLastName)); + needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.getString("InvalidLastName", R.string.InvalidLastName)); } else { - needShowAlert(error.text); + needShowAlert(LocaleController.getString("AppName", R.string.AppName), error.text); } } } }); } - }, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassWithoutLogin); + }, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassWithoutLogin | RPCRequest.RPCRequestClassFailOnServerErrors); } @Override diff --git a/TMessagesProj/src/main/java/org/telegram/ui/MediaActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/MediaActivity.java index a34f7e354..90d6f84fb 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/MediaActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/MediaActivity.java @@ -216,364 +216,358 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setTitle(""); - actionBar.setAllowOverlayTitle(false); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - if (Build.VERSION.SDK_INT < 11 && listView != null) { - listView.setAdapter(null); - listView = null; - photoVideoAdapter = null; - documentsAdapter = null; - } - finishFragment(); - } else if (id == -2) { - selectedFiles.clear(); - actionBar.hideActionMode(); - listView.invalidateViews(); - } else if (id == shared_media_item) { - if (selectedMode == 0) { - return; - } - selectedMode = 0; - switchToCurrentSelectedMode(); - } else if (id == files_item) { - if (selectedMode == 1) { - return; - } - selectedMode = 1; - switchToCurrentSelectedMode(); - } else if (id == delete) { - if (getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setMessage(LocaleController.formatString("AreYouSureDeleteMessages", R.string.AreYouSureDeleteMessages, LocaleController.formatPluralString("items", selectedFiles.size()))); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - ArrayList ids = new ArrayList<>(selectedFiles.keySet()); - ArrayList random_ids = null; - TLRPC.EncryptedChat currentEncryptedChat = null; - if ((int) dialog_id == 0) { - currentEncryptedChat = MessagesController.getInstance().getEncryptedChat((int) (dialog_id >> 32)); - } - if (currentEncryptedChat != null) { - random_ids = new ArrayList<>(); - for (HashMap.Entry entry : selectedFiles.entrySet()) { - MessageObject msg = entry.getValue(); - if (msg.messageOwner.random_id != 0 && msg.type != 10) { - random_ids.add(msg.messageOwner.random_id); - } - } - } - MessagesController.getInstance().deleteMessages(ids, random_ids, currentEncryptedChat); - actionBar.hideActionMode(); - selectedFiles.clear(); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } else if (id == forward) { - Bundle args = new Bundle(); - args.putBoolean("onlySelect", true); - args.putBoolean("serverOnly", true); - MessagesActivity fragment = new MessagesActivity(args); - fragment.setDelegate(new MessagesActivity.MessagesActivityDelegate() { - @Override - public void didSelectDialog(MessagesActivity fragment, long did, boolean param) { - int lower_part = (int)did; - if (lower_part != 0) { - Bundle args = new Bundle(); - args.putBoolean("scrollToTopOnResume", true); - if (lower_part > 0) { - args.putInt("user_id", lower_part); - } else if (lower_part < 0) { - args.putInt("chat_id", -lower_part); - } - - ArrayList fmessages = new ArrayList<>(); - ArrayList ids = new ArrayList<>(selectedFiles.keySet()); - Collections.sort(ids); - for (Integer id : ids) { - if (id > 0) { - fmessages.add(selectedFiles.get(id)); - } - } - selectedFiles.clear(); - actionBar.hideActionMode(); - - NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); - ChatActivity chatActivity = new ChatActivity(args); - presentFragment(chatActivity, true); - chatActivity.showReplyForMessageObjectOrForward(true, null, fmessages, false); - - if (!AndroidUtilities.isTablet()) { - removeSelfFromStack(); - Activity parentActivity = getParentActivity(); - if (parentActivity == null) { - parentActivity = chatActivity.getParentActivity(); - } - if (parentActivity != null) { - parentActivity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); - } - } - } else { - fragment.finishFragment(); - } - } - }); - presentFragment(fragment); + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setTitle(""); + actionBar.setAllowOverlayTitle(false); + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + if (Build.VERSION.SDK_INT < 11 && listView != null) { + listView.setAdapter(null); + listView = null; + photoVideoAdapter = null; + documentsAdapter = null; } - } - }); - - selectedFiles.clear(); - actionModeViews.clear(); - - final ActionBarMenu menu = actionBar.createMenu(); - searchItem = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() { - @Override - public void onSearchExpand() { - dropDownContainer.setVisibility(View.GONE); - searching = true; - } - - @Override - public boolean onSearchCollapse() { - dropDownContainer.setVisibility(View.VISIBLE); - documentsSearchAdapter.searchDocuments(null); - searching = false; - searchWas = false; + finishFragment(); + } else if (id == -2) { + selectedFiles.clear(); + actionBar.hideActionMode(); + listView.invalidateViews(); + } else if (id == shared_media_item) { + if (selectedMode == 0) { + return; + } + selectedMode = 0; switchToCurrentSelectedMode(); - - return true; - } - - @Override - public void onTextChanged(EditText editText) { - if (documentsSearchAdapter == null) { + } else if (id == files_item) { + if (selectedMode == 1) { return; } - String text = editText.getText().toString(); - if (text.length() != 0) { - searchWas = true; - switchToCurrentSelectedMode(); - } - documentsSearchAdapter.searchDocuments(text); - } - }); - searchItem.getSearchField().setHint(LocaleController.getString("Search", R.string.Search)); - searchItem.setVisibility(View.GONE); - - dropDownContainer = new ActionBarMenuItem(getParentActivity(), menu, R.drawable.bar_selector); - dropDownContainer.setSubMenuOpenSide(1); - dropDownContainer.addSubItem(shared_media_item, LocaleController.getString("SharedMediaTitle", R.string.SharedMediaTitle), 0); - dropDownContainer.addSubItem(files_item, LocaleController.getString("DocumentsTitle", R.string.DocumentsTitle), 0); - actionBar.addView(dropDownContainer); - FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) dropDownContainer.getLayoutParams(); - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.rightMargin = AndroidUtilities.dp(40); - layoutParams.leftMargin = AndroidUtilities.isTablet() ? AndroidUtilities.dp(64) : AndroidUtilities.dp(56); - layoutParams.gravity = Gravity.TOP | Gravity.LEFT; - dropDownContainer.setLayoutParams(layoutParams); - dropDownContainer.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - dropDownContainer.toggleSubMenu(); - } - }); - - dropDown = new TextView(getParentActivity()); - dropDown.setGravity(Gravity.LEFT); - dropDown.setSingleLine(true); - dropDown.setLines(1); - dropDown.setMaxLines(1); - dropDown.setEllipsize(TextUtils.TruncateAt.END); - dropDown.setTextColor(0xffffffff); - dropDown.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - dropDown.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_arrow_drop_down, 0); - dropDown.setCompoundDrawablePadding(AndroidUtilities.dp(4)); - dropDown.setPadding(0, 0, AndroidUtilities.dp(10), 0); - dropDownContainer.addView(dropDown); - layoutParams = (FrameLayout.LayoutParams) dropDown.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.leftMargin = AndroidUtilities.dp(16); - layoutParams.gravity = Gravity.CENTER_VERTICAL; - dropDown.setLayoutParams(layoutParams); - - final ActionBarMenu actionMode = actionBar.createActionMode(); - actionModeViews.add(actionMode.addItem(-2, R.drawable.ic_ab_back_grey, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); - - selectedMessagesCountTextView = new TextView(actionMode.getContext()); - selectedMessagesCountTextView.setTextSize(18); - selectedMessagesCountTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - selectedMessagesCountTextView.setTextColor(0xff737373); - selectedMessagesCountTextView.setSingleLine(true); - selectedMessagesCountTextView.setLines(1); - selectedMessagesCountTextView.setEllipsize(TextUtils.TruncateAt.END); - selectedMessagesCountTextView.setPadding(AndroidUtilities.dp(11), 0, 0, AndroidUtilities.dp(2)); - selectedMessagesCountTextView.setGravity(Gravity.CENTER_VERTICAL); - selectedMessagesCountTextView.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - return true; - } - }); - actionMode.addView(selectedMessagesCountTextView); - LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams)selectedMessagesCountTextView.getLayoutParams(); - layoutParams1.weight = 1; - layoutParams1.width = 0; - layoutParams1.height = LinearLayout.LayoutParams.MATCH_PARENT; - selectedMessagesCountTextView.setLayoutParams(layoutParams1); - - if ((int) dialog_id != 0) { - actionModeViews.add(actionMode.addItem(forward, R.drawable.ic_ab_fwd_forward, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); - } - actionModeViews.add(actionMode.addItem(delete, R.drawable.ic_ab_fwd_delete, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); - - photoVideoAdapter = new SharedPhotoVideoAdapter(getParentActivity()); - documentsAdapter = new SharedDocumentsAdapter(getParentActivity()); - documentsSearchAdapter = new DocumentsSearchAdapter(getParentActivity()); - - FrameLayout frameLayout; - fragmentView = frameLayout = new FrameLayout(getParentActivity()); - - listView = new SectionsListView(getParentActivity()); - listView.setDivider(null); - listView.setDividerHeight(0); - listView.setDrawSelectorOnTop(true); - listView.setClipToPadding(false); - frameLayout.addView(listView); - layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.gravity = Gravity.TOP; - listView.setLayoutParams(layoutParams); - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, final int i, long l) { - if (selectedMode == 1 && view instanceof SharedDocumentCell) { - SharedDocumentCell cell = (SharedDocumentCell) view; - MessageObject message = cell.getDocument(); - MediaActivity.this.onItemClick(i, view, message, 0); - } - } - }); - listView.setOnScrollListener(new AbsListView.OnScrollListener() { - @Override - public void onScrollStateChanged(AbsListView view, int scrollState) { - if (scrollState == SCROLL_STATE_TOUCH_SCROLL && searching && searchWas) { - AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus()); - } - scrolling = scrollState != SCROLL_STATE_IDLE; - } - - @Override - public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - if (searching && searchWas) { + selectedMode = 1; + switchToCurrentSelectedMode(); + } else if (id == delete) { + if (getParentActivity() == null) { return; } - if (visibleItemCount != 0 && firstVisibleItem + visibleItemCount > totalItemCount - 2 && !sharedMediaData[selectedMode].loading && !sharedMediaData[selectedMode].endReached) { - sharedMediaData[selectedMode].loading = true; - int type; - if (selectedMode == 0) { - type = SharedMediaQuery.MEDIA_PHOTOVIDEO; - } else if (selectedMode == 1) { - type = SharedMediaQuery.MEDIA_FILE; - } else { - type = SharedMediaQuery.MEDIA_AUDIO; + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setMessage(LocaleController.formatString("AreYouSureDeleteMessages", R.string.AreYouSureDeleteMessages, LocaleController.formatPluralString("items", selectedFiles.size()))); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + ArrayList ids = new ArrayList<>(selectedFiles.keySet()); + ArrayList random_ids = null; + TLRPC.EncryptedChat currentEncryptedChat = null; + if ((int) dialog_id == 0) { + currentEncryptedChat = MessagesController.getInstance().getEncryptedChat((int) (dialog_id >> 32)); + } + if (currentEncryptedChat != null) { + random_ids = new ArrayList<>(); + for (HashMap.Entry entry : selectedFiles.entrySet()) { + MessageObject msg = entry.getValue(); + if (msg.messageOwner.random_id != 0 && msg.type != 10) { + random_ids.add(msg.messageOwner.random_id); + } + } + } + MessagesController.getInstance().deleteMessages(ids, random_ids, currentEncryptedChat); + actionBar.hideActionMode(); + selectedFiles.clear(); } - SharedMediaQuery.loadMedia(dialog_id, 0, 50, sharedMediaData[selectedMode].max_id, type, !sharedMediaData[selectedMode].cacheEndReached, classGuid); - } - } - }); - listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { - @Override - public boolean onItemLongClick(AdapterView parent, View view, int i, long id) { - if (selectedMode == 1 && view instanceof SharedDocumentCell) { - SharedDocumentCell cell = (SharedDocumentCell) view; - MessageObject message = cell.getDocument(); - return MediaActivity.this.onItemLongClick(message, view, 0); - } - return false; - } - }); + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } else if (id == forward) { + Bundle args = new Bundle(); + args.putBoolean("onlySelect", true); + args.putBoolean("serverOnly", true); + MessagesActivity fragment = new MessagesActivity(args); + fragment.setDelegate(new MessagesActivity.MessagesActivityDelegate() { + @Override + public void didSelectDialog(MessagesActivity fragment, long did, boolean param) { + int lower_part = (int) did; + if (lower_part != 0) { + Bundle args = new Bundle(); + args.putBoolean("scrollToTopOnResume", true); + if (lower_part > 0) { + args.putInt("user_id", lower_part); + } else if (lower_part < 0) { + args.putInt("chat_id", -lower_part); + } - for (int a = 0; a < 6; a++) { - cellCache.add(new SharedPhotoVideoCell(getParentActivity())); + ArrayList fmessages = new ArrayList<>(); + ArrayList ids = new ArrayList<>(selectedFiles.keySet()); + Collections.sort(ids); + for (Integer id : ids) { + if (id > 0) { + fmessages.add(selectedFiles.get(id)); + } + } + selectedFiles.clear(); + actionBar.hideActionMode(); + + NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); + ChatActivity chatActivity = new ChatActivity(args); + presentFragment(chatActivity, true); + chatActivity.showReplyPanel(true, null, fmessages, null, false, false); + + if (!AndroidUtilities.isTablet()) { + removeSelfFromStack(); + Activity parentActivity = getParentActivity(); + if (parentActivity == null) { + parentActivity = chatActivity.getParentActivity(); + } + if (parentActivity != null) { + parentActivity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); + } + } + } else { + fragment.finishFragment(); + } + } + }); + presentFragment(fragment); + } + } + }); + + selectedFiles.clear(); + actionModeViews.clear(); + + final ActionBarMenu menu = actionBar.createMenu(); + searchItem = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() { + @Override + public void onSearchExpand() { + dropDownContainer.setVisibility(View.GONE); + searching = true; } - emptyView = new LinearLayout(getParentActivity()); - emptyView.setOrientation(LinearLayout.VERTICAL); - emptyView.setGravity(Gravity.CENTER); - emptyView.setVisibility(View.GONE); - emptyView.setBackgroundColor(0xfff0f0f0); - frameLayout.addView(emptyView); - layoutParams = (FrameLayout.LayoutParams) emptyView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - emptyView.setLayoutParams(layoutParams); - emptyView.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - return true; - } - }); + @Override + public boolean onSearchCollapse() { + dropDownContainer.setVisibility(View.VISIBLE); + documentsSearchAdapter.searchDocuments(null); + searching = false; + searchWas = false; + switchToCurrentSelectedMode(); - emptyImageView = new ImageView(getParentActivity()); - emptyView.addView(emptyImageView); - layoutParams1 = (LinearLayout.LayoutParams) emptyImageView.getLayoutParams(); - layoutParams1.width = LinearLayout.LayoutParams.WRAP_CONTENT; - layoutParams1.height = LinearLayout.LayoutParams.WRAP_CONTENT; - emptyImageView.setLayoutParams(layoutParams1); - - emptyTextView = new TextView(getParentActivity()); - emptyTextView.setTextColor(0xff8a8a8a); - emptyTextView.setGravity(Gravity.CENTER); - emptyTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17); - emptyTextView.setPadding(AndroidUtilities.dp(40), 0, AndroidUtilities.dp(40), AndroidUtilities.dp(128)); - emptyView.addView(emptyTextView); - layoutParams1 = (LinearLayout.LayoutParams) emptyTextView.getLayoutParams(); - layoutParams1.topMargin = AndroidUtilities.dp(24); - layoutParams1.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams1.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams1.gravity = Gravity.CENTER; - emptyTextView.setLayoutParams(layoutParams1); - - progressView = new LinearLayout(getParentActivity()); - progressView.setGravity(Gravity.CENTER); - progressView.setOrientation(LinearLayout.VERTICAL); - progressView.setVisibility(View.GONE); - progressView.setBackgroundColor(0xfff0f0f0); - frameLayout.addView(progressView); - layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - progressView.setLayoutParams(layoutParams); - - ProgressBar progressBar = new ProgressBar(getParentActivity()); - progressView.addView(progressBar); - layoutParams1 = (LinearLayout.LayoutParams) progressBar.getLayoutParams(); - layoutParams1.width = LinearLayout.LayoutParams.WRAP_CONTENT; - layoutParams1.height = LinearLayout.LayoutParams.WRAP_CONTENT; - progressBar.setLayoutParams(layoutParams1); - - switchToCurrentSelectedMode(); - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); + return true; } + + @Override + public void onTextChanged(EditText editText) { + if (documentsSearchAdapter == null) { + return; + } + String text = editText.getText().toString(); + if (text.length() != 0) { + searchWas = true; + switchToCurrentSelectedMode(); + } + documentsSearchAdapter.searchDocuments(text); + } + }); + searchItem.getSearchField().setHint(LocaleController.getString("Search", R.string.Search)); + searchItem.setVisibility(View.GONE); + + dropDownContainer = new ActionBarMenuItem(context, menu, R.drawable.bar_selector); + dropDownContainer.setSubMenuOpenSide(1); + dropDownContainer.addSubItem(shared_media_item, LocaleController.getString("SharedMediaTitle", R.string.SharedMediaTitle), 0); + dropDownContainer.addSubItem(files_item, LocaleController.getString("DocumentsTitle", R.string.DocumentsTitle), 0); + actionBar.addView(dropDownContainer); + FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) dropDownContainer.getLayoutParams(); + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.rightMargin = AndroidUtilities.dp(40); + layoutParams.leftMargin = AndroidUtilities.isTablet() ? AndroidUtilities.dp(64) : AndroidUtilities.dp(56); + layoutParams.gravity = Gravity.TOP | Gravity.LEFT; + dropDownContainer.setLayoutParams(layoutParams); + dropDownContainer.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + dropDownContainer.toggleSubMenu(); + } + }); + + dropDown = new TextView(context); + dropDown.setGravity(Gravity.LEFT); + dropDown.setSingleLine(true); + dropDown.setLines(1); + dropDown.setMaxLines(1); + dropDown.setEllipsize(TextUtils.TruncateAt.END); + dropDown.setTextColor(0xffffffff); + dropDown.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); + dropDown.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_arrow_drop_down, 0); + dropDown.setCompoundDrawablePadding(AndroidUtilities.dp(4)); + dropDown.setPadding(0, 0, AndroidUtilities.dp(10), 0); + dropDownContainer.addView(dropDown); + layoutParams = (FrameLayout.LayoutParams) dropDown.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.leftMargin = AndroidUtilities.dp(16); + layoutParams.gravity = Gravity.CENTER_VERTICAL; + dropDown.setLayoutParams(layoutParams); + + final ActionBarMenu actionMode = actionBar.createActionMode(); + actionModeViews.add(actionMode.addItem(-2, R.drawable.ic_ab_back_grey, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); + + selectedMessagesCountTextView = new TextView(actionMode.getContext()); + selectedMessagesCountTextView.setTextSize(18); + selectedMessagesCountTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); + selectedMessagesCountTextView.setTextColor(0xff737373); + selectedMessagesCountTextView.setSingleLine(true); + selectedMessagesCountTextView.setLines(1); + selectedMessagesCountTextView.setEllipsize(TextUtils.TruncateAt.END); + selectedMessagesCountTextView.setPadding(AndroidUtilities.dp(11), 0, 0, AndroidUtilities.dp(2)); + selectedMessagesCountTextView.setGravity(Gravity.CENTER_VERTICAL); + selectedMessagesCountTextView.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + actionMode.addView(selectedMessagesCountTextView); + LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) selectedMessagesCountTextView.getLayoutParams(); + layoutParams1.weight = 1; + layoutParams1.width = 0; + layoutParams1.height = LinearLayout.LayoutParams.MATCH_PARENT; + selectedMessagesCountTextView.setLayoutParams(layoutParams1); + + if ((int) dialog_id != 0) { + actionModeViews.add(actionMode.addItem(forward, R.drawable.ic_ab_fwd_forward, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); } + actionModeViews.add(actionMode.addItem(delete, R.drawable.ic_ab_fwd_delete, R.drawable.bar_selector_mode, null, AndroidUtilities.dp(54))); + + photoVideoAdapter = new SharedPhotoVideoAdapter(context); + documentsAdapter = new SharedDocumentsAdapter(context); + documentsSearchAdapter = new DocumentsSearchAdapter(context); + + FrameLayout frameLayout; + fragmentView = frameLayout = new FrameLayout(context); + + listView = new SectionsListView(context); + listView.setDivider(null); + listView.setDividerHeight(0); + listView.setDrawSelectorOnTop(true); + listView.setClipToPadding(false); + frameLayout.addView(listView); + layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.gravity = Gravity.TOP; + listView.setLayoutParams(layoutParams); + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, final int i, long l) { + if (selectedMode == 1 && view instanceof SharedDocumentCell) { + SharedDocumentCell cell = (SharedDocumentCell) view; + MessageObject message = cell.getDocument(); + MediaActivity.this.onItemClick(i, view, message, 0); + } + } + }); + listView.setOnScrollListener(new AbsListView.OnScrollListener() { + @Override + public void onScrollStateChanged(AbsListView view, int scrollState) { + if (scrollState == SCROLL_STATE_TOUCH_SCROLL && searching && searchWas) { + AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus()); + } + scrolling = scrollState != SCROLL_STATE_IDLE; + } + + @Override + public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + if (searching && searchWas) { + return; + } + if (visibleItemCount != 0 && firstVisibleItem + visibleItemCount > totalItemCount - 2 && !sharedMediaData[selectedMode].loading && !sharedMediaData[selectedMode].endReached) { + sharedMediaData[selectedMode].loading = true; + int type; + if (selectedMode == 0) { + type = SharedMediaQuery.MEDIA_PHOTOVIDEO; + } else if (selectedMode == 1) { + type = SharedMediaQuery.MEDIA_FILE; + } else { + type = SharedMediaQuery.MEDIA_AUDIO; + } + SharedMediaQuery.loadMedia(dialog_id, 0, 50, sharedMediaData[selectedMode].max_id, type, !sharedMediaData[selectedMode].cacheEndReached, classGuid); + } + } + }); + listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { + @Override + public boolean onItemLongClick(AdapterView parent, View view, int i, long id) { + if (selectedMode == 1 && view instanceof SharedDocumentCell) { + SharedDocumentCell cell = (SharedDocumentCell) view; + MessageObject message = cell.getDocument(); + return MediaActivity.this.onItemLongClick(message, view, 0); + } + return false; + } + }); + + for (int a = 0; a < 6; a++) { + cellCache.add(new SharedPhotoVideoCell(context)); + } + + emptyView = new LinearLayout(context); + emptyView.setOrientation(LinearLayout.VERTICAL); + emptyView.setGravity(Gravity.CENTER); + emptyView.setVisibility(View.GONE); + emptyView.setBackgroundColor(0xfff0f0f0); + frameLayout.addView(emptyView); + layoutParams = (FrameLayout.LayoutParams) emptyView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + emptyView.setLayoutParams(layoutParams); + emptyView.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + + emptyImageView = new ImageView(context); + emptyView.addView(emptyImageView); + layoutParams1 = (LinearLayout.LayoutParams) emptyImageView.getLayoutParams(); + layoutParams1.width = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams1.height = LinearLayout.LayoutParams.WRAP_CONTENT; + emptyImageView.setLayoutParams(layoutParams1); + + emptyTextView = new TextView(context); + emptyTextView.setTextColor(0xff8a8a8a); + emptyTextView.setGravity(Gravity.CENTER); + emptyTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17); + emptyTextView.setPadding(AndroidUtilities.dp(40), 0, AndroidUtilities.dp(40), AndroidUtilities.dp(128)); + emptyView.addView(emptyTextView); + layoutParams1 = (LinearLayout.LayoutParams) emptyTextView.getLayoutParams(); + layoutParams1.topMargin = AndroidUtilities.dp(24); + layoutParams1.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams1.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams1.gravity = Gravity.CENTER; + emptyTextView.setLayoutParams(layoutParams1); + + progressView = new LinearLayout(context); + progressView.setGravity(Gravity.CENTER); + progressView.setOrientation(LinearLayout.VERTICAL); + progressView.setVisibility(View.GONE); + progressView.setBackgroundColor(0xfff0f0f0); + frameLayout.addView(progressView); + layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + progressView.setLayoutParams(layoutParams); + + ProgressBar progressBar = new ProgressBar(context); + progressView.addView(progressBar); + layoutParams1 = (LinearLayout.LayoutParams) progressBar.getLayoutParams(); + layoutParams1.width = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams1.height = LinearLayout.LayoutParams.WRAP_CONTENT; + progressBar.setLayoutParams(layoutParams1); + + switchToCurrentSelectedMode(); + return fragmentView; } @@ -742,7 +736,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No object.viewX = coords[0]; object.viewY = coords[1] - AndroidUtilities.statusBarHeight; object.parentView = listView; - object.imageReceiver = imageView.imageReceiver; + object.imageReceiver = imageView.getImageReceiver(); object.thumb = object.imageReceiver.getBitmap(); return object; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/MessagesActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/MessagesActivity.java index 1f5155ffa..4d56274f6 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/MessagesActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/MessagesActivity.java @@ -11,6 +11,7 @@ package org.telegram.ui; import android.animation.ObjectAnimator; import android.animation.StateListAnimator; import android.app.AlertDialog; +import android.content.Context; import android.content.DialogInterface; import android.content.res.Configuration; import android.graphics.Outline; @@ -155,459 +156,456 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - searching = false; - searchWas = false; + public View createView(Context context, LayoutInflater inflater) { + searching = false; + searchWas = false; - ActionBarMenu menu = actionBar.createMenu(); - if (!onlySelect && searchString == null) { - passcodeItem = menu.addItem(passcode_menu_item, R.drawable.lock_close); + ActionBarMenu menu = actionBar.createMenu(); + if (!onlySelect && searchString == null) { + passcodeItem = menu.addItem(passcode_menu_item, R.drawable.lock_close); + updatePasscodeButton(); + } + ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() { + @Override + public void onSearchExpand() { + searching = true; + if (messagesListView != null) { + if (searchString != null) { + messagesListView.setEmptyView(progressView); + searchEmptyView.setVisibility(View.INVISIBLE); + } else { + messagesListView.setEmptyView(searchEmptyView); + progressView.setVisibility(View.INVISIBLE); + } + emptyView.setVisibility(View.INVISIBLE); + if (!onlySelect) { + floatingButton.setVisibility(View.GONE); + } + } updatePasscodeButton(); } - ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() { - @Override - public void onSearchExpand() { - searching = true; - if (messagesListView != null) { - if (searchString != null) { - messagesListView.setEmptyView(progressView); - searchEmptyView.setVisibility(View.INVISIBLE); - } else { - messagesListView.setEmptyView(searchEmptyView); - progressView.setVisibility(View.INVISIBLE); - } - emptyView.setVisibility(View.INVISIBLE); - if (!onlySelect) { - floatingButton.setVisibility(View.GONE); - } - } - updatePasscodeButton(); - } - @Override - public boolean onSearchCollapse() { - if (searchString != null) { - finishFragment(); - return false; - } - searching = false; - searchWas = false; - if (messagesListView != null) { - if (MessagesController.getInstance().loadingDialogs && MessagesController.getInstance().dialogs.isEmpty()) { - searchEmptyView.setVisibility(View.INVISIBLE); - emptyView.setVisibility(View.INVISIBLE); - progressView.setVisibility(View.VISIBLE); - messagesListView.setEmptyView(progressView); - } else { - messagesListView.setEmptyView(emptyView); - searchEmptyView.setVisibility(View.INVISIBLE); - progressView.setVisibility(View.INVISIBLE); - } - if (!onlySelect) { - floatingButton.setVisibility(View.VISIBLE); - floatingHidden = true; - ViewProxy.setTranslationY(floatingButton, AndroidUtilities.dp(100)); - hideFloatingButton(false); - } - if (messagesListView.getAdapter() != dialogsAdapter) { - messagesListView.setAdapter(dialogsAdapter); - dialogsAdapter.notifyDataSetChanged(); - } - } - if (dialogsSearchAdapter != null) { - dialogsSearchAdapter.searchDialogs(null, false); - } - updatePasscodeButton(); - return true; - } - - @Override - public void onTextChanged(EditText editText) { - String text = editText.getText().toString(); - if (text.length() != 0) { - searchWas = true; - if (dialogsSearchAdapter != null) { - messagesListView.setAdapter(dialogsSearchAdapter); - dialogsSearchAdapter.notifyDataSetChanged(); - } - if (searchEmptyView != null && messagesListView.getEmptyView() == emptyView) { - messagesListView.setEmptyView(searchEmptyView); - emptyView.setVisibility(View.INVISIBLE); - progressView.setVisibility(View.INVISIBLE); - } - } - if (dialogsSearchAdapter != null) { - dialogsSearchAdapter.searchDialogs(text, serverOnly); - } - } - }); - item.getSearchField().setHint(LocaleController.getString("Search", R.string.Search)); - if (onlySelect) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setTitle(LocaleController.getString("SelectChat", R.string.SelectChat)); - } else { + @Override + public boolean onSearchCollapse() { if (searchString != null) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - } else { - actionBar.setBackButtonDrawable(new MenuDrawable()); + finishFragment(); + return false; } - actionBar.setTitle(LocaleController.getString("AppName", R.string.AppName)); - } - actionBar.setAllowOverlayTitle(true); - - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - if (onlySelect) { - finishFragment(); - } else if (parentLayout != null) { - parentLayout.getDrawerLayoutContainer().openDrawer(false); - } - } else if (id == passcode_menu_item) { - UserConfig.appLocked = !UserConfig.appLocked; - UserConfig.saveConfig(false); - updatePasscodeButton(); - } - } - }); - - fragmentView = inflater.inflate(R.layout.messages_list, null, false); - - if (searchString == null) { - dialogsAdapter = new DialogsAdapter(getParentActivity(), serverOnly); - if (AndroidUtilities.isTablet() && openedDialogId != 0) { - dialogsAdapter.setOpenedDialogId(openedDialogId); - } - } - int type = 0; - if (searchString != null) { - type = 2; - } else if (!onlySelect) { - type = 1; - } - dialogsSearchAdapter = new DialogsSearchAdapter(getParentActivity(), type); - dialogsSearchAdapter.setDelegate(new DialogsSearchAdapter.MessagesActivitySearchAdapterDelegate() { - @Override - public void searchStateChanged(boolean search) { - if (searching && searchWas && messagesListView != null) { - progressView.setVisibility(search ? View.VISIBLE : View.INVISIBLE); - searchEmptyView.setVisibility(search ? View.INVISIBLE : View.VISIBLE); - messagesListView.setEmptyView(search ? progressView : searchEmptyView); - } - } - }); - - messagesListView = (ListView)fragmentView.findViewById(R.id.messages_list_view); - if (dialogsAdapter != null) { - messagesListView.setAdapter(dialogsAdapter); - } - if (Build.VERSION.SDK_INT >= 11) { - messagesListView.setVerticalScrollbarPosition(LocaleController.isRTL ? ListView.SCROLLBAR_POSITION_LEFT : ListView.SCROLLBAR_POSITION_RIGHT); - } - - progressView = fragmentView.findViewById(R.id.progressLayout); - searchEmptyView = fragmentView.findViewById(R.id.search_empty_view); - searchEmptyView.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - return true; - } - }); - emptyView = fragmentView.findViewById(R.id.list_empty_view); - emptyView.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - return true; - } - }); - - - TextView textView = (TextView)fragmentView.findViewById(R.id.list_empty_view_text1); - textView.setText(LocaleController.getString("NoChats", R.string.NoChats)); - textView = (TextView)fragmentView.findViewById(R.id.list_empty_view_text2); - String help = LocaleController.getString("NoChatsHelp", R.string.NoChatsHelp); - if (AndroidUtilities.isTablet() && !AndroidUtilities.isSmallTablet()) { - help = help.replace("\n", " "); - } - textView.setText(help); - textView = (TextView)fragmentView.findViewById(R.id.search_empty_text); - textView.setText(LocaleController.getString("NoResult", R.string.NoResult)); - - floatingButton = (ImageView) fragmentView.findViewById(R.id.floating_button); - floatingButton.setVisibility(onlySelect ? View.GONE : View.VISIBLE); - floatingButton.setScaleType(ImageView.ScaleType.CENTER); - if (Build.VERSION.SDK_INT >= 21) { - StateListAnimator animator = new StateListAnimator(); - animator.addState(new int[] {android.R.attr.state_pressed}, ObjectAnimator.ofFloat(floatingButton, "translationZ", AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200)); - animator.addState(new int[] {}, ObjectAnimator.ofFloat(floatingButton, "translationZ", AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200)); - floatingButton.setStateListAnimator(animator); - floatingButton.setOutlineProvider(new ViewOutlineProvider() { - @Override - public void getOutline(View view, Outline outline) { - outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56)); - } - }); - } - FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams)floatingButton.getLayoutParams(); - layoutParams.leftMargin = LocaleController.isRTL ? AndroidUtilities.dp(14) : 0; - layoutParams.rightMargin = LocaleController.isRTL ? 0 : AndroidUtilities.dp(14); - layoutParams.gravity = (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.BOTTOM; - floatingButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - Bundle args = new Bundle(); - args.putBoolean("destroyAfterSelect", true); - presentFragment(new ContactsActivity(args)); - } - }); - - if (MessagesController.getInstance().loadingDialogs && MessagesController.getInstance().dialogs.isEmpty()) { - searchEmptyView.setVisibility(View.INVISIBLE); - emptyView.setVisibility(View.INVISIBLE); - progressView.setVisibility(View.VISIBLE); - messagesListView.setEmptyView(progressView); - } else { - messagesListView.setEmptyView(emptyView); - searchEmptyView.setVisibility(View.INVISIBLE); - progressView.setVisibility(View.INVISIBLE); - } - - messagesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, int i, long l) { - if (messagesListView == null || messagesListView.getAdapter() == null) { - return; - } - long dialog_id = 0; - int message_id = 0; - BaseFragmentAdapter adapter = (BaseFragmentAdapter) messagesListView.getAdapter(); - if (adapter == dialogsAdapter) { - TLRPC.TL_dialog dialog = dialogsAdapter.getItem(i); - if (dialog == null) { - return; - } - dialog_id = dialog.id; - } else if (adapter == dialogsSearchAdapter) { - Object obj = dialogsSearchAdapter.getItem(i); - if (obj instanceof TLRPC.User) { - dialog_id = ((TLRPC.User) obj).id; - if (dialogsSearchAdapter.isGlobalSearch(i)) { - ArrayList users = new ArrayList<>(); - users.add((TLRPC.User)obj); - MessagesController.getInstance().putUsers(users, false); - MessagesStorage.getInstance().putUsersAndChats(users, null, false, true); - } - } else if (obj instanceof TLRPC.Chat) { - if (((TLRPC.Chat) obj).id > 0) { - dialog_id = -((TLRPC.Chat) obj).id; - } else { - dialog_id = AndroidUtilities.makeBroadcastId(((TLRPC.Chat) obj).id); - } - } else if (obj instanceof TLRPC.EncryptedChat) { - dialog_id = ((long)((TLRPC.EncryptedChat) obj).id) << 32; - } else if (obj instanceof MessageObject) { - MessageObject messageObject = (MessageObject)obj; - dialog_id = messageObject.getDialogId(); - message_id = messageObject.getId(); - dialogsSearchAdapter.addHashtagsFromMessage(dialogsSearchAdapter.getLastSearchString()); - } else if (obj instanceof String) { - actionBar.openSearchField((String) obj); - } - } - - if (dialog_id == 0) { - return; - } - - if (onlySelect) { - didSelectResult(dialog_id, true, false); + searching = false; + searchWas = false; + if (messagesListView != null) { + if (MessagesController.getInstance().loadingDialogs && MessagesController.getInstance().dialogs.isEmpty()) { + searchEmptyView.setVisibility(View.INVISIBLE); + emptyView.setVisibility(View.INVISIBLE); + progressView.setVisibility(View.VISIBLE); + messagesListView.setEmptyView(progressView); } else { - Bundle args = new Bundle(); - int lower_part = (int)dialog_id; - int high_id = (int)(dialog_id >> 32); - if (lower_part != 0) { - if (high_id == 1) { - args.putInt("chat_id", lower_part); - } else { - if (lower_part > 0) { - args.putInt("user_id", lower_part); - } else if (lower_part < 0) { - args.putInt("chat_id", -lower_part); - } - } - } else { - args.putInt("enc_id", high_id); - } - if (message_id != 0) { - args.putInt("message_id", message_id); - } else { - if (actionBar != null) { - actionBar.closeSearchField(); - } - } - if (AndroidUtilities.isTablet()) { - if (openedDialogId == dialog_id) { - return; - } - if (dialogsAdapter != null) { - dialogsAdapter.setOpenedDialogId(openedDialogId = dialog_id); - updateVisibleRows(MessagesController.UPDATE_MASK_SELECT_DIALOG); - } - } - if (searchString != null) { - NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); - presentFragment(new ChatActivity(args)); - } else { - presentFragment(new ChatActivity(args)); - } + messagesListView.setEmptyView(emptyView); + searchEmptyView.setVisibility(View.INVISIBLE); + progressView.setVisibility(View.INVISIBLE); + } + if (!onlySelect) { + floatingButton.setVisibility(View.VISIBLE); + floatingHidden = true; + ViewProxy.setTranslationY(floatingButton, AndroidUtilities.dp(100)); + hideFloatingButton(false); + } + if (messagesListView.getAdapter() != dialogsAdapter) { + messagesListView.setAdapter(dialogsAdapter); + dialogsAdapter.notifyDataSetChanged(); } } - }); - - messagesListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { - @Override - public boolean onItemLongClick(AdapterView adapterView, View view, int i, long l) { - if (onlySelect || searching && searchWas || getParentActivity() == null) { - if (searchWas && searching) { - BaseFragmentAdapter adapter = (BaseFragmentAdapter) messagesListView.getAdapter(); - if (adapter == dialogsSearchAdapter) { - Object item = adapter.getItem(i); - if (item instanceof String) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setMessage(LocaleController.getString("ClearSearch", R.string.ClearSearch)); - builder.setPositiveButton(LocaleController.getString("ClearButton", R.string.ClearButton).toUpperCase(), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - dialogsSearchAdapter.clearRecentHashtags(); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - return true; - } - } - } - return false; - } - TLRPC.TL_dialog dialog; - if (serverOnly) { - if (i >= MessagesController.getInstance().dialogsServerOnly.size()) { - return false; - } - dialog = MessagesController.getInstance().dialogsServerOnly.get(i); - } else { - if (i >= MessagesController.getInstance().dialogs.size()) { - return false; - } - dialog = MessagesController.getInstance().dialogs.get(i); - } - selectedDialog = dialog.id; - - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - - int lower_id = (int)selectedDialog; - int high_id = (int)(selectedDialog >> 32); - - final boolean isChat = lower_id < 0 && high_id != 1; - builder.setItems(new CharSequence[]{LocaleController.getString("ClearHistory", R.string.ClearHistory), - isChat ? LocaleController.getString("DeleteChat", R.string.DeleteChat) : LocaleController.getString("Delete", R.string.Delete)}, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, final int which) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - if (which == 0) { - builder.setMessage(LocaleController.getString("AreYouSureClearHistory", R.string.AreYouSureClearHistory)); - } else { - if (isChat) { - builder.setMessage(LocaleController.getString("AreYouSureDeleteAndExit", R.string.AreYouSureDeleteAndExit)); - } else { - builder.setMessage(LocaleController.getString("AreYouSureDeleteThisChat", R.string.AreYouSureDeleteThisChat)); - } - } - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - MessagesController.getInstance().deleteDialog(selectedDialog, 0, which == 0); - if (which != 0) { - if (isChat) { - MessagesController.getInstance().deleteUserFromChat((int) -selectedDialog, MessagesController.getInstance().getUser(UserConfig.getClientUserId()), null); - } - if (AndroidUtilities.isTablet()) { - NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats, selectedDialog); - } - } - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - return true; + if (dialogsSearchAdapter != null) { + dialogsSearchAdapter.searchDialogs(null, false); } - }); - - messagesListView.setOnScrollListener(new AbsListView.OnScrollListener() { - @Override - public void onScrollStateChanged(AbsListView absListView, int i) { - if (i == SCROLL_STATE_TOUCH_SCROLL && searching && searchWas) { - AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus()); - } - } - - @Override - public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - if (searching && searchWas) { - if (visibleItemCount > 0 && absListView.getLastVisiblePosition() == totalItemCount - 1 && !dialogsSearchAdapter.isMessagesSearchEndReached()) { - dialogsSearchAdapter.loadMoreSearchMessages(); - } - return; - } - if (visibleItemCount > 0) { - if (absListView.getLastVisiblePosition() == MessagesController.getInstance().dialogs.size() && !serverOnly || absListView.getLastVisiblePosition() == MessagesController.getInstance().dialogsServerOnly.size() && serverOnly) { - MessagesController.getInstance().loadDialogs(MessagesController.getInstance().dialogs.size(), MessagesController.getInstance().dialogsServerOnly.size(), 100, true); - } - } - - if (floatingButton.getVisibility() != View.GONE) { - final View topChild = absListView.getChildAt(0); - int firstViewTop = 0; - if (topChild != null) { - firstViewTop = topChild.getTop(); - } - boolean goingDown; - boolean changed = true; - if (prevPosition == firstVisibleItem) { - final int topDelta = prevTop - firstViewTop; - goingDown = firstViewTop < prevTop; - changed = Math.abs(topDelta) > 1; - } else { - goingDown = firstVisibleItem > prevPosition; - } - if (changed && scrollUpdated) { - hideFloatingButton(goingDown); - } - prevPosition = firstVisibleItem; - prevTop = firstViewTop; - scrollUpdated = true; - } - } - }); - - if (searchString != null) { - actionBar.openSearchField(searchString); + updatePasscodeButton(); + return true; } + + @Override + public void onTextChanged(EditText editText) { + String text = editText.getText().toString(); + if (text.length() != 0) { + searchWas = true; + if (dialogsSearchAdapter != null) { + messagesListView.setAdapter(dialogsSearchAdapter); + dialogsSearchAdapter.notifyDataSetChanged(); + } + if (searchEmptyView != null && messagesListView.getEmptyView() == emptyView) { + messagesListView.setEmptyView(searchEmptyView); + emptyView.setVisibility(View.INVISIBLE); + progressView.setVisibility(View.INVISIBLE); + } + } + if (dialogsSearchAdapter != null) { + dialogsSearchAdapter.searchDialogs(text, serverOnly); + } + } + }); + item.getSearchField().setHint(LocaleController.getString("Search", R.string.Search)); + if (onlySelect) { + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setTitle(LocaleController.getString("SelectChat", R.string.SelectChat)); } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); + if (searchString != null) { + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + } else { + actionBar.setBackButtonDrawable(new MenuDrawable()); + } + actionBar.setTitle(LocaleController.getString("AppName", R.string.AppName)); + } + actionBar.setAllowOverlayTitle(true); + + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + if (onlySelect) { + finishFragment(); + } else if (parentLayout != null) { + parentLayout.getDrawerLayoutContainer().openDrawer(false); + } + } else if (id == passcode_menu_item) { + UserConfig.appLocked = !UserConfig.appLocked; + UserConfig.saveConfig(false); + updatePasscodeButton(); + } + } + }); + + fragmentView = inflater.inflate(R.layout.messages_list, null, false); + + if (searchString == null) { + dialogsAdapter = new DialogsAdapter(context, serverOnly); + if (AndroidUtilities.isTablet() && openedDialogId != 0) { + dialogsAdapter.setOpenedDialogId(openedDialogId); } } + int type = 0; + if (searchString != null) { + type = 2; + } else if (!onlySelect) { + type = 1; + } + dialogsSearchAdapter = new DialogsSearchAdapter(context, type); + dialogsSearchAdapter.setDelegate(new DialogsSearchAdapter.MessagesActivitySearchAdapterDelegate() { + @Override + public void searchStateChanged(boolean search) { + if (searching && searchWas && messagesListView != null) { + progressView.setVisibility(search ? View.VISIBLE : View.INVISIBLE); + searchEmptyView.setVisibility(search ? View.INVISIBLE : View.VISIBLE); + messagesListView.setEmptyView(search ? progressView : searchEmptyView); + } + } + }); + + messagesListView = (ListView) fragmentView.findViewById(R.id.messages_list_view); + if (dialogsAdapter != null) { + messagesListView.setAdapter(dialogsAdapter); + } + if (Build.VERSION.SDK_INT >= 11) { + messagesListView.setVerticalScrollbarPosition(LocaleController.isRTL ? ListView.SCROLLBAR_POSITION_LEFT : ListView.SCROLLBAR_POSITION_RIGHT); + } + + progressView = fragmentView.findViewById(R.id.progressLayout); + searchEmptyView = fragmentView.findViewById(R.id.search_empty_view); + searchEmptyView.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + emptyView = fragmentView.findViewById(R.id.list_empty_view); + emptyView.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + + + TextView textView = (TextView) fragmentView.findViewById(R.id.list_empty_view_text1); + textView.setText(LocaleController.getString("NoChats", R.string.NoChats)); + textView = (TextView) fragmentView.findViewById(R.id.list_empty_view_text2); + String help = LocaleController.getString("NoChatsHelp", R.string.NoChatsHelp); + if (AndroidUtilities.isTablet() && !AndroidUtilities.isSmallTablet()) { + help = help.replace("\n", " "); + } + textView.setText(help); + textView = (TextView) fragmentView.findViewById(R.id.search_empty_text); + textView.setText(LocaleController.getString("NoResult", R.string.NoResult)); + + floatingButton = (ImageView) fragmentView.findViewById(R.id.floating_button); + floatingButton.setVisibility(onlySelect ? View.GONE : View.VISIBLE); + floatingButton.setScaleType(ImageView.ScaleType.CENTER); + if (Build.VERSION.SDK_INT >= 21) { + StateListAnimator animator = new StateListAnimator(); + animator.addState(new int[]{android.R.attr.state_pressed}, ObjectAnimator.ofFloat(floatingButton, "translationZ", AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200)); + animator.addState(new int[]{}, ObjectAnimator.ofFloat(floatingButton, "translationZ", AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200)); + floatingButton.setStateListAnimator(animator); + floatingButton.setOutlineProvider(new ViewOutlineProvider() { + @Override + public void getOutline(View view, Outline outline) { + outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56)); + } + }); + } + FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) floatingButton.getLayoutParams(); + layoutParams.leftMargin = LocaleController.isRTL ? AndroidUtilities.dp(14) : 0; + layoutParams.rightMargin = LocaleController.isRTL ? 0 : AndroidUtilities.dp(14); + layoutParams.gravity = (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.BOTTOM; + floatingButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + Bundle args = new Bundle(); + args.putBoolean("destroyAfterSelect", true); + presentFragment(new ContactsActivity(args)); + } + }); + + if (MessagesController.getInstance().loadingDialogs && MessagesController.getInstance().dialogs.isEmpty()) { + searchEmptyView.setVisibility(View.INVISIBLE); + emptyView.setVisibility(View.INVISIBLE); + progressView.setVisibility(View.VISIBLE); + messagesListView.setEmptyView(progressView); + } else { + messagesListView.setEmptyView(emptyView); + searchEmptyView.setVisibility(View.INVISIBLE); + progressView.setVisibility(View.INVISIBLE); + } + + messagesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, int i, long l) { + if (messagesListView == null || messagesListView.getAdapter() == null) { + return; + } + long dialog_id = 0; + int message_id = 0; + BaseFragmentAdapter adapter = (BaseFragmentAdapter) messagesListView.getAdapter(); + if (adapter == dialogsAdapter) { + TLRPC.TL_dialog dialog = dialogsAdapter.getItem(i); + if (dialog == null) { + return; + } + dialog_id = dialog.id; + } else if (adapter == dialogsSearchAdapter) { + Object obj = dialogsSearchAdapter.getItem(i); + if (obj instanceof TLRPC.User) { + dialog_id = ((TLRPC.User) obj).id; + if (dialogsSearchAdapter.isGlobalSearch(i)) { + ArrayList users = new ArrayList<>(); + users.add((TLRPC.User) obj); + MessagesController.getInstance().putUsers(users, false); + MessagesStorage.getInstance().putUsersAndChats(users, null, false, true); + } + } else if (obj instanceof TLRPC.Chat) { + if (((TLRPC.Chat) obj).id > 0) { + dialog_id = -((TLRPC.Chat) obj).id; + } else { + dialog_id = AndroidUtilities.makeBroadcastId(((TLRPC.Chat) obj).id); + } + } else if (obj instanceof TLRPC.EncryptedChat) { + dialog_id = ((long) ((TLRPC.EncryptedChat) obj).id) << 32; + } else if (obj instanceof MessageObject) { + MessageObject messageObject = (MessageObject) obj; + dialog_id = messageObject.getDialogId(); + message_id = messageObject.getId(); + dialogsSearchAdapter.addHashtagsFromMessage(dialogsSearchAdapter.getLastSearchString()); + } else if (obj instanceof String) { + actionBar.openSearchField((String) obj); + } + } + + if (dialog_id == 0) { + return; + } + + if (onlySelect) { + didSelectResult(dialog_id, true, false); + } else { + Bundle args = new Bundle(); + int lower_part = (int) dialog_id; + int high_id = (int) (dialog_id >> 32); + if (lower_part != 0) { + if (high_id == 1) { + args.putInt("chat_id", lower_part); + } else { + if (lower_part > 0) { + args.putInt("user_id", lower_part); + } else if (lower_part < 0) { + args.putInt("chat_id", -lower_part); + } + } + } else { + args.putInt("enc_id", high_id); + } + if (message_id != 0) { + args.putInt("message_id", message_id); + } else { + if (actionBar != null) { + actionBar.closeSearchField(); + } + } + if (AndroidUtilities.isTablet()) { + if (openedDialogId == dialog_id) { + return; + } + if (dialogsAdapter != null) { + dialogsAdapter.setOpenedDialogId(openedDialogId = dialog_id); + updateVisibleRows(MessagesController.UPDATE_MASK_SELECT_DIALOG); + } + } + if (searchString != null) { + NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); + presentFragment(new ChatActivity(args)); + } else { + presentFragment(new ChatActivity(args)); + } + } + } + }); + + messagesListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { + @Override + public boolean onItemLongClick(AdapterView adapterView, View view, int i, long l) { + if (onlySelect || searching && searchWas || getParentActivity() == null) { + if (searchWas && searching) { + BaseFragmentAdapter adapter = (BaseFragmentAdapter) messagesListView.getAdapter(); + if (adapter == dialogsSearchAdapter) { + Object item = adapter.getItem(i); + if (item instanceof String) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + builder.setMessage(LocaleController.getString("ClearSearch", R.string.ClearSearch)); + builder.setPositiveButton(LocaleController.getString("ClearButton", R.string.ClearButton).toUpperCase(), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + dialogsSearchAdapter.clearRecentHashtags(); + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + return true; + } + } + } + return false; + } + TLRPC.TL_dialog dialog; + if (serverOnly) { + if (i >= MessagesController.getInstance().dialogsServerOnly.size()) { + return false; + } + dialog = MessagesController.getInstance().dialogsServerOnly.get(i); + } else { + if (i >= MessagesController.getInstance().dialogs.size()) { + return false; + } + dialog = MessagesController.getInstance().dialogs.get(i); + } + selectedDialog = dialog.id; + + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + + int lower_id = (int) selectedDialog; + int high_id = (int) (selectedDialog >> 32); + + final boolean isChat = lower_id < 0 && high_id != 1; + builder.setItems(new CharSequence[]{LocaleController.getString("ClearHistory", R.string.ClearHistory), + isChat ? LocaleController.getString("DeleteChat", R.string.DeleteChat) : LocaleController.getString("Delete", R.string.Delete)}, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, final int which) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + if (which == 0) { + builder.setMessage(LocaleController.getString("AreYouSureClearHistory", R.string.AreYouSureClearHistory)); + } else { + if (isChat) { + builder.setMessage(LocaleController.getString("AreYouSureDeleteAndExit", R.string.AreYouSureDeleteAndExit)); + } else { + builder.setMessage(LocaleController.getString("AreYouSureDeleteThisChat", R.string.AreYouSureDeleteThisChat)); + } + } + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + if (which != 0) { + if (isChat) { + MessagesController.getInstance().deleteUserFromChat((int) -selectedDialog, MessagesController.getInstance().getUser(UserConfig.getClientUserId()), null); + } else { + MessagesController.getInstance().deleteDialog(selectedDialog, 0, false); + } + if (AndroidUtilities.isTablet()) { + NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats, selectedDialog); + } + } else { + MessagesController.getInstance().deleteDialog(selectedDialog, 0, true); + } + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + return true; + } + }); + + messagesListView.setOnScrollListener(new AbsListView.OnScrollListener() { + @Override + public void onScrollStateChanged(AbsListView absListView, int i) { + if (i == SCROLL_STATE_TOUCH_SCROLL && searching && searchWas) { + AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus()); + } + } + + @Override + public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + if (searching && searchWas) { + if (visibleItemCount > 0 && absListView.getLastVisiblePosition() == totalItemCount - 1 && !dialogsSearchAdapter.isMessagesSearchEndReached()) { + dialogsSearchAdapter.loadMoreSearchMessages(); + } + return; + } + if (visibleItemCount > 0) { + if (absListView.getLastVisiblePosition() == MessagesController.getInstance().dialogs.size() && !serverOnly || absListView.getLastVisiblePosition() == MessagesController.getInstance().dialogsServerOnly.size() && serverOnly) { + MessagesController.getInstance().loadDialogs(MessagesController.getInstance().dialogs.size(), MessagesController.getInstance().dialogsServerOnly.size(), 100, true); + } + } + + if (floatingButton.getVisibility() != View.GONE) { + final View topChild = absListView.getChildAt(0); + int firstViewTop = 0; + if (topChild != null) { + firstViewTop = topChild.getTop(); + } + boolean goingDown; + boolean changed = true; + if (prevPosition == firstVisibleItem) { + final int topDelta = prevTop - firstViewTop; + goingDown = firstViewTop < prevTop; + changed = Math.abs(topDelta) > 1; + } else { + goingDown = firstVisibleItem > prevPosition; + } + if (changed && scrollUpdated) { + hideFloatingButton(goingDown); + } + prevPosition = firstVisibleItem; + prevTop = firstViewTop; + scrollUpdated = true; + } + } + }); + + if (searchString != null) { + actionBar.openSearchField(searchString); + } + return fragmentView; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/NotificationsSettingsActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/NotificationsSettingsActivity.java index 3bc8e8594..a8f3bfd52 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/NotificationsSettingsActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/NotificationsSettingsActivity.java @@ -156,391 +156,385 @@ public class NotificationsSettingsActivity extends BaseFragment implements Notif } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - actionBar.setTitle(LocaleController.getString("NotificationsAndSounds", R.string.NotificationsAndSounds)); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setAllowOverlayTitle(true); + actionBar.setTitle(LocaleController.getString("NotificationsAndSounds", R.string.NotificationsAndSounds)); + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); } - }); + } + }); - fragmentView = new FrameLayout(getParentActivity()); - FrameLayout frameLayout = (FrameLayout) fragmentView; + fragmentView = new FrameLayout(context); + FrameLayout frameLayout = (FrameLayout) fragmentView; - listView = new ListView(getParentActivity()); - listView.setDivider(null); - listView.setDividerHeight(0); - listView.setVerticalScrollBarEnabled(false); - frameLayout.addView(listView); - FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - listView.setLayoutParams(layoutParams); - listView.setAdapter(new ListAdapter(getParentActivity())); - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, final int i, long l) { - boolean enabled = false; - if (i == messageAlertRow || i == groupAlertRow) { + listView = new ListView(context); + listView.setDivider(null); + listView.setDividerHeight(0); + listView.setVerticalScrollBarEnabled(false); + frameLayout.addView(listView); + FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + listView.setLayoutParams(layoutParams); + listView.setAdapter(new ListAdapter(context)); + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, final int i, long l) { + boolean enabled = false; + if (i == messageAlertRow || i == groupAlertRow) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + if (i == messageAlertRow) { + enabled = preferences.getBoolean("EnableAll", true); + editor.putBoolean("EnableAll", !enabled); + } else if (i == groupAlertRow) { + enabled = preferences.getBoolean("EnableGroup", true); + editor.putBoolean("EnableGroup", !enabled); + } + editor.commit(); + updateServerNotificationsSettings(i == groupAlertRow); + } else if (i == messagePreviewRow || i == groupPreviewRow) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + if (i == messagePreviewRow) { + enabled = preferences.getBoolean("EnablePreviewAll", true); + editor.putBoolean("EnablePreviewAll", !enabled); + } else if (i == groupPreviewRow) { + enabled = preferences.getBoolean("EnablePreviewGroup", true); + editor.putBoolean("EnablePreviewGroup", !enabled); + } + editor.commit(); + updateServerNotificationsSettings(i == groupPreviewRow); + } else if (i == messageSoundRow || i == groupSoundRow) { + try { SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - if (i == messageAlertRow) { - enabled = preferences.getBoolean("EnableAll", true); - editor.putBoolean("EnableAll", !enabled); - } else if (i == groupAlertRow) { - enabled = preferences.getBoolean("EnableGroup", true); - editor.putBoolean("EnableGroup", !enabled); - } - editor.commit(); - updateServerNotificationsSettings(i == groupAlertRow); - } else if (i == messagePreviewRow || i == groupPreviewRow) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - if (i == messagePreviewRow) { - enabled = preferences.getBoolean("EnablePreviewAll", true); - editor.putBoolean("EnablePreviewAll", !enabled); - } else if (i == groupPreviewRow) { - enabled = preferences.getBoolean("EnablePreviewGroup", true); - editor.putBoolean("EnablePreviewGroup", !enabled); - } - editor.commit(); - updateServerNotificationsSettings(i == groupPreviewRow); - } else if (i == messageSoundRow || i == groupSoundRow) { - try { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - Intent tmpIntent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER); - tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION); - tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true); - tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); - Uri currentSound = null; + Intent tmpIntent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER); + tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION); + tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true); + tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); + Uri currentSound = null; - String defaultPath = null; - Uri defaultUri = Settings.System.DEFAULT_NOTIFICATION_URI; - if (defaultUri != null) { - defaultPath = defaultUri.getPath(); - } + String defaultPath = null; + Uri defaultUri = Settings.System.DEFAULT_NOTIFICATION_URI; + if (defaultUri != null) { + defaultPath = defaultUri.getPath(); + } - if (i == messageSoundRow) { - String path = preferences.getString("GlobalSoundPath", defaultPath); - if (path != null && !path.equals("NoSound")) { - if (path.equals(defaultPath)) { - currentSound = defaultUri; - } else { - currentSound = Uri.parse(path); - } - } - } else if (i == groupSoundRow) { - String path = preferences.getString("GroupSoundPath", defaultPath); - if (path != null && !path.equals("NoSound")) { - if (path.equals(defaultPath)) { - currentSound = defaultUri; - } else { - currentSound = Uri.parse(path); - } + if (i == messageSoundRow) { + String path = preferences.getString("GlobalSoundPath", defaultPath); + if (path != null && !path.equals("NoSound")) { + if (path.equals(defaultPath)) { + currentSound = defaultUri; + } else { + currentSound = Uri.parse(path); } } - tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, currentSound); - startActivityForResult(tmpIntent, i); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } else if (i == resetNotificationsRow) { - if (reseting) { - return; - } - reseting = true; - TLRPC.TL_account_resetNotifySettings req = new TLRPC.TL_account_resetNotifySettings(); - ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { - @Override - public void run(TLObject response, TLRPC.TL_error error) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - MessagesController.getInstance().enableJoined = true; - reseting = false; - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - editor.clear(); - editor.commit(); - if (listView != null) { - listView.invalidateViews(); - } - if (getParentActivity() != null) { - Toast toast = Toast.makeText(getParentActivity(), LocaleController.getString("ResetNotificationsText", R.string.ResetNotificationsText), Toast.LENGTH_SHORT); - toast.show(); - } - } - }); + } else if (i == groupSoundRow) { + String path = preferences.getString("GroupSoundPath", defaultPath); + if (path != null && !path.equals("NoSound")) { + if (path.equals(defaultPath)) { + currentSound = defaultUri; + } else { + currentSound = Uri.parse(path); + } } - }); - } else if (i == inappSoundRow) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - enabled = preferences.getBoolean("EnableInAppSounds", true); - editor.putBoolean("EnableInAppSounds", !enabled); - editor.commit(); - } else if (i == inappVibrateRow) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - enabled = preferences.getBoolean("EnableInAppVibrate", true); - editor.putBoolean("EnableInAppVibrate", !enabled); - editor.commit(); - } else if (i == inappPreviewRow) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - enabled = preferences.getBoolean("EnableInAppPreview", true); - editor.putBoolean("EnableInAppPreview", !enabled); - editor.commit(); - } else if (i == inchatSoundRow) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - enabled = preferences.getBoolean("EnableInChatSound", true); - editor.putBoolean("EnableInChatSound", !enabled); - editor.commit(); - NotificationsController.getInstance().setInChatSoundEnabled(!enabled); - } else if (i == inappPriorityRow) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - enabled = preferences.getBoolean("EnableInAppPriority", false); - editor.putBoolean("EnableInAppPriority", !enabled); - editor.commit(); - } else if (i == contactJoinedRow) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - enabled = preferences.getBoolean("EnableContactJoined", true); - MessagesController.getInstance().enableJoined = !enabled; - editor.putBoolean("EnableContactJoined", !enabled); - editor.commit(); - } else if (i == pebbleAlertRow) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - enabled = preferences.getBoolean("EnablePebbleNotifications", false); - editor.putBoolean("EnablePebbleNotifications", !enabled); - editor.commit(); - } else if (i == badgeNumberRow) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - enabled = preferences.getBoolean("badgeNumber", true); - editor.putBoolean("badgeNumber", !enabled); - editor.commit(); - NotificationsController.getInstance().setBadgeEnabled(!enabled); - } else if (i == notificationsServiceRow) { - final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - enabled = preferences.getBoolean("pushService", true); - if (!enabled) { - final SharedPreferences.Editor editor = preferences.edit(); - editor.putBoolean("pushService", !enabled); - editor.commit(); - ApplicationLoader.startPushService(); - } else { - if (getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setMessage(LocaleController.getString("NotificationsServiceDisableInfo", R.string.NotificationsServiceDisableInfo)); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + } + tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, currentSound); + startActivityForResult(tmpIntent, i); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } else if (i == resetNotificationsRow) { + if (reseting) { + return; + } + reseting = true; + TLRPC.TL_account_resetNotifySettings req = new TLRPC.TL_account_resetNotifySettings(); + ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(TLObject response, TLRPC.TL_error error) { + AndroidUtilities.runOnUIThread(new Runnable() { @Override - public void onClick(DialogInterface dialogInterface, int i) { - ApplicationLoader.stopPushService(); - final SharedPreferences.Editor editor = preferences.edit(); - editor.putBoolean("pushService", false); + public void run() { + MessagesController.getInstance().enableJoined = true; + reseting = false; + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + editor.clear(); editor.commit(); - listView.invalidateViews(); + if (listView != null) { + listView.invalidateViews(); + } + if (getParentActivity() != null) { + Toast toast = Toast.makeText(getParentActivity(), LocaleController.getString("ResetNotificationsText", R.string.ResetNotificationsText), Toast.LENGTH_SHORT); + toast.show(); + } } }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); } - } else if (i == messageLedRow || i == groupLedRow) { + }); + } else if (i == inappSoundRow) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + enabled = preferences.getBoolean("EnableInAppSounds", true); + editor.putBoolean("EnableInAppSounds", !enabled); + editor.commit(); + } else if (i == inappVibrateRow) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + enabled = preferences.getBoolean("EnableInAppVibrate", true); + editor.putBoolean("EnableInAppVibrate", !enabled); + editor.commit(); + } else if (i == inappPreviewRow) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + enabled = preferences.getBoolean("EnableInAppPreview", true); + editor.putBoolean("EnableInAppPreview", !enabled); + editor.commit(); + } else if (i == inchatSoundRow) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + enabled = preferences.getBoolean("EnableInChatSound", true); + editor.putBoolean("EnableInChatSound", !enabled); + editor.commit(); + NotificationsController.getInstance().setInChatSoundEnabled(!enabled); + } else if (i == inappPriorityRow) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + enabled = preferences.getBoolean("EnableInAppPriority", false); + editor.putBoolean("EnableInAppPriority", !enabled); + editor.commit(); + } else if (i == contactJoinedRow) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + enabled = preferences.getBoolean("EnableContactJoined", true); + MessagesController.getInstance().enableJoined = !enabled; + editor.putBoolean("EnableContactJoined", !enabled); + editor.commit(); + } else if (i == pebbleAlertRow) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + enabled = preferences.getBoolean("EnablePebbleNotifications", false); + editor.putBoolean("EnablePebbleNotifications", !enabled); + editor.commit(); + } else if (i == badgeNumberRow) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + enabled = preferences.getBoolean("badgeNumber", true); + editor.putBoolean("badgeNumber", !enabled); + editor.commit(); + NotificationsController.getInstance().setBadgeEnabled(!enabled); + } else if (i == notificationsServiceRow) { + final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + enabled = preferences.getBoolean("pushService", true); + if (!enabled) { + final SharedPreferences.Editor editor = preferences.edit(); + editor.putBoolean("pushService", !enabled); + editor.commit(); + ApplicationLoader.startPushService(); + } else { if (getParentActivity() == null) { return; } + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setMessage(LocaleController.getString("NotificationsServiceDisableInfo", R.string.NotificationsServiceDisableInfo)); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + ApplicationLoader.stopPushService(); + final SharedPreferences.Editor editor = preferences.edit(); + editor.putBoolean("pushService", false); + editor.commit(); + listView.invalidateViews(); + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } + } else if (i == messageLedRow || i == groupLedRow) { + if (getParentActivity() == null) { + return; + } - LayoutInflater li = (LayoutInflater)getParentActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); - view = li.inflate(R.layout.settings_color_dialog_layout, null, false); - final ColorPickerView colorPickerView = (ColorPickerView)view.findViewById(R.id.color_picker); + LayoutInflater li = (LayoutInflater) getParentActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); + view = li.inflate(R.layout.settings_color_dialog_layout, null, false); + final ColorPickerView colorPickerView = (ColorPickerView) view.findViewById(R.id.color_picker); - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - if (i == messageLedRow) { - colorPickerView.setOldCenterColor(preferences.getInt("MessagesLed", 0xff00ff00)); - } else if (i == groupLedRow) { - colorPickerView.setOldCenterColor(preferences.getInt("GroupLed", 0xff00ff00)); + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + if (i == messageLedRow) { + colorPickerView.setOldCenterColor(preferences.getInt("MessagesLed", 0xff00ff00)); + } else if (i == groupLedRow) { + colorPickerView.setOldCenterColor(preferences.getInt("GroupLed", 0xff00ff00)); + } + + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("LedColor", R.string.LedColor)); + builder.setView(view); + builder.setPositiveButton(LocaleController.getString("Set", R.string.Set), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int which) { + final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + if (i == messageLedRow) { + editor.putInt("MessagesLed", colorPickerView.getColor()); + } else if (i == groupLedRow) { + editor.putInt("GroupLed", colorPickerView.getColor()); + } + editor.commit(); + listView.invalidateViews(); } - - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("LedColor", R.string.LedColor)); - builder.setView(view); - builder.setPositiveButton(LocaleController.getString("Set", R.string.Set), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int which) { - final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - if (i == messageLedRow) { - editor.putInt("MessagesLed", colorPickerView.getColor()); - } else if (i == groupLedRow) { - editor.putInt("GroupLed", colorPickerView.getColor()); - } - editor.commit(); + }); + builder.setNeutralButton(LocaleController.getString("LedDisabled", R.string.LedDisabled), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + if (i == messageLedRow) { + editor.putInt("MessagesLed", 0); + } else if (i == groupLedRow) { + editor.putInt("GroupLed", 0); + } + editor.commit(); + listView.invalidateViews(); + } + }); + showAlertDialog(builder); + } else if (i == messagePopupNotificationRow || i == groupPopupNotificationRow) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("PopupNotification", R.string.PopupNotification)); + builder.setItems(new CharSequence[]{ + LocaleController.getString("NoPopup", R.string.NoPopup), + LocaleController.getString("OnlyWhenScreenOn", R.string.OnlyWhenScreenOn), + LocaleController.getString("OnlyWhenScreenOff", R.string.OnlyWhenScreenOff), + LocaleController.getString("AlwaysShowPopup", R.string.AlwaysShowPopup) + }, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + if (i == messagePopupNotificationRow) { + editor.putInt("popupAll", which); + } else if (i == groupPopupNotificationRow) { + editor.putInt("popupGroup", which); + } + editor.commit(); + if (listView != null) { listView.invalidateViews(); } - }); - builder.setNeutralButton(LocaleController.getString("LedDisabled", R.string.LedDisabled), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - if (i == messageLedRow) { - editor.putInt("MessagesLed", 0); - } else if (i == groupLedRow) { - editor.putInt("GroupLed", 0); - } - editor.commit(); + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } else if (i == messageVibrateRow || i == groupVibrateRow) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("Vibrate", R.string.Vibrate)); + builder.setItems(new CharSequence[]{ + LocaleController.getString("VibrationDisabled", R.string.VibrationDisabled), + LocaleController.getString("Default", R.string.Default), + LocaleController.getString("Short", R.string.Short), + LocaleController.getString("Long", R.string.Long), + LocaleController.getString("OnlyIfSilent", R.string.OnlyIfSilent) + }, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + String param = "vibrate_messages"; + if (i == groupVibrateRow) { + param = "vibrate_group"; + } + if (which == 0) { + editor.putInt(param, 2); + } else if (which == 1) { + editor.putInt(param, 0); + } else if (which == 2) { + editor.putInt(param, 1); + } else if (which == 3) { + editor.putInt(param, 3); + } else if (which == 4) { + editor.putInt(param, 4); + } + editor.commit(); + if (listView != null) { listView.invalidateViews(); } - }); - showAlertDialog(builder); - } else if (i == messagePopupNotificationRow || i == groupPopupNotificationRow) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("PopupNotification", R.string.PopupNotification)); - builder.setItems(new CharSequence[] { - LocaleController.getString("NoPopup", R.string.NoPopup), - LocaleController.getString("OnlyWhenScreenOn", R.string.OnlyWhenScreenOn), - LocaleController.getString("OnlyWhenScreenOff", R.string.OnlyWhenScreenOff), - LocaleController.getString("AlwaysShowPopup", R.string.AlwaysShowPopup) - }, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - if (i == messagePopupNotificationRow) { - editor.putInt("popupAll", which); - } else if (i == groupPopupNotificationRow) { - editor.putInt("popupGroup", which); - } - editor.commit(); - if (listView != null) { - listView.invalidateViews(); - } + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } else if (i == messagePriorityRow || i == groupPriorityRow) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("NotificationsPriority", R.string.NotificationsPriority)); + builder.setItems(new CharSequence[]{ + LocaleController.getString("NotificationsPriorityDefault", R.string.NotificationsPriorityDefault), + LocaleController.getString("NotificationsPriorityHigh", R.string.NotificationsPriorityHigh), + LocaleController.getString("NotificationsPriorityMax", R.string.NotificationsPriorityMax) + }, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + if (i == messagePriorityRow) { + preferences.edit().putInt("priority_messages", which).commit(); + } else if (i == groupPriorityRow) { + preferences.edit().putInt("priority_group", which).commit(); } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } else if (i == messageVibrateRow || i == groupVibrateRow) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("Vibrate", R.string.Vibrate)); - builder.setItems(new CharSequence[] { - LocaleController.getString("VibrationDisabled", R.string.VibrationDisabled), - LocaleController.getString("Default", R.string.Default), - LocaleController.getString("Short", R.string.Short), - LocaleController.getString("Long", R.string.Long), - LocaleController.getString("OnlyIfSilent", R.string.OnlyIfSilent) - }, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - String param = "vibrate_messages"; - if (i == groupVibrateRow) { - param = "vibrate_group"; - } - if (which == 0) { - editor.putInt(param, 2); - } else if (which == 1) { - editor.putInt(param, 0); - } else if (which == 2) { - editor.putInt(param, 1); - } else if (which == 3) { - editor.putInt(param, 3); - } else if (which == 4) { - editor.putInt(param, 4); - } - editor.commit(); - if (listView != null) { - listView.invalidateViews(); - } + if (listView != null) { + listView.invalidateViews(); } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } else if (i == messagePriorityRow || i == groupPriorityRow) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("NotificationsPriority", R.string.NotificationsPriority)); - builder.setItems(new CharSequence[] { - LocaleController.getString("NotificationsPriorityDefault", R.string.NotificationsPriorityDefault), - LocaleController.getString("NotificationsPriorityHigh", R.string.NotificationsPriorityHigh), - LocaleController.getString("NotificationsPriorityMax", R.string.NotificationsPriorityMax) - }, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - if (i == messagePriorityRow) { - preferences.edit().putInt("priority_messages", which).commit(); - } else if (i == groupPriorityRow) { - preferences.edit().putInt("priority_group", which).commit(); - } - if (listView != null) { - listView.invalidateViews(); - } + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } else if (i == repeatRow) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("RepeatNotifications", R.string.RepeatNotifications)); + builder.setItems(new CharSequence[]{ + LocaleController.getString("RepeatDisabled", R.string.RepeatDisabled), + LocaleController.formatPluralString("Minutes", 5), + LocaleController.formatPluralString("Minutes", 10), + LocaleController.formatPluralString("Minutes", 30), + LocaleController.formatPluralString("Hours", 1), + LocaleController.formatPluralString("Hours", 2), + LocaleController.formatPluralString("Hours", 4) + }, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + int minutes = 0; + if (which == 1) { + minutes = 5; + } else if (which == 2) { + minutes = 10; + } else if (which == 3) { + minutes = 30; + } else if (which == 4) { + minutes = 60; + } else if (which == 5) { + minutes = 60 * 2; + } else if (which == 6) { + minutes = 60 * 4; } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } else if (i == repeatRow) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("RepeatNotifications", R.string.RepeatNotifications)); - builder.setItems(new CharSequence[] { - LocaleController.getString("RepeatDisabled", R.string.RepeatDisabled), - LocaleController.formatPluralString("Minutes", 5), - LocaleController.formatPluralString("Minutes", 10), - LocaleController.formatPluralString("Minutes", 30), - LocaleController.formatPluralString("Hours", 1), - LocaleController.formatPluralString("Hours", 2), - LocaleController.formatPluralString("Hours", 4) - }, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - int minutes = 0; - if (which == 1) { - minutes = 5; - } else if (which == 2) { - minutes = 10; - } else if (which == 3) { - minutes = 30; - } else if (which == 4) { - minutes = 60; - } else if (which == 5) { - minutes = 60 * 2; - } else if (which == 6) { - minutes = 60 * 4; - } - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - preferences.edit().putInt("repeat_messages", minutes).commit(); - if (listView != null) { - listView.invalidateViews(); - } + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + preferences.edit().putInt("repeat_messages", minutes).commit(); + if (listView != null) { + listView.invalidateViews(); } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } - if (view instanceof TextCheckCell) { - ((TextCheckCell) view).setChecked(!enabled); - } + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } + if (view instanceof TextCheckCell) { + ((TextCheckCell) view).setChecked(!enabled); } - }); - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); } - } + }); + return fragmentView; } @@ -577,7 +571,7 @@ public class NotificationsSettingsActivity extends BaseFragment implements Notif Ringtone rng = RingtoneManager.getRingtone(getParentActivity(), ringtone); if (rng != null) { if(ringtone.equals(Settings.System.DEFAULT_NOTIFICATION_URI)) { - name = LocaleController.getString("Default", R.string.Default); + name = LocaleController.getString("SoundDefault", R.string.SoundDefault); } else { name = rng.getTitle(getParentActivity()); } @@ -724,9 +718,9 @@ public class NotificationsSettingsActivity extends BaseFragment implements Notif textCell.setMultilineDetail(false); String value = null; if (i == messageSoundRow) { - value = preferences.getString("GlobalSound", LocaleController.getString("Default", R.string.Default)); + value = preferences.getString("GlobalSound", LocaleController.getString("SoundDefault", R.string.SoundDefault)); } else if (i == groupSoundRow) { - value = preferences.getString("GroupSound", LocaleController.getString("Default", R.string.Default)); + value = preferences.getString("GroupSound", LocaleController.getString("SoundDefault", R.string.SoundDefault)); } if (value.equals("NoSound")) { value = LocaleController.getString("NoSound", R.string.NoSound); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/PasscodeActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/PasscodeActivity.java index a0548ca3a..f5cad11a8 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/PasscodeActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/PasscodeActivity.java @@ -55,9 +55,6 @@ import org.telegram.ui.ActionBar.ActionBarMenu; import org.telegram.ui.ActionBar.ActionBarMenuItem; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.Adapters.BaseFragmentAdapter; -import org.telegram.ui.AnimationCompat.AnimatorListenerAdapterProxy; -import org.telegram.ui.AnimationCompat.AnimatorSetProxy; -import org.telegram.ui.AnimationCompat.ObjectAnimatorProxy; import org.telegram.ui.Cells.TextCheckCell; import org.telegram.ui.Cells.TextInfoPrivacyCell; import org.telegram.ui.Cells.TextSettingsCell; @@ -111,297 +108,295 @@ public class PasscodeActivity extends BaseFragment implements NotificationCenter } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - if (type != 3) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); + public View createView(Context context, LayoutInflater inflater) { + if (type != 3) { + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + } + actionBar.setAllowOverlayTitle(false); + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); + } else if (id == done_button) { + if (passwordEditText.getImeOptions() == EditorInfo.IME_ACTION_NEXT) { + processNext(); + } else if (passwordEditText.getImeOptions() == EditorInfo.IME_ACTION_DONE) { + processDone(); + } + } else if (id == pin_item) { + currentPasswordType = 0; + updateDropDownTextView(); + } else if (id == password_item) { + currentPasswordType = 1; + updateDropDownTextView(); + } } - actionBar.setAllowOverlayTitle(false); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + }); + + fragmentView = new FrameLayout(context); + FrameLayout frameLayout = (FrameLayout) fragmentView; + + if (type != 0) { + ActionBarMenu menu = actionBar.createMenu(); + menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); + + titleTextView = new TextView(context); + titleTextView.setTextColor(0xff757575); + if (type == 1) { + if (UserConfig.passcodeHash.length() != 0) { + titleTextView.setText(LocaleController.getString("EnterNewPasscode", R.string.EnterNewPasscode)); + } else { + titleTextView.setText(LocaleController.getString("EnterNewFirstPasscode", R.string.EnterNewFirstPasscode)); + } + } else { + titleTextView.setText(LocaleController.getString("EnterCurrentPasscode", R.string.EnterCurrentPasscode)); + } + titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); + titleTextView.setGravity(Gravity.CENTER_HORIZONTAL); + frameLayout.addView(titleTextView); + FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) titleTextView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.gravity = Gravity.CENTER_HORIZONTAL; + layoutParams.topMargin = AndroidUtilities.dp(38); + titleTextView.setLayoutParams(layoutParams); + + passwordEditText = new EditText(context); + passwordEditText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); + passwordEditText.setTextColor(0xff000000); + passwordEditText.setMaxLines(1); + passwordEditText.setLines(1); + passwordEditText.setGravity(Gravity.CENTER_HORIZONTAL); + passwordEditText.setSingleLine(true); + if (type == 1) { + passwordEditText.setImeOptions(EditorInfo.IME_ACTION_NEXT); + } else { + passwordEditText.setImeOptions(EditorInfo.IME_ACTION_DONE); + } + passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance()); + passwordEditText.setTypeface(Typeface.DEFAULT); + AndroidUtilities.clearCursorDrawable(passwordEditText); + frameLayout.addView(passwordEditText); + layoutParams = (FrameLayout.LayoutParams) passwordEditText.getLayoutParams(); + layoutParams.topMargin = AndroidUtilities.dp(90); + layoutParams.height = AndroidUtilities.dp(36); + layoutParams.leftMargin = AndroidUtilities.dp(40); + layoutParams.gravity = Gravity.TOP | Gravity.LEFT; + layoutParams.rightMargin = AndroidUtilities.dp(40); + layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; + passwordEditText.setLayoutParams(layoutParams); + passwordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } else if (id == done_button) { - if (passwordEditText.getImeOptions() == EditorInfo.IME_ACTION_NEXT) { - processNext(); - } else if (passwordEditText.getImeOptions() == EditorInfo.IME_ACTION_DONE) { + public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { + if (i == EditorInfo.IME_ACTION_NEXT) { + processNext(); + return true; + } else if (i == EditorInfo.IME_ACTION_DONE) { + processDone(); + return true; + } + return false; + } + }); + passwordEditText.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + + } + + @Override + public void afterTextChanged(Editable s) { + if (passwordEditText.length() == 4) { + if (type == 2 && UserConfig.passcodeType == 0) { processDone(); + } else if (type == 1 && currentPasswordType == 0) { + if (passwordEditText.getImeOptions() == EditorInfo.IME_ACTION_NEXT) { + processNext(); + } else if (passwordEditText.getImeOptions() == EditorInfo.IME_ACTION_DONE) { + processDone(); + } } - } else if (id == pin_item) { - currentPasswordType = 0; - updateDropDownTextView(); - } else if (id == password_item) { - currentPasswordType = 1; - updateDropDownTextView(); } } }); + if (android.os.Build.VERSION.SDK_INT < 11) { + passwordEditText.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() { + public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { + menu.clear(); + } + }); + } else { + passwordEditText.setCustomSelectionActionModeCallback(new ActionMode.Callback() { + public boolean onPrepareActionMode(ActionMode mode, Menu menu) { + return false; + } - fragmentView = new FrameLayout(getParentActivity()); - FrameLayout frameLayout = (FrameLayout) fragmentView; + public void onDestroyActionMode(ActionMode mode) { + } - if (type != 0) { - ActionBarMenu menu = actionBar.createMenu(); - menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); + public boolean onCreateActionMode(ActionMode mode, Menu menu) { + return false; + } - titleTextView = new TextView(getParentActivity()); - titleTextView.setTextColor(0xff757575); - if (type == 1) { - titleTextView.setText(LocaleController.getString("EnterNewPasscode", R.string.EnterNewPasscode)); - } else { - titleTextView.setText(LocaleController.getString("EnterCurrentPasscode", R.string.EnterCurrentPasscode)); - } - titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - titleTextView.setGravity(Gravity.CENTER_HORIZONTAL); - frameLayout.addView(titleTextView); - FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) titleTextView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.gravity = Gravity.CENTER_HORIZONTAL; - layoutParams.topMargin = AndroidUtilities.dp(38); - titleTextView.setLayoutParams(layoutParams); - - passwordEditText = new EditText(getParentActivity()); - passwordEditText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); - passwordEditText.setTextColor(0xff000000); - passwordEditText.setMaxLines(1); - passwordEditText.setLines(1); - passwordEditText.setGravity(Gravity.CENTER_HORIZONTAL); - passwordEditText.setSingleLine(true); - if (type == 1) { - passwordEditText.setImeOptions(EditorInfo.IME_ACTION_NEXT); - } else { - passwordEditText.setImeOptions(EditorInfo.IME_ACTION_DONE); - } - passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance()); - passwordEditText.setTypeface(Typeface.DEFAULT); - AndroidUtilities.clearCursorDrawable(passwordEditText); - frameLayout.addView(passwordEditText); - layoutParams = (FrameLayout.LayoutParams) passwordEditText.getLayoutParams(); - layoutParams.topMargin = AndroidUtilities.dp(90); - layoutParams.height = AndroidUtilities.dp(36); - layoutParams.leftMargin = AndroidUtilities.dp(40); - layoutParams.gravity = Gravity.TOP | Gravity.LEFT; - layoutParams.rightMargin = AndroidUtilities.dp(40); - layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT; - passwordEditText.setLayoutParams(layoutParams); - passwordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { - if (i == EditorInfo.IME_ACTION_NEXT) { - processNext(); - return true; - } else if (i == EditorInfo.IME_ACTION_DONE) { - processDone(); - return true; - } + public boolean onActionItemClicked(ActionMode mode, MenuItem item) { return false; } }); - passwordEditText.addTextChangedListener(new TextWatcher() { + } + + if (type == 1) { + dropDownContainer = new ActionBarMenuItem(context, menu, R.drawable.bar_selector); + dropDownContainer.setSubMenuOpenSide(1); + dropDownContainer.addSubItem(pin_item, LocaleController.getString("PasscodePIN", R.string.PasscodePIN), 0); + dropDownContainer.addSubItem(password_item, LocaleController.getString("PasscodePassword", R.string.PasscodePassword), 0); + actionBar.addView(dropDownContainer); + layoutParams = (FrameLayout.LayoutParams) dropDownContainer.getLayoutParams(); + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.rightMargin = AndroidUtilities.dp(40); + layoutParams.leftMargin = AndroidUtilities.isTablet() ? AndroidUtilities.dp(64) : AndroidUtilities.dp(56); + layoutParams.gravity = Gravity.TOP | Gravity.LEFT; + dropDownContainer.setLayoutParams(layoutParams); + dropDownContainer.setOnClickListener(new View.OnClickListener() { @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - - } - - @Override - public void afterTextChanged(Editable s) { - if (passwordEditText.length() == 4) { - if (type == 2 && UserConfig.passcodeType == 0) { - processDone(); - } else if (type == 1 && currentPasswordType == 0) { - if (passwordEditText.getImeOptions() == EditorInfo.IME_ACTION_NEXT) { - processNext(); - } else if (passwordEditText.getImeOptions() == EditorInfo.IME_ACTION_DONE) { - processDone(); - } - } - } + public void onClick(View view) { + dropDownContainer.toggleSubMenu(); } }); - if (android.os.Build.VERSION.SDK_INT < 11) { - passwordEditText.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() { - public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { - menu.clear(); - } - }); - } else { - passwordEditText.setCustomSelectionActionModeCallback(new ActionMode.Callback() { - public boolean onPrepareActionMode(ActionMode mode, Menu menu) { - return false; - } - public void onDestroyActionMode(ActionMode mode) { - } - - public boolean onCreateActionMode(ActionMode mode, Menu menu) { - return false; - } - - public boolean onActionItemClicked(ActionMode mode, MenuItem item) { - return false; - } - }); - } - - if (type == 1) { - dropDownContainer = new ActionBarMenuItem(getParentActivity(), menu, R.drawable.bar_selector); - dropDownContainer.setSubMenuOpenSide(1); - dropDownContainer.addSubItem(pin_item, LocaleController.getString("PasscodePIN", R.string.PasscodePIN), 0); - dropDownContainer.addSubItem(password_item, LocaleController.getString("PasscodePassword", R.string.PasscodePassword), 0); - actionBar.addView(dropDownContainer); - layoutParams = (FrameLayout.LayoutParams) dropDownContainer.getLayoutParams(); - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.rightMargin = AndroidUtilities.dp(40); - layoutParams.leftMargin = AndroidUtilities.isTablet() ? AndroidUtilities.dp(64) : AndroidUtilities.dp(56); - layoutParams.gravity = Gravity.TOP | Gravity.LEFT; - dropDownContainer.setLayoutParams(layoutParams); - dropDownContainer.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - dropDownContainer.toggleSubMenu(); - } - }); - - dropDown = new TextView(getParentActivity()); - dropDown.setGravity(Gravity.LEFT); - dropDown.setSingleLine(true); - dropDown.setLines(1); - dropDown.setMaxLines(1); - dropDown.setEllipsize(TextUtils.TruncateAt.END); - dropDown.setTextColor(0xffffffff); - dropDown.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - dropDown.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_arrow_drop_down, 0); - dropDown.setCompoundDrawablePadding(AndroidUtilities.dp(4)); - dropDown.setPadding(0, 0, AndroidUtilities.dp(10), 0); - dropDownContainer.addView(dropDown); - layoutParams = (FrameLayout.LayoutParams) dropDown.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.leftMargin = AndroidUtilities.dp(16); - layoutParams.gravity = Gravity.CENTER_VERTICAL; - layoutParams.bottomMargin = AndroidUtilities.dp(1); - dropDown.setLayoutParams(layoutParams); - } else { - actionBar.setTitle(LocaleController.getString("Passcode", R.string.Passcode)); - } - - updateDropDownTextView(); + dropDown = new TextView(context); + dropDown.setGravity(Gravity.LEFT); + dropDown.setSingleLine(true); + dropDown.setLines(1); + dropDown.setMaxLines(1); + dropDown.setEllipsize(TextUtils.TruncateAt.END); + dropDown.setTextColor(0xffffffff); + dropDown.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); + dropDown.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_arrow_drop_down, 0); + dropDown.setCompoundDrawablePadding(AndroidUtilities.dp(4)); + dropDown.setPadding(0, 0, AndroidUtilities.dp(10), 0); + dropDownContainer.addView(dropDown); + layoutParams = (FrameLayout.LayoutParams) dropDown.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.leftMargin = AndroidUtilities.dp(16); + layoutParams.gravity = Gravity.CENTER_VERTICAL; + layoutParams.bottomMargin = AndroidUtilities.dp(1); + dropDown.setLayoutParams(layoutParams); } else { actionBar.setTitle(LocaleController.getString("Passcode", R.string.Passcode)); - frameLayout.setBackgroundColor(0xfff0f0f0); - listView = new ListView(getParentActivity()); - listView.setDivider(null); - listView.setDividerHeight(0); - listView.setVerticalScrollBarEnabled(false); - listView.setDrawSelectorOnTop(true); - frameLayout.addView(listView); - FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.gravity = Gravity.TOP; - listView.setLayoutParams(layoutParams); - listView.setAdapter(listAdapter = new ListAdapter(getParentActivity())); - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, final int i, long l) { - if (i == changePasscodeRow) { - presentFragment(new PasscodeActivity(1)); - } else if (i == passcodeRow) { - TextCheckCell cell = (TextCheckCell) view; - if (UserConfig.passcodeHash.length() != 0) { - UserConfig.passcodeHash = ""; - UserConfig.appLocked = false; - UserConfig.saveConfig(false); - int count = listView.getChildCount(); - for (int a = 0; a < count; a++) { - View child = listView.getChildAt(a); - if (child instanceof TextSettingsCell) { - TextSettingsCell textCell = (TextSettingsCell) child; - textCell.setTextColor(0xffc6c6c6); - break; - } - } - cell.setChecked(UserConfig.passcodeHash.length() != 0); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.didSetPasscode); - } else { - presentFragment(new PasscodeActivity(1)); - } - } else if (i == autoLockRow) { - if (getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("AutoLock", R.string.AutoLock)); - final NumberPicker numberPicker = new NumberPicker(getParentActivity()); - numberPicker.setMinValue(0); - numberPicker.setMaxValue(4); - if (UserConfig.autoLockIn == 0) { - numberPicker.setValue(0); - } else if (UserConfig.autoLockIn == 60) { - numberPicker.setValue(1); - } else if (UserConfig.autoLockIn == 60 * 5) { - numberPicker.setValue(2); - } else if (UserConfig.autoLockIn == 60 * 60) { - numberPicker.setValue(3); - } else if (UserConfig.autoLockIn == 60 * 60 * 5) { - numberPicker.setValue(4); - } - numberPicker.setFormatter(new NumberPicker.Formatter() { - @Override - public String format(int value) { - if (value == 0) { - return LocaleController.getString("Disabled", R.string.Disabled); - } else if (value == 1) { - return LocaleController.formatString("AutoLockInTime", R.string.AutoLockInTime, LocaleController.formatPluralString("Minutes", 1)); - } else if (value == 2) { - return LocaleController.formatString("AutoLockInTime", R.string.AutoLockInTime, LocaleController.formatPluralString("Minutes", 5)); - } else if (value == 3) { - return LocaleController.formatString("AutoLockInTime", R.string.AutoLockInTime, LocaleController.formatPluralString("Hours", 1)); - } else if (value == 4) { - return LocaleController.formatString("AutoLockInTime", R.string.AutoLockInTime, LocaleController.formatPluralString("Hours", 5)); - } - return ""; - } - }); - builder.setView(numberPicker); - builder.setNegativeButton(LocaleController.getString("Done", R.string.Done), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - which = numberPicker.getValue(); - if (which == 0) { - UserConfig.autoLockIn = 0; - } else if (which == 1) { - UserConfig.autoLockIn = 60; - } else if (which == 2) { - UserConfig.autoLockIn = 60 * 5; - } else if (which == 3) { - UserConfig.autoLockIn = 60 * 60; - } else if (which == 4) { - UserConfig.autoLockIn = 60 * 60 * 5; - } - listView.invalidateViews(); - UserConfig.saveConfig(false); - } - }); - showAlertDialog(builder); - } - } - }); } + + updateDropDownTextView(); } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); - } + actionBar.setTitle(LocaleController.getString("Passcode", R.string.Passcode)); + frameLayout.setBackgroundColor(0xfff0f0f0); + listView = new ListView(context); + listView.setDivider(null); + listView.setDividerHeight(0); + listView.setVerticalScrollBarEnabled(false); + listView.setDrawSelectorOnTop(true); + frameLayout.addView(listView); + FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.gravity = Gravity.TOP; + listView.setLayoutParams(layoutParams); + listView.setAdapter(listAdapter = new ListAdapter(context)); + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, final int i, long l) { + if (i == changePasscodeRow) { + presentFragment(new PasscodeActivity(1)); + } else if (i == passcodeRow) { + TextCheckCell cell = (TextCheckCell) view; + if (UserConfig.passcodeHash.length() != 0) { + UserConfig.passcodeHash = ""; + UserConfig.appLocked = false; + UserConfig.saveConfig(false); + int count = listView.getChildCount(); + for (int a = 0; a < count; a++) { + View child = listView.getChildAt(a); + if (child instanceof TextSettingsCell) { + TextSettingsCell textCell = (TextSettingsCell) child; + textCell.setTextColor(0xffc6c6c6); + break; + } + } + cell.setChecked(UserConfig.passcodeHash.length() != 0); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.didSetPasscode); + } else { + presentFragment(new PasscodeActivity(1)); + } + } else if (i == autoLockRow) { + if (getParentActivity() == null) { + return; + } + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("AutoLock", R.string.AutoLock)); + final NumberPicker numberPicker = new NumberPicker(getParentActivity()); + numberPicker.setMinValue(0); + numberPicker.setMaxValue(4); + if (UserConfig.autoLockIn == 0) { + numberPicker.setValue(0); + } else if (UserConfig.autoLockIn == 60) { + numberPicker.setValue(1); + } else if (UserConfig.autoLockIn == 60 * 5) { + numberPicker.setValue(2); + } else if (UserConfig.autoLockIn == 60 * 60) { + numberPicker.setValue(3); + } else if (UserConfig.autoLockIn == 60 * 60 * 5) { + numberPicker.setValue(4); + } + numberPicker.setFormatter(new NumberPicker.Formatter() { + @Override + public String format(int value) { + if (value == 0) { + return LocaleController.getString("Disabled", R.string.Disabled); + } else if (value == 1) { + return LocaleController.formatString("AutoLockInTime", R.string.AutoLockInTime, LocaleController.formatPluralString("Minutes", 1)); + } else if (value == 2) { + return LocaleController.formatString("AutoLockInTime", R.string.AutoLockInTime, LocaleController.formatPluralString("Minutes", 5)); + } else if (value == 3) { + return LocaleController.formatString("AutoLockInTime", R.string.AutoLockInTime, LocaleController.formatPluralString("Hours", 1)); + } else if (value == 4) { + return LocaleController.formatString("AutoLockInTime", R.string.AutoLockInTime, LocaleController.formatPluralString("Hours", 5)); + } + return ""; + } + }); + builder.setView(numberPicker); + builder.setNegativeButton(LocaleController.getString("Done", R.string.Done), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + which = numberPicker.getValue(); + if (which == 0) { + UserConfig.autoLockIn = 0; + } else if (which == 1) { + UserConfig.autoLockIn = 60; + } else if (which == 2) { + UserConfig.autoLockIn = 60 * 5; + } else if (which == 3) { + UserConfig.autoLockIn = 60 * 60; + } else if (which == 4) { + UserConfig.autoLockIn = 60 * 60 * 5; + } + listView.invalidateViews(); + UserConfig.saveConfig(false); + } + }); + showAlertDialog(builder); + } + } + }); } + return fragmentView; } @@ -526,7 +521,7 @@ public class PasscodeActivity extends BaseFragment implements NotificationCenter } catch (Exception e) { FileLog.e("tmessages", e); } - shakeTextView(2, 0); + AndroidUtilities.shakeTextView(titleTextView, 2, 0); passwordEditText.setText(""); return; } @@ -550,23 +545,6 @@ public class PasscodeActivity extends BaseFragment implements NotificationCenter } } - private void shakeTextView(final float x, final int num) { - if (num == 6) { - titleTextView.clearAnimation(); - return; - } - AnimatorSetProxy animatorSetProxy = new AnimatorSetProxy(); - animatorSetProxy.playTogether(ObjectAnimatorProxy.ofFloat(titleTextView, "translationX", AndroidUtilities.dp(x))); - animatorSetProxy.setDuration(50); - animatorSetProxy.addListener(new AnimatorListenerAdapterProxy() { - @Override - public void onAnimationEnd(Object animation) { - shakeTextView(num == 5 ? 0 : -x, num + 1); - } - }); - animatorSetProxy.start(); - } - private void onPasscodeError() { if (getParentActivity() == null) { return; @@ -575,7 +553,7 @@ public class PasscodeActivity extends BaseFragment implements NotificationCenter if (v != null) { v.vibrate(200); } - shakeTextView(2, 0); + AndroidUtilities.shakeTextView(titleTextView, 2, 0); } private void fixLayoutInternal() { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/PhotoAlbumPickerActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/PhotoAlbumPickerActivity.java index b2ad1a747..fa330b1db 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/PhotoAlbumPickerActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/PhotoAlbumPickerActivity.java @@ -95,129 +95,123 @@ public class PhotoAlbumPickerActivity extends BaseFragment implements Notificati @SuppressWarnings("unchecked") @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setBackgroundColor(0xff333333); - actionBar.setItemsBackground(R.drawable.bar_selector_picker); - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setTitle(LocaleController.getString("Gallery", R.string.Gallery)); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - if (Build.VERSION.SDK_INT < 11) { - listView.setAdapter(null); - listView = null; - listAdapter = null; - } - finishFragment(); - } else if (id == 1) { - if (delegate != null) { - finishFragment(false); - delegate.startPhotoSelectActivity(); - } + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackgroundColor(0xff333333); + actionBar.setItemsBackground(R.drawable.bar_selector_picker); + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setTitle(LocaleController.getString("Gallery", R.string.Gallery)); + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + if (Build.VERSION.SDK_INT < 11) { + listView.setAdapter(null); + listView = null; + listAdapter = null; + } + finishFragment(); + } else if (id == 1) { + if (delegate != null) { + finishFragment(false); + delegate.startPhotoSelectActivity(); } } - }); - - ActionBarMenu menu = actionBar.createMenu(); - menu.addItem(1, R.drawable.ic_ab_other); - - fragmentView = new FrameLayout(getParentActivity()); - - FrameLayout frameLayout = (FrameLayout) fragmentView; - frameLayout.setBackgroundColor(0xff000000); - - listView = new ListView(getParentActivity()); - listView.setPadding(AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4), AndroidUtilities.dp(4)); - listView.setClipToPadding(false); - listView.setHorizontalScrollBarEnabled(false); - listView.setVerticalScrollBarEnabled(false); - listView.setSelector(new ColorDrawable(0)); - listView.setDividerHeight(0); - listView.setDivider(null); - listView.setDrawingCacheEnabled(false); - listView.setScrollingCacheEnabled(false); - frameLayout.addView(listView); - FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.bottomMargin = AndroidUtilities.dp(48); - listView.setLayoutParams(layoutParams); - listView.setAdapter(listAdapter = new ListAdapter(getParentActivity())); - AndroidUtilities.setListViewEdgeEffectColor(listView, 0xff333333); - - emptyView = new TextView(getParentActivity()); - emptyView.setTextColor(0xff808080); - emptyView.setTextSize(20); - emptyView.setGravity(Gravity.CENTER); - emptyView.setVisibility(View.GONE); - emptyView.setText(LocaleController.getString("NoPhotos", R.string.NoPhotos)); - frameLayout.addView(emptyView); - layoutParams = (FrameLayout.LayoutParams) emptyView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.bottomMargin = AndroidUtilities.dp(48); - emptyView.setLayoutParams(layoutParams); - emptyView.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - return true; - } - }); - - progressView = new FrameLayout(getParentActivity()); - progressView.setVisibility(View.GONE); - frameLayout.addView(progressView); - layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.bottomMargin = AndroidUtilities.dp(48); - progressView.setLayoutParams(layoutParams); - - ProgressBar progressBar = new ProgressBar(getParentActivity()); - progressView.addView(progressBar); - layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.gravity = Gravity.CENTER; - progressView.setLayoutParams(layoutParams); - - photoPickerBottomLayout = new PhotoPickerBottomLayout(getParentActivity()); - frameLayout.addView(photoPickerBottomLayout); - layoutParams = (FrameLayout.LayoutParams) photoPickerBottomLayout.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = AndroidUtilities.dp(48); - layoutParams.gravity = Gravity.BOTTOM; - photoPickerBottomLayout.setLayoutParams(layoutParams); - photoPickerBottomLayout.cancelButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - finishFragment(); - } - }); - photoPickerBottomLayout.doneButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - sendSelectedPhotos(); - finishFragment(); - } - }); - - if (loading && (albumsSorted == null || albumsSorted != null && albumsSorted.isEmpty())) { - progressView.setVisibility(View.VISIBLE); - listView.setEmptyView(null); - } else { - progressView.setVisibility(View.GONE); - listView.setEmptyView(emptyView); } - photoPickerBottomLayout.updateSelectedCount(selectedPhotos.size() + selectedWebPhotos.size(), true); + }); + + ActionBarMenu menu = actionBar.createMenu(); + menu.addItem(1, R.drawable.ic_ab_other); + + fragmentView = new FrameLayout(context); + + FrameLayout frameLayout = (FrameLayout) fragmentView; + frameLayout.setBackgroundColor(0xff000000); + + listView = new ListView(context); + listView.setPadding(AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4), AndroidUtilities.dp(4)); + listView.setClipToPadding(false); + listView.setHorizontalScrollBarEnabled(false); + listView.setVerticalScrollBarEnabled(false); + listView.setSelector(new ColorDrawable(0)); + listView.setDividerHeight(0); + listView.setDivider(null); + listView.setDrawingCacheEnabled(false); + listView.setScrollingCacheEnabled(false); + frameLayout.addView(listView); + FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.bottomMargin = AndroidUtilities.dp(48); + listView.setLayoutParams(layoutParams); + listView.setAdapter(listAdapter = new ListAdapter(context)); + AndroidUtilities.setListViewEdgeEffectColor(listView, 0xff333333); + + emptyView = new TextView(context); + emptyView.setTextColor(0xff808080); + emptyView.setTextSize(20); + emptyView.setGravity(Gravity.CENTER); + emptyView.setVisibility(View.GONE); + emptyView.setText(LocaleController.getString("NoPhotos", R.string.NoPhotos)); + frameLayout.addView(emptyView); + layoutParams = (FrameLayout.LayoutParams) emptyView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.bottomMargin = AndroidUtilities.dp(48); + emptyView.setLayoutParams(layoutParams); + emptyView.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + + progressView = new FrameLayout(context); + progressView.setVisibility(View.GONE); + frameLayout.addView(progressView); + layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.bottomMargin = AndroidUtilities.dp(48); + progressView.setLayoutParams(layoutParams); + + ProgressBar progressBar = new ProgressBar(context); + progressView.addView(progressBar); + layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.gravity = Gravity.CENTER; + progressView.setLayoutParams(layoutParams); + + photoPickerBottomLayout = new PhotoPickerBottomLayout(context); + frameLayout.addView(photoPickerBottomLayout); + layoutParams = (FrameLayout.LayoutParams) photoPickerBottomLayout.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = AndroidUtilities.dp(48); + layoutParams.gravity = Gravity.BOTTOM; + photoPickerBottomLayout.setLayoutParams(layoutParams); + photoPickerBottomLayout.cancelButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + finishFragment(); + } + }); + photoPickerBottomLayout.doneButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + sendSelectedPhotos(); + finishFragment(); + } + }); + + if (loading && (albumsSorted == null || albumsSorted != null && albumsSorted.isEmpty())) { + progressView.setVisibility(View.VISIBLE); + listView.setEmptyView(null); } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); - } + progressView.setVisibility(View.GONE); + listView.setEmptyView(emptyView); } + photoPickerBottomLayout.updateSelectedCount(selectedPhotos.size() + selectedWebPhotos.size(), true); + return fragmentView; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/PhotoCropActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/PhotoCropActivity.java index 43e856ee3..af94958c1 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/PhotoCropActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/PhotoCropActivity.java @@ -19,7 +19,6 @@ import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; -import android.view.ViewGroup; import android.widget.FrameLayout; import org.telegram.android.AndroidUtilities; @@ -432,44 +431,38 @@ public class PhotoCropActivity extends BaseFragment { } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setBackgroundColor(0xff333333); - actionBar.setItemsBackground(R.drawable.bar_selector_picker); - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - actionBar.setTitle(LocaleController.getString("CropImage", R.string.CropImage)); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } else if (id == done_button) { - if (delegate != null && !doneButtonPressed) { - Bitmap bitmap = view.getBitmap(); - if (bitmap == imageToCrop) { - sameBitmap = true; - } - delegate.didFinishEdit(bitmap, getArguments()); - doneButtonPressed = true; + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackgroundColor(0xff333333); + actionBar.setItemsBackground(R.drawable.bar_selector_picker); + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setAllowOverlayTitle(true); + actionBar.setTitle(LocaleController.getString("CropImage", R.string.CropImage)); + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); + } else if (id == done_button) { + if (delegate != null && !doneButtonPressed) { + Bitmap bitmap = view.getBitmap(); + if (bitmap == imageToCrop) { + sameBitmap = true; } - finishFragment(); + delegate.didFinishEdit(bitmap, getArguments()); + doneButtonPressed = true; } + finishFragment(); } - }); - - ActionBarMenu menu = actionBar.createMenu(); - menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); - - fragmentView = view = new PhotoCropView(getParentActivity()); - ((PhotoCropView) fragmentView).freeform = getArguments().getBoolean("freeform", false); - fragmentView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); } - } + }); + + ActionBarMenu menu = actionBar.createMenu(); + menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); + + fragmentView = view = new PhotoCropView(context); + ((PhotoCropView) fragmentView).freeform = getArguments().getBoolean("freeform", false); + fragmentView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); + return fragmentView; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/PhotoPickerActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/PhotoPickerActivity.java index 3e92b919c..d58873cad 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/PhotoPickerActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/PhotoPickerActivity.java @@ -142,275 +142,269 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen @SuppressWarnings("unchecked") @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setBackgroundColor(0xff333333); - actionBar.setItemsBackground(R.drawable.bar_selector_picker); - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - if (selectedAlbum != null) { - actionBar.setTitle(selectedAlbum.bucketName); - } else if (type == 0) { - actionBar.setTitle(LocaleController.getString("SearchImagesTitle", R.string.SearchImagesTitle)); - } else if (type == 1) { - actionBar.setTitle(LocaleController.getString("SearchGifsTitle", R.string.SearchGifsTitle)); - } - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - if (Build.VERSION.SDK_INT < 11) { - listView.setAdapter(null); - listView = null; - listAdapter = null; - } - finishFragment(); + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackgroundColor(0xff333333); + actionBar.setItemsBackground(R.drawable.bar_selector_picker); + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + if (selectedAlbum != null) { + actionBar.setTitle(selectedAlbum.bucketName); + } else if (type == 0) { + actionBar.setTitle(LocaleController.getString("SearchImagesTitle", R.string.SearchImagesTitle)); + } else if (type == 1) { + actionBar.setTitle(LocaleController.getString("SearchGifsTitle", R.string.SearchGifsTitle)); + } + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + if (Build.VERSION.SDK_INT < 11) { + listView.setAdapter(null); + listView = null; + listAdapter = null; } + finishFragment(); } - }); + } + }); - if (selectedAlbum == null) { - ActionBarMenu menu = actionBar.createMenu(); - searchItem = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() { - @Override - public void onSearchExpand() { + if (selectedAlbum == null) { + ActionBarMenu menu = actionBar.createMenu(); + searchItem = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() { + @Override + public void onSearchExpand() { - } + } - @Override - public boolean onSearchCollapse() { - finishFragment(); - return false; - } + @Override + public boolean onSearchCollapse() { + finishFragment(); + return false; + } - @Override - public void onTextChanged(EditText editText) { - if (editText.getText().length() == 0) { - searchResult.clear(); - searchResultKeys.clear(); - lastSearchString = null; - nextSearchBingString = null; - giphySearchEndReached = true; - searching = false; - requestQueue.cancelAll("search"); - if (type == 0) { - emptyView.setText(LocaleController.getString("NoRecentPhotos", R.string.NoRecentPhotos)); - } else if (type == 1) { - emptyView.setText(LocaleController.getString("NoRecentGIFs", R.string.NoRecentGIFs)); - } - updateSearchInterface(); - } - } - - @Override - public void onSearchPressed(EditText editText) { - if (editText.getText().toString().length() == 0) { - return; - } + @Override + public void onTextChanged(EditText editText) { + if (editText.getText().length() == 0) { searchResult.clear(); searchResultKeys.clear(); + lastSearchString = null; nextSearchBingString = null; giphySearchEndReached = true; + searching = false; + requestQueue.cancelAll("search"); if (type == 0) { - searchBingImages(editText.getText().toString(), 0, 53); + emptyView.setText(LocaleController.getString("NoRecentPhotos", R.string.NoRecentPhotos)); } else if (type == 1) { - searchGiphyImages(editText.getText().toString(), 0, 53); - } - lastSearchString = editText.getText().toString(); - if (lastSearchString.length() == 0) { - lastSearchString = null; - if (type == 0) { - emptyView.setText(LocaleController.getString("NoRecentPhotos", R.string.NoRecentPhotos)); - } else if (type == 1) { - emptyView.setText(LocaleController.getString("NoRecentGIFs", R.string.NoRecentGIFs)); - } - } else { - emptyView.setText(LocaleController.getString("NoResult", R.string.NoResult)); + emptyView.setText(LocaleController.getString("NoRecentGIFs", R.string.NoRecentGIFs)); } updateSearchInterface(); } - }); - } - - if (selectedAlbum == null) { - if (type == 0) { - searchItem.getSearchField().setHint(LocaleController.getString("SearchImagesTitle", R.string.SearchImagesTitle)); - } else if (type == 1) { - searchItem.getSearchField().setHint(LocaleController.getString("SearchGifsTitle", R.string.SearchGifsTitle)); } - } - fragmentView = new FrameLayout(getParentActivity()); - - FrameLayout frameLayout = (FrameLayout) fragmentView; - frameLayout.setBackgroundColor(0xff000000); - - listView = new GridView(getParentActivity()); - listView.setPadding(AndroidUtilities.dp(4), AndroidUtilities.dp(4), AndroidUtilities.dp(4), AndroidUtilities.dp(4)); - listView.setClipToPadding(false); - listView.setDrawSelectorOnTop(true); - listView.setStretchMode(GridView.STRETCH_COLUMN_WIDTH); - listView.setHorizontalScrollBarEnabled(false); - listView.setVerticalScrollBarEnabled(false); - listView.setNumColumns(GridView.AUTO_FIT); - listView.setVerticalSpacing(AndroidUtilities.dp(4)); - listView.setHorizontalSpacing(AndroidUtilities.dp(4)); - listView.setSelector(R.drawable.list_selector); - frameLayout.addView(listView); - FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.bottomMargin = singlePhoto ? 0 : AndroidUtilities.dp(48); - listView.setLayoutParams(layoutParams); - listView.setAdapter(listAdapter = new ListAdapter(getParentActivity())); - AndroidUtilities.setListViewEdgeEffectColor(listView, 0xff333333); - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override - public void onItemClick(AdapterView adapterView, View view, int i, long l) { - ArrayList arrayList = null; - if (selectedAlbum != null) { - arrayList = (ArrayList) selectedAlbum.photos; - } else { - if (searchResult.isEmpty() && lastSearchString == null) { - arrayList = (ArrayList) recentImages; - } else { - arrayList = (ArrayList) searchResult; - } - } - if (i < 0 || i >= arrayList.size()) { + public void onSearchPressed(EditText editText) { + if (editText.getText().toString().length() == 0) { return; } - PhotoViewer.getInstance().setParentActivity(getParentActivity()); - PhotoViewer.getInstance().openPhotoForSelect(arrayList, i, singlePhoto ? 1 : 0, PhotoPickerActivity.this); + searchResult.clear(); + searchResultKeys.clear(); + nextSearchBingString = null; + giphySearchEndReached = true; + if (type == 0) { + searchBingImages(editText.getText().toString(), 0, 53); + } else if (type == 1) { + searchGiphyImages(editText.getText().toString(), 0, 53); + } + lastSearchString = editText.getText().toString(); + if (lastSearchString.length() == 0) { + lastSearchString = null; + if (type == 0) { + emptyView.setText(LocaleController.getString("NoRecentPhotos", R.string.NoRecentPhotos)); + } else if (type == 1) { + emptyView.setText(LocaleController.getString("NoRecentGIFs", R.string.NoRecentGIFs)); + } + } else { + emptyView.setText(LocaleController.getString("NoResult", R.string.NoResult)); + } + updateSearchInterface(); + } + }); + } + + if (selectedAlbum == null) { + if (type == 0) { + searchItem.getSearchField().setHint(LocaleController.getString("SearchImagesTitle", R.string.SearchImagesTitle)); + } else if (type == 1) { + searchItem.getSearchField().setHint(LocaleController.getString("SearchGifsTitle", R.string.SearchGifsTitle)); + } + } + + fragmentView = new FrameLayout(context); + + FrameLayout frameLayout = (FrameLayout) fragmentView; + frameLayout.setBackgroundColor(0xff000000); + + listView = new GridView(context); + listView.setPadding(AndroidUtilities.dp(4), AndroidUtilities.dp(4), AndroidUtilities.dp(4), AndroidUtilities.dp(4)); + listView.setClipToPadding(false); + listView.setDrawSelectorOnTop(true); + listView.setStretchMode(GridView.STRETCH_COLUMN_WIDTH); + listView.setHorizontalScrollBarEnabled(false); + listView.setVerticalScrollBarEnabled(false); + listView.setNumColumns(GridView.AUTO_FIT); + listView.setVerticalSpacing(AndroidUtilities.dp(4)); + listView.setHorizontalSpacing(AndroidUtilities.dp(4)); + listView.setSelector(R.drawable.list_selector); + frameLayout.addView(listView); + FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.bottomMargin = singlePhoto ? 0 : AndroidUtilities.dp(48); + listView.setLayoutParams(layoutParams); + listView.setAdapter(listAdapter = new ListAdapter(context)); + AndroidUtilities.setListViewEdgeEffectColor(listView, 0xff333333); + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, int i, long l) { + ArrayList arrayList = null; + if (selectedAlbum != null) { + arrayList = (ArrayList) selectedAlbum.photos; + } else { + if (searchResult.isEmpty() && lastSearchString == null) { + arrayList = (ArrayList) recentImages; + } else { + arrayList = (ArrayList) searchResult; + } + } + if (i < 0 || i >= arrayList.size()) { + return; + } + PhotoViewer.getInstance().setParentActivity(getParentActivity()); + PhotoViewer.getInstance().openPhotoForSelect(arrayList, i, singlePhoto ? 1 : 0, PhotoPickerActivity.this); + } + }); + + if (selectedAlbum == null) { + listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { + @Override + public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { + if (searchResult.isEmpty() && lastSearchString == null) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + builder.setMessage(LocaleController.getString("ClearSearch", R.string.ClearSearch)); + builder.setPositiveButton(LocaleController.getString("ClearButton", R.string.ClearButton).toUpperCase(), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + recentImages.clear(); + if (listAdapter != null) { + listAdapter.notifyDataSetChanged(); + } + MessagesStorage.getInstance().clearWebRecent(type); + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + return true; + } + return false; + } + }); + } + + emptyView = new TextView(context); + emptyView.setTextColor(0xff808080); + emptyView.setTextSize(20); + emptyView.setGravity(Gravity.CENTER); + emptyView.setVisibility(View.GONE); + if (selectedAlbum != null) { + emptyView.setText(LocaleController.getString("NoPhotos", R.string.NoPhotos)); + } else { + if (type == 0) { + emptyView.setText(LocaleController.getString("NoRecentPhotos", R.string.NoRecentPhotos)); + } else if (type == 1) { + emptyView.setText(LocaleController.getString("NoRecentGIFs", R.string.NoRecentGIFs)); + } + } + frameLayout.addView(emptyView); + layoutParams = (FrameLayout.LayoutParams) emptyView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.bottomMargin = singlePhoto ? 0 : AndroidUtilities.dp(48); + emptyView.setLayoutParams(layoutParams); + emptyView.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + + if (selectedAlbum == null) { + listView.setOnScrollListener(new AbsListView.OnScrollListener() { + @Override + public void onScrollStateChanged(AbsListView absListView, int i) { + if (i == SCROLL_STATE_TOUCH_SCROLL) { + AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus()); + } + } + + @Override + public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + if (visibleItemCount != 0 && firstVisibleItem + visibleItemCount > totalItemCount - 2 && !searching) { + if (type == 0 && nextSearchBingString != null) { + searchBingImages(lastSearchString, searchResult.size(), 54); + } else if (type == 1 && !giphySearchEndReached) { + searchGiphyImages(searchItem.getSearchField().getText().toString(), searchResult.size(), 54); + } + } } }); - if (selectedAlbum == null) { - listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { - @Override - public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { - if (searchResult.isEmpty() && lastSearchString == null) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setMessage(LocaleController.getString("ClearSearch", R.string.ClearSearch)); - builder.setPositiveButton(LocaleController.getString("ClearButton", R.string.ClearButton).toUpperCase(), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - recentImages.clear(); - if (listAdapter != null) { - listAdapter.notifyDataSetChanged(); - } - MessagesStorage.getInstance().clearWebRecent(type); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - return true; - } - return false; - } - }); - } - - emptyView = new TextView(getParentActivity()); - emptyView.setTextColor(0xff808080); - emptyView.setTextSize(20); - emptyView.setGravity(Gravity.CENTER); - emptyView.setVisibility(View.GONE); - if (selectedAlbum != null) { - emptyView.setText(LocaleController.getString("NoPhotos", R.string.NoPhotos)); - } else { - if (type == 0) { - emptyView.setText(LocaleController.getString("NoRecentPhotos", R.string.NoRecentPhotos)); - } else if (type == 1) { - emptyView.setText(LocaleController.getString("NoRecentGIFs", R.string.NoRecentGIFs)); - } - } - frameLayout.addView(emptyView); - layoutParams = (FrameLayout.LayoutParams) emptyView.getLayoutParams(); + progressView = new FrameLayout(context); + progressView.setVisibility(View.GONE); + frameLayout.addView(progressView); + layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams(); layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; layoutParams.bottomMargin = singlePhoto ? 0 : AndroidUtilities.dp(48); - emptyView.setLayoutParams(layoutParams); - emptyView.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - return true; - } - }); + progressView.setLayoutParams(layoutParams); - if (selectedAlbum == null) { - listView.setOnScrollListener(new AbsListView.OnScrollListener() { - @Override - public void onScrollStateChanged(AbsListView absListView, int i) { - if (i == SCROLL_STATE_TOUCH_SCROLL) { - AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus()); - } - } + ProgressBar progressBar = new ProgressBar(context); + progressView.addView(progressBar); + layoutParams = (FrameLayout.LayoutParams) progressBar.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.gravity = Gravity.CENTER; + progressBar.setLayoutParams(layoutParams); - @Override - public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - if (visibleItemCount != 0 && firstVisibleItem + visibleItemCount > totalItemCount - 2 && !searching) { - if (type == 0 && nextSearchBingString != null) { - searchBingImages(lastSearchString, searchResult.size(), 54); - } else if (type == 1 && !giphySearchEndReached) { - searchGiphyImages(searchItem.getSearchField().getText().toString(), searchResult.size(), 54); - } - } - } - }); - - progressView = new FrameLayout(getParentActivity()); - progressView.setVisibility(View.GONE); - frameLayout.addView(progressView); - layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.bottomMargin = singlePhoto ? 0 : AndroidUtilities.dp(48); - progressView.setLayoutParams(layoutParams); - - ProgressBar progressBar = new ProgressBar(getParentActivity()); - progressView.addView(progressBar); - layoutParams = (FrameLayout.LayoutParams) progressBar.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.gravity = Gravity.CENTER; - progressBar.setLayoutParams(layoutParams); - - updateSearchInterface(); - } - - photoPickerBottomLayout = new PhotoPickerBottomLayout(getParentActivity()); - frameLayout.addView(photoPickerBottomLayout); - layoutParams = (FrameLayout.LayoutParams) photoPickerBottomLayout.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = AndroidUtilities.dp(48); - layoutParams.gravity = Gravity.BOTTOM; - photoPickerBottomLayout.setLayoutParams(layoutParams); - photoPickerBottomLayout.cancelButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - delegate.actionButtonPressed(true); - finishFragment(); - } - }); - photoPickerBottomLayout.doneButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - sendSelectedPhotos(); - } - }); - if (singlePhoto) { - photoPickerBottomLayout.setVisibility(View.GONE); - } - - listView.setEmptyView(emptyView); - photoPickerBottomLayout.updateSelectedCount(selectedPhotos.size() + selectedWebPhotos.size(), true); - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); - } + updateSearchInterface(); } + + photoPickerBottomLayout = new PhotoPickerBottomLayout(context); + frameLayout.addView(photoPickerBottomLayout); + layoutParams = (FrameLayout.LayoutParams) photoPickerBottomLayout.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = AndroidUtilities.dp(48); + layoutParams.gravity = Gravity.BOTTOM; + photoPickerBottomLayout.setLayoutParams(layoutParams); + photoPickerBottomLayout.cancelButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + delegate.actionButtonPressed(true); + finishFragment(); + } + }); + photoPickerBottomLayout.doneButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + sendSelectedPhotos(); + } + }); + if (singlePhoto) { + photoPickerBottomLayout.setVisibility(View.GONE); + } + + listView.setEmptyView(emptyView); + photoPickerBottomLayout.updateSelectedCount(selectedPhotos.size() + selectedWebPhotos.size(), true); + return fragmentView; } @@ -488,7 +482,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen object.viewX = coords[0]; object.viewY = coords[1] - AndroidUtilities.statusBarHeight; object.parentView = listView; - object.imageReceiver = cell.photoImage.imageReceiver; + object.imageReceiver = cell.photoImage.getImageReceiver(); object.thumb = object.imageReceiver.getBitmap(); cell.checkBox.setVisibility(View.GONE); return object; @@ -534,7 +528,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen public Bitmap getThumbForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) { PhotoPickerPhotoCell cell = getCellForIndex(index); if (cell != null) { - return cell.photoImage.imageReceiver.getBitmap(); + return cell.photoImage.getImageReceiver().getBitmap(); } return null; } @@ -1057,7 +1051,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen cell.checkBox.setChecked(selectedWebPhotos.containsKey(photoEntry.id), false); showing = PhotoViewer.getInstance().isShowingImage(photoEntry.thumbUrl); } - imageView.imageReceiver.setVisible(!showing, false); + imageView.getImageReceiver().setVisible(!showing, false); cell.checkBox.setVisibility(singlePhoto || showing ? View.GONE : View.VISIBLE); } else if (viewType == 1) { if (view == null) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/PopupNotificationActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/PopupNotificationActivity.java index e6104eb0e..b8a8832d8 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/PopupNotificationActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/PopupNotificationActivity.java @@ -207,7 +207,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC } @Override - public void onTextChanged(CharSequence text) { + public void onTextChanged(CharSequence text, boolean big) { } @@ -264,8 +264,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC avatarContainer.setLayoutParams(layoutParams2); avatarImageView = new BackupImageView(this); - avatarImageView.imageReceiver.setRoundRadius(AndroidUtilities.dp(21)); - avatarImageView.processDetach = false; + avatarImageView.setRoundRadius(AndroidUtilities.dp(21)); avatarContainer.addView(avatarImageView); layoutParams2 = (FrameLayout.LayoutParams) avatarImageView.getLayoutParams(); layoutParams2.width = AndroidUtilities.dp(42); @@ -549,7 +548,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC TextView messageText = (TextView)view.findViewById(R.id.message_text); BackupImageView imageView = (BackupImageView) view.findViewById(R.id.message_image); - imageView.imageReceiver.setAspectFit(true); + imageView.setAspectFit(true); if (messageObject.type == 1) { TLRPC.PhotoSize currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, AndroidUtilities.getPhotoSize()); @@ -986,6 +985,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC } ConnectionsManager.getInstance().setAppPaused(false, false); fixLayout(); + checkAndUpdateAvatar(); wakeLock.acquire(7000); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/PrivacySettingsActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/PrivacySettingsActivity.java index 0fdf3a59f..6f5d0e901 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/PrivacySettingsActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/PrivacySettingsActivity.java @@ -19,12 +19,10 @@ import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.FrameLayout; import android.widget.ListView; -import android.widget.Toast; import org.telegram.android.AndroidUtilities; import org.telegram.android.ContactsController; import org.telegram.android.LocaleController; -import org.telegram.android.MessagesController; import org.telegram.android.NotificationCenter; import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.FileLog; @@ -51,10 +49,10 @@ public class PrivacySettingsActivity extends BaseFragment implements Notificatio private int lastSeenRow; private int lastSeenDetailRow; private int securitySectionRow; - private int terminateSessionsRow; + private int sessionsRow; private int passwordRow; private int passcodeRow; - private int terminateSessionsDetailRow; + private int sessionsDetailRow; private int deleteAccountSectionRow; private int deleteAccountRow; private int deleteAccountDetailRow; @@ -73,12 +71,12 @@ public class PrivacySettingsActivity extends BaseFragment implements Notificatio lastSeenDetailRow = rowCount++; securitySectionRow = rowCount++; passcodeRow = rowCount++; - terminateSessionsRow = rowCount++; - terminateSessionsDetailRow = rowCount++; + passwordRow = rowCount++; + sessionsRow = rowCount++; + sessionsDetailRow = rowCount++; deleteAccountSectionRow = rowCount++; deleteAccountRow = rowCount++; deleteAccountDetailRow = rowCount++; - passwordRow = -1; NotificationCenter.getInstance().addObserver(this, NotificationCenter.privacyRulesUpdated); @@ -92,158 +90,114 @@ public class PrivacySettingsActivity extends BaseFragment implements Notificatio } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - actionBar.setTitle(LocaleController.getString("PrivacySettings", R.string.PrivacySettings)); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setAllowOverlayTitle(true); + actionBar.setTitle(LocaleController.getString("PrivacySettings", R.string.PrivacySettings)); + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); } - }); - - listAdapter = new ListAdapter(getParentActivity()); - - fragmentView = new FrameLayout(getParentActivity()); - FrameLayout frameLayout = (FrameLayout) fragmentView; - frameLayout.setBackgroundColor(0xfff0f0f0); - - ListView listView = new ListView(getParentActivity()); - listView.setDivider(null); - listView.setDividerHeight(0); - listView.setVerticalScrollBarEnabled(false); - listView.setDrawSelectorOnTop(true); - frameLayout.addView(listView); - FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.gravity = Gravity.TOP; - listView.setLayoutParams(layoutParams); - listView.setAdapter(listAdapter); - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, final int i, long l) { - if (i == blockedRow) { - presentFragment(new BlockedUsersActivity()); - } else if (i == terminateSessionsRow) { - if (getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setMessage(LocaleController.getString("AreYouSureSessions", R.string.AreYouSureSessions)); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - TLRPC.TL_auth_resetAuthorizations req = new TLRPC.TL_auth_resetAuthorizations(); - ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { - @Override - public void run(final TLObject response, final TLRPC.TL_error error) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - if (getParentActivity() == null) { - return; - } - if (error == null && response instanceof TLRPC.TL_boolTrue) { - Toast toast = Toast.makeText(getParentActivity(), LocaleController.getString("TerminateAllSessions", R.string.TerminateAllSessions), Toast.LENGTH_SHORT); - toast.show(); - } else { - Toast toast = Toast.makeText(getParentActivity(), LocaleController.getString("UnknownError", R.string.UnknownError), Toast.LENGTH_SHORT); - toast.show(); - } - } - }); - UserConfig.registeredForPush = false; - UserConfig.registeredForInternalPush = false; - UserConfig.saveConfig(false); - MessagesController.getInstance().registerForPush(UserConfig.pushString); - ConnectionsManager.getInstance().initPushConnection(); - } - }); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } else if (i == deleteAccountRow) { - if (getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("DeleteAccountTitle", R.string.DeleteAccountTitle)); - builder.setItems(new CharSequence[] { - LocaleController.formatPluralString("Months", 1), - LocaleController.formatPluralString("Months", 3), - LocaleController.formatPluralString("Months", 6), - LocaleController.formatPluralString("Years", 1) - }, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - int value = 0; - if (which == 0) { - value = 30; - } else if (which == 1) { - value = 90; - } else if (which == 2) { - value = 182; - } else if (which == 3) { - value = 365; - } - final ProgressDialog progressDialog = new ProgressDialog(getParentActivity()); - progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading)); - progressDialog.setCanceledOnTouchOutside(false); - progressDialog.setCancelable(false); - progressDialog.show(); - - final TLRPC.TL_account_setAccountTTL req = new TLRPC.TL_account_setAccountTTL(); - req.ttl = new TLRPC.TL_accountDaysTTL(); - req.ttl.days = value; - ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { - @Override - public void run(final TLObject response, final TLRPC.TL_error error) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - try { - progressDialog.dismiss(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - if (response instanceof TLRPC.TL_boolTrue) { - ContactsController.getInstance().setDeleteAccountTTL(req.ttl.days); - listAdapter.notifyDataSetChanged(); - } - } - }); - } - }); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } else if (i == lastSeenRow) { - presentFragment(new LastSeenActivity()); - } else if (i == passwordRow) { - presentFragment(new AccountPasswordActivity(0)); - } else if (i == passcodeRow) { - if (UserConfig.passcodeHash.length() > 0) { - presentFragment(new PasscodeActivity(2)); - } else { - presentFragment(new PasscodeActivity(0)); - } - } - } - }); - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); } - } + }); + + listAdapter = new ListAdapter(context); + + fragmentView = new FrameLayout(context); + FrameLayout frameLayout = (FrameLayout) fragmentView; + frameLayout.setBackgroundColor(0xfff0f0f0); + + ListView listView = new ListView(context); + listView.setDivider(null); + listView.setDividerHeight(0); + listView.setVerticalScrollBarEnabled(false); + listView.setDrawSelectorOnTop(true); + frameLayout.addView(listView); + FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.gravity = Gravity.TOP; + listView.setLayoutParams(layoutParams); + listView.setAdapter(listAdapter); + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, final int i, long l) { + if (i == blockedRow) { + presentFragment(new BlockedUsersActivity()); + } else if (i == sessionsRow) { + presentFragment(new SessionsActivity()); + } else if (i == deleteAccountRow) { + if (getParentActivity() == null) { + return; + } + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("DeleteAccountTitle", R.string.DeleteAccountTitle)); + builder.setItems(new CharSequence[]{ + LocaleController.formatPluralString("Months", 1), + LocaleController.formatPluralString("Months", 3), + LocaleController.formatPluralString("Months", 6), + LocaleController.formatPluralString("Years", 1) + }, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + int value = 0; + if (which == 0) { + value = 30; + } else if (which == 1) { + value = 90; + } else if (which == 2) { + value = 182; + } else if (which == 3) { + value = 365; + } + final ProgressDialog progressDialog = new ProgressDialog(getParentActivity()); + progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading)); + progressDialog.setCanceledOnTouchOutside(false); + progressDialog.setCancelable(false); + progressDialog.show(); + + final TLRPC.TL_account_setAccountTTL req = new TLRPC.TL_account_setAccountTTL(); + req.ttl = new TLRPC.TL_accountDaysTTL(); + req.ttl.days = value; + ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(final TLObject response, final TLRPC.TL_error error) { + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + try { + progressDialog.dismiss(); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + if (response instanceof TLRPC.TL_boolTrue) { + ContactsController.getInstance().setDeleteAccountTTL(req.ttl.days); + listAdapter.notifyDataSetChanged(); + } + } + }); + } + }); + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } else if (i == lastSeenRow) { + presentFragment(new LastSeenActivity()); + } else if (i == passwordRow) { + presentFragment(new TwoStepVerificationActivity(0)); + } else if (i == passcodeRow) { + if (UserConfig.passcodeHash.length() > 0) { + presentFragment(new PasscodeActivity(2)); + } else { + presentFragment(new PasscodeActivity(0)); + } + } + } + }); + return fragmentView; } @@ -327,7 +281,7 @@ public class PrivacySettingsActivity extends BaseFragment implements Notificatio @Override public boolean isEnabled(int i) { - return i == passcodeRow || i == passwordRow || i == blockedRow || i == terminateSessionsRow || i == lastSeenRow && !ContactsController.getInstance().getLoadingLastSeenInfo() || i == deleteAccountRow && !ContactsController.getInstance().getLoadingDeleteInfo(); + return i == passcodeRow || i == passwordRow || i == blockedRow || i == sessionsRow || i == lastSeenRow && !ContactsController.getInstance().getLoadingLastSeenInfo() || i == deleteAccountRow && !ContactsController.getInstance().getLoadingDeleteInfo(); } @Override @@ -361,10 +315,10 @@ public class PrivacySettingsActivity extends BaseFragment implements Notificatio TextSettingsCell textCell = (TextSettingsCell) view; if (i == blockedRow) { textCell.setText(LocaleController.getString("BlockedUsers", R.string.BlockedUsers), true); - } else if (i == terminateSessionsRow) { - textCell.setText(LocaleController.getString("TerminateAllSessions", R.string.TerminateAllSessions), false); + } else if (i == sessionsRow) { + textCell.setText(LocaleController.getString("SessionsTitle", R.string.SessionsTitle), false); } else if (i == passwordRow) { - textCell.setText(LocaleController.getString("Password", R.string.Password), true); + textCell.setText(LocaleController.getString("TwoStepVerification", R.string.TwoStepVerification), true); } else if (i == passcodeRow) { textCell.setText(LocaleController.getString("Passcode", R.string.Passcode), true); } else if (i == lastSeenRow) { @@ -401,8 +355,8 @@ public class PrivacySettingsActivity extends BaseFragment implements Notificatio } else if (i == lastSeenDetailRow) { ((TextInfoPrivacyCell) view).setText(LocaleController.getString("LastSeenHelp", R.string.LastSeenHelp)); view.setBackgroundResource(R.drawable.greydivider); - } else if (i == terminateSessionsDetailRow) { - ((TextInfoPrivacyCell) view).setText(LocaleController.getString("ClearOtherSessionsHelp", R.string.ClearOtherSessionsHelp)); + } else if (i == sessionsDetailRow) { + ((TextInfoPrivacyCell) view).setText(LocaleController.getString("SessionsInfo", R.string.SessionsInfo)); view.setBackgroundResource(R.drawable.greydivider); } } else if (type == 2) { @@ -423,9 +377,9 @@ public class PrivacySettingsActivity extends BaseFragment implements Notificatio @Override public int getItemViewType(int i) { - if (i == lastSeenRow || i == blockedRow || i == deleteAccountRow || i == terminateSessionsRow || i == passwordRow || i == passcodeRow) { + if (i == lastSeenRow || i == blockedRow || i == deleteAccountRow || i == sessionsRow || i == passwordRow || i == passcodeRow) { return 0; - } else if (i == deleteAccountDetailRow || i == lastSeenDetailRow || i == terminateSessionsDetailRow) { + } else if (i == deleteAccountDetailRow || i == lastSeenDetailRow || i == sessionsDetailRow) { return 1; } else if (i == securitySectionRow || i == deleteAccountSectionRow || i == privacySectionRow) { return 2; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ProfileActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ProfileActivity.java index c697dccc2..99fae5d7e 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ProfileActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ProfileActivity.java @@ -20,7 +20,6 @@ import android.graphics.Outline; import android.net.Uri; import android.os.Build; import android.os.Bundle; -import android.text.Html; import android.text.TextUtils; import android.util.TypedValue; import android.view.Gravity; @@ -208,9 +207,6 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. @Override public void onFragmentDestroy() { super.onFragmentDestroy(); - if (avatarImage != null) { - avatarImage.setImageDrawable(null); - } NotificationCenter.getInstance().removeObserver(this, NotificationCenter.mediaCountDidLoaded); NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces); NotificationCenter.getInstance().removeObserver(this, NotificationCenter.closeChats); @@ -227,434 +223,425 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setBackgroundColor(AvatarDrawable.getProfileBackColorForId(user_id != 0 ? 5 : chat_id)); - actionBar.setItemsBackground(AvatarDrawable.getButtonColorForId(user_id != 0 ? 5 : chat_id)); - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setExtraHeight(AndroidUtilities.dp(88), false); - if (AndroidUtilities.isTablet()) { - actionBar.setOccupyStatusBar(false); + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackgroundColor(AvatarDrawable.getProfileBackColorForId(user_id != 0 ? 5 : chat_id)); + actionBar.setItemsBackground(AvatarDrawable.getButtonColorForId(user_id != 0 ? 5 : chat_id)); + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setExtraHeight(AndroidUtilities.dp(88), false); + if (AndroidUtilities.isTablet()) { + actionBar.setOccupyStatusBar(false); + } + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(final int id) { + if (getParentActivity() == null) { + return; + } + if (id == -1) { + finishFragment(); + } else if (id == block_contact) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + if (!userBlocked) { + builder.setMessage(LocaleController.getString("AreYouSureBlockContact", R.string.AreYouSureBlockContact)); + } else { + builder.setMessage(LocaleController.getString("AreYouSureUnblockContact", R.string.AreYouSureUnblockContact)); + } + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + if (!userBlocked) { + MessagesController.getInstance().blockUser(user_id); + } else { + MessagesController.getInstance().unblockUser(user_id); + } + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } else if (id == add_contact) { + TLRPC.User user = MessagesController.getInstance().getUser(user_id); + Bundle args = new Bundle(); + args.putInt("user_id", user.id); + presentFragment(new ContactAddActivity(args)); + } else if (id == share_contact) { + Bundle args = new Bundle(); + args.putBoolean("onlySelect", true); + args.putBoolean("serverOnly", true); + MessagesActivity fragment = new MessagesActivity(args); + fragment.setDelegate(ProfileActivity.this); + presentFragment(fragment); + } else if (id == edit_contact) { + Bundle args = new Bundle(); + args.putInt("user_id", user_id); + presentFragment(new ContactAddActivity(args)); + } else if (id == delete_contact) { + final TLRPC.User user = MessagesController.getInstance().getUser(user_id); + if (user == null || getParentActivity() == null) { + return; + } + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setMessage(LocaleController.getString("AreYouSureDeleteContact", R.string.AreYouSureDeleteContact)); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + ArrayList arrayList = new ArrayList<>(); + arrayList.add(user); + ContactsController.getInstance().deleteContact(arrayList); + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } else if (id == add_member) { + Bundle args = new Bundle(); + args.putBoolean("onlyUsers", true); + args.putBoolean("destroyAfterSelect", true); + args.putBoolean("returnAsResult", true); + //args.putBoolean("allowUsernameSearch", false); + if (chat_id > 0) { + args.putString("selectAlertString", LocaleController.getString("AddToTheGroup", R.string.AddToTheGroup)); + } + ContactsActivity fragment = new ContactsActivity(args); + fragment.setDelegate(new ContactsActivity.ContactsActivityDelegate() { + @Override + public void didSelectContact(TLRPC.User user, String param) { + MessagesController.getInstance().addUserToChat(chat_id, user, info, param != null ? Utilities.parseInt(param) : 0); + } + }); + if (info != null) { + HashMap users = new HashMap<>(); + for (TLRPC.TL_chatParticipant p : info.participants) { + users.put(p.user_id, null); + } + fragment.setIgnoreUsers(users); + } + presentFragment(fragment); + } else if (id == leave_group) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setMessage(LocaleController.getString("AreYouSureDeleteAndExit", R.string.AreYouSureDeleteAndExit)); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + kickUser(null); + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } else if (id == edit_name) { + Bundle args = new Bundle(); + args.putInt("chat_id", chat_id); + presentFragment(new ChangeChatNameActivity(args)); + } } - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(final int id) { + }); + + createActionBarMenu(); + + listAdapter = new ListAdapter(context); + + fragmentView = new FrameLayout(context); + FrameLayout frameLayout = (FrameLayout) fragmentView; + + avatarImage = new BackupImageView(context); + avatarImage.setRoundRadius(AndroidUtilities.dp(30)); + actionBar.addView(avatarImage); + FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) avatarImage.getLayoutParams(); + layoutParams.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.BOTTOM; + layoutParams.width = AndroidUtilities.dp(60); + layoutParams.height = AndroidUtilities.dp(60); + layoutParams.leftMargin = LocaleController.isRTL ? 0 : AndroidUtilities.dp(17); + layoutParams.rightMargin = LocaleController.isRTL ? AndroidUtilities.dp(17) : 0; + layoutParams.bottomMargin = AndroidUtilities.dp(22); + avatarImage.setLayoutParams(layoutParams); + avatarImage.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (user_id != 0) { + TLRPC.User user = MessagesController.getInstance().getUser(user_id); + if (user.photo != null && user.photo.photo_big != null) { + PhotoViewer.getInstance().setParentActivity(getParentActivity()); + PhotoViewer.getInstance().openPhoto(user.photo.photo_big, ProfileActivity.this); + } + } else if (chat_id != 0) { + TLRPC.Chat chat = MessagesController.getInstance().getChat(chat_id); + if (chat.photo != null && chat.photo.photo_big != null) { + PhotoViewer.getInstance().setParentActivity(getParentActivity()); + PhotoViewer.getInstance().openPhoto(chat.photo.photo_big, ProfileActivity.this); + } + } + } + }); + + nameTextView = new TextView(context); + nameTextView.setTextColor(0xffffffff); + nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); + nameTextView.setLines(1); + nameTextView.setMaxLines(1); + nameTextView.setSingleLine(true); + nameTextView.setEllipsize(TextUtils.TruncateAt.END); + nameTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); + nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); + actionBar.addView(nameTextView); + layoutParams = (FrameLayout.LayoutParams) nameTextView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.leftMargin = AndroidUtilities.dp(LocaleController.isRTL ? 16 : 97); + layoutParams.rightMargin = AndroidUtilities.dp(LocaleController.isRTL ? 97 : 16); + layoutParams.bottomMargin = AndroidUtilities.dp(51); + layoutParams.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.BOTTOM; + nameTextView.setLayoutParams(layoutParams); + + onlineTextView = new TextView(context); + onlineTextView.setTextColor(AvatarDrawable.getProfileTextColorForId(user_id != 0 ? 5 : chat_id)); + onlineTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + onlineTextView.setLines(1); + onlineTextView.setMaxLines(1); + onlineTextView.setSingleLine(true); + onlineTextView.setEllipsize(TextUtils.TruncateAt.END); + onlineTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); + actionBar.addView(onlineTextView); + layoutParams = (FrameLayout.LayoutParams) onlineTextView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.leftMargin = AndroidUtilities.dp(LocaleController.isRTL ? 16 : 97); + layoutParams.rightMargin = AndroidUtilities.dp(LocaleController.isRTL ? 97 : 16); + layoutParams.bottomMargin = AndroidUtilities.dp(30); + layoutParams.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.BOTTOM; + onlineTextView.setLayoutParams(layoutParams); + + listView = new ListView(context); + listView.setDivider(null); + listView.setDividerHeight(0); + listView.setVerticalScrollBarEnabled(false); + AndroidUtilities.setListViewEdgeEffectColor(listView, AvatarDrawable.getProfileBackColorForId(user_id != 0 ? 5 : chat_id)); + frameLayout.addView(listView); + layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.gravity = Gravity.TOP; + listView.setLayoutParams(layoutParams); + + listView.setAdapter(listAdapter); + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, final int i, long l) { + if (getParentActivity() == null) { + return; + } + if (i == sharedMediaRow) { + Bundle args = new Bundle(); + if (user_id != 0) { + args.putLong("dialog_id", dialog_id != 0 ? dialog_id : user_id); + } else { + args.putLong("dialog_id", -chat_id); + } + presentFragment(new MediaActivity(args)); + } else if (i == settingsKeyRow) { + Bundle args = new Bundle(); + args.putInt("chat_id", (int) (dialog_id >> 32)); + presentFragment(new IdenticonActivity(args)); + } else if (i == settingsTimerRow) { if (getParentActivity() == null) { return; } - if (id == -1) { - finishFragment(); - } else if (id == block_contact) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - if (!userBlocked) { - builder.setMessage(LocaleController.getString("AreYouSureBlockContact", R.string.AreYouSureBlockContact)); - } else { - builder.setMessage(LocaleController.getString("AreYouSureUnblockContact", R.string.AreYouSureUnblockContact)); + showAlertDialog(AndroidUtilities.buildTTLAlert(getParentActivity(), currentEncryptedChat)); + } else if (i == settingsNotificationsRow) { + Bundle args = new Bundle(); + if (user_id != 0) { + args.putLong("dialog_id", dialog_id == 0 ? user_id : dialog_id); + } else if (chat_id != 0) { + args.putLong("dialog_id", -chat_id); + } + presentFragment(new ProfileNotificationsActivity(args)); + } else if (i == startSecretChatRow) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setMessage(LocaleController.getString("AreYouSureSecretChat", R.string.AreYouSureSecretChat)); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + creatingChat = true; + SecretChatHelper.getInstance().startSecretChat(getParentActivity(), MessagesController.getInstance().getUser(user_id)); } - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - if (!userBlocked) { - MessagesController.getInstance().blockUser(user_id); + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } else if (i == phoneRow) { + final TLRPC.User user = MessagesController.getInstance().getUser(user_id); + if (user == null || user.phone == null || user.phone.length() == 0 || getParentActivity() == null) { + return; + } + + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setItems(new CharSequence[]{LocaleController.getString("Call", R.string.Call), LocaleController.getString("Copy", R.string.Copy)}, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + if (i == 0) { + try { + Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:+" + user.phone)); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + getParentActivity().startActivityForResult(intent, 500); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } else if (i == 1) { + if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) { + android.text.ClipboardManager clipboard = (android.text.ClipboardManager) ApplicationLoader.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE); + clipboard.setText("+" + user.phone); } else { - MessagesController.getInstance().unblockUser(user_id); + android.content.ClipboardManager clipboard = (android.content.ClipboardManager) ApplicationLoader.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE); + android.content.ClipData clip = android.content.ClipData.newPlainText("label", "+" + user.phone); + clipboard.setPrimaryClip(clip); } } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } else if (id == add_contact) { - TLRPC.User user = MessagesController.getInstance().getUser(user_id); - Bundle args = new Bundle(); - args.putInt("user_id", user.id); - presentFragment(new ContactAddActivity(args)); - } else if (id == share_contact) { - Bundle args = new Bundle(); - args.putBoolean("onlySelect", true); - args.putBoolean("serverOnly", true); - MessagesActivity fragment = new MessagesActivity(args); - fragment.setDelegate(ProfileActivity.this); - presentFragment(fragment); - } else if (id == edit_contact) { - Bundle args = new Bundle(); - args.putInt("user_id", user_id); - presentFragment(new ContactAddActivity(args)); - } else if (id == delete_contact) { - final TLRPC.User user = MessagesController.getInstance().getUser(user_id); - if (user == null || getParentActivity() == null) { - return; } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setMessage(LocaleController.getString("AreYouSureDeleteContact", R.string.AreYouSureDeleteContact)); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - ArrayList arrayList = new ArrayList<>(); - arrayList.add(user); - ContactsController.getInstance().deleteContact(arrayList); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } else if (id == add_member) { - Bundle args = new Bundle(); - args.putBoolean("onlyUsers", true); - args.putBoolean("destroyAfterSelect", true); - args.putBoolean("returnAsResult", true); - //args.putBoolean("allowUsernameSearch", false); - if (chat_id > 0) { - args.putString("selectAlertString", LocaleController.getString("AddToTheGroup", R.string.AddToTheGroup)); - } - ContactsActivity fragment = new ContactsActivity(args); - fragment.setDelegate(new ContactsActivity.ContactsActivityDelegate() { - @Override - public void didSelectContact(TLRPC.User user, String param) { - MessagesController.getInstance().addUserToChat(chat_id, user, info, param != null ? Utilities.parseInt(param) : 0); - } - }); - if (info != null) { - HashMap users = new HashMap<>(); - for (TLRPC.TL_chatParticipant p : info.participants) { - users.put(p.user_id, null); - } - fragment.setIgnoreUsers(users); - } - presentFragment(fragment); - } else if (id == leave_group) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setMessage(LocaleController.getString("AreYouSureDeleteAndExit", R.string.AreYouSureDeleteAndExit)); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - kickUser(null); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } else if (id == edit_name) { - Bundle args = new Bundle(); - args.putInt("chat_id", chat_id); - presentFragment(new ChangeChatNameActivity(args)); - } - } - }); - - createActionBarMenu(); - - listAdapter = new ListAdapter(getParentActivity()); - - fragmentView = new FrameLayout(getParentActivity()); - FrameLayout frameLayout = (FrameLayout) fragmentView; - - avatarImage = new BackupImageView(getParentActivity()); - avatarImage.imageReceiver.setRoundRadius(AndroidUtilities.dp(30)); - avatarImage.processDetach = false; - actionBar.addView(avatarImage); - FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) avatarImage.getLayoutParams(); - layoutParams.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.BOTTOM; - layoutParams.width = AndroidUtilities.dp(60); - layoutParams.height = AndroidUtilities.dp(60); - layoutParams.leftMargin = LocaleController.isRTL ? 0 : AndroidUtilities.dp(17); - layoutParams.rightMargin = LocaleController.isRTL ? AndroidUtilities.dp(17) : 0; - layoutParams.bottomMargin = AndroidUtilities.dp(22); - avatarImage.setLayoutParams(layoutParams); - avatarImage.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (user_id != 0) { - TLRPC.User user = MessagesController.getInstance().getUser(user_id); - if (user.photo != null && user.photo.photo_big != null) { - PhotoViewer.getInstance().setParentActivity(getParentActivity()); - PhotoViewer.getInstance().openPhoto(user.photo.photo_big, ProfileActivity.this); - } - } else if (chat_id != 0) { - TLRPC.Chat chat = MessagesController.getInstance().getChat(chat_id); - if (chat.photo != null && chat.photo.photo_big != null) { - PhotoViewer.getInstance().setParentActivity(getParentActivity()); - PhotoViewer.getInstance().openPhoto(chat.photo.photo_big, ProfileActivity.this); - } - } - } - }); - - nameTextView = new TextView(getParentActivity()); - nameTextView.setTextColor(0xffffffff); - nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); - nameTextView.setLines(1); - nameTextView.setMaxLines(1); - nameTextView.setSingleLine(true); - nameTextView.setEllipsize(TextUtils.TruncateAt.END); - nameTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); - nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - actionBar.addView(nameTextView); - layoutParams = (FrameLayout.LayoutParams) nameTextView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.leftMargin = AndroidUtilities.dp(LocaleController.isRTL ? 16 : 97); - layoutParams.rightMargin = AndroidUtilities.dp(LocaleController.isRTL ? 97 : 16); - layoutParams.bottomMargin = AndroidUtilities.dp(51); - layoutParams.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.BOTTOM; - nameTextView.setLayoutParams(layoutParams); - - onlineTextView = new TextView(getParentActivity()); - onlineTextView.setTextColor(AvatarDrawable.getProfileTextColorForId(user_id != 0 ? 5 : chat_id)); - onlineTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - onlineTextView.setLines(1); - onlineTextView.setMaxLines(1); - onlineTextView.setSingleLine(true); - onlineTextView.setEllipsize(TextUtils.TruncateAt.END); - onlineTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); - actionBar.addView(onlineTextView); - layoutParams = (FrameLayout.LayoutParams) onlineTextView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.leftMargin = AndroidUtilities.dp(LocaleController.isRTL ? 16 : 97); - layoutParams.rightMargin = AndroidUtilities.dp(LocaleController.isRTL ? 97 : 16); - layoutParams.bottomMargin = AndroidUtilities.dp(30); - layoutParams.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.BOTTOM; - onlineTextView.setLayoutParams(layoutParams); - - listView = new ListView(getParentActivity()); - listView.setDivider(null); - listView.setDividerHeight(0); - listView.setVerticalScrollBarEnabled(false); - AndroidUtilities.setListViewEdgeEffectColor(listView, AvatarDrawable.getProfileBackColorForId(user_id != 0 ? 5 : chat_id)); - frameLayout.addView(listView); - layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.gravity = Gravity.TOP; - listView.setLayoutParams(layoutParams); - - listView.setAdapter(listAdapter); - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, final int i, long l) { - if (getParentActivity() == null) { + }); + showAlertDialog(builder); + } else if (i > emptyRowChat2 && i < membersEndRow) { + int user_id = info.participants.get(sortedUsers.get(i - emptyRowChat2 - 1)).user_id; + if (user_id == UserConfig.getClientUserId()) { return; } - if (i == sharedMediaRow) { - Bundle args = new Bundle(); - if (user_id != 0) { - args.putLong("dialog_id", dialog_id != 0 ? dialog_id : user_id); - } else { - args.putLong("dialog_id", -chat_id); - } - presentFragment(new MediaActivity(args)); - } else if (i == settingsKeyRow) { - Bundle args = new Bundle(); - args.putInt("chat_id", (int)(dialog_id >> 32)); - presentFragment(new IdenticonActivity(args)); - } else if (i == settingsTimerRow) { + Bundle args = new Bundle(); + args.putInt("user_id", user_id); + presentFragment(new ProfileActivity(args)); + } + } + }); + if (chat_id != 0) { + listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { + @Override + public boolean onItemLongClick(AdapterView adapterView, View view, int i, long l) { + if (i > emptyRowChat2 && i < membersEndRow) { if (getParentActivity() == null) { - return; - } - showAlertDialog(AndroidUtilities.buildTTLAlert(getParentActivity(), currentEncryptedChat)); - } else if (i == settingsNotificationsRow) { - Bundle args = new Bundle(); - if (user_id != 0) { - args.putLong("dialog_id", dialog_id == 0 ? user_id : dialog_id); - } else if (chat_id != 0) { - args.putLong("dialog_id", -chat_id); - } - presentFragment(new ProfileNotificationsActivity(args)); - } else if (i == startSecretChatRow) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setMessage(LocaleController.getString("AreYouSureSecretChat", R.string.AreYouSureSecretChat)); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - creatingChat = true; - SecretChatHelper.getInstance().startSecretChat(getParentActivity(), MessagesController.getInstance().getUser(user_id)); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } else if (i == phoneRow) { - final TLRPC.User user = MessagesController.getInstance().getUser(user_id); - if (user == null || user.phone == null || user.phone.length() == 0 || getParentActivity() == null) { - return; + return false; } + TLRPC.TL_chatParticipant user = info.participants.get(sortedUsers.get(i - emptyRowChat2 - 1)); + if (user.user_id == UserConfig.getClientUserId()) { + return false; + } + if (info.admin_id != UserConfig.getClientUserId() && user.inviter_id != UserConfig.getClientUserId()) { + return false; + } + selectedUser = user; + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setItems(new CharSequence[] {LocaleController.getString("Call", R.string.Call), LocaleController.getString("Copy", R.string.Copy)}, new DialogInterface.OnClickListener() { + CharSequence[] items = new CharSequence[]{chat_id > 0 ? LocaleController.getString("KickFromGroup", R.string.KickFromGroup) : LocaleController.getString("KickFromBroadcast", R.string.KickFromBroadcast)}; + + builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (i == 0) { - try { - Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:+" + user.phone)); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - getParentActivity().startActivityForResult(intent, 500); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } else if (i == 1) { - if(Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) { - android.text.ClipboardManager clipboard = (android.text.ClipboardManager) ApplicationLoader.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE); - clipboard.setText("+" + user.phone); - } else { - android.content.ClipboardManager clipboard = (android.content.ClipboardManager)ApplicationLoader.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE); - android.content.ClipData clip = android.content.ClipData.newPlainText("label", "+" + user.phone); - clipboard.setPrimaryClip(clip); - } + kickUser(selectedUser); } } }); showAlertDialog(builder); - } else if (i > emptyRowChat2 && i < membersEndRow) { - int user_id = info.participants.get(sortedUsers.get(i - emptyRowChat2 - 1)).user_id; - if (user_id == UserConfig.getClientUserId()) { + + return true; + } + return false; + } + }); + } + if (dialog_id != 0) { + SharedMediaQuery.getMediaCount(dialog_id, SharedMediaQuery.MEDIA_PHOTOVIDEO, classGuid, true); + } else { + SharedMediaQuery.getMediaCount(user_id, SharedMediaQuery.MEDIA_PHOTOVIDEO, classGuid, true); + } + + frameLayout.addView(actionBar); + + if (user_id != 0 || chat_id >= 0 && !currentChat.left) { + writeButton = new ImageView(context); + writeButton.setBackgroundResource(R.drawable.floating_user_states); + writeButton.setScaleType(ImageView.ScaleType.CENTER); + if (user_id != 0) { + writeButton.setImageResource(R.drawable.floating_message); + writeButton.setPadding(0, AndroidUtilities.dp(3), 0, 0); + } else if (chat_id != 0) { + writeButton.setImageResource(R.drawable.floating_camera); + } + frameLayout.addView(writeButton); + if (Build.VERSION.SDK_INT >= 21) { + StateListAnimator animator = new StateListAnimator(); + animator.addState(new int[]{android.R.attr.state_pressed}, ObjectAnimator.ofFloat(writeButton, "translationZ", AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200)); + animator.addState(new int[]{}, ObjectAnimator.ofFloat(writeButton, "translationZ", AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200)); + writeButton.setStateListAnimator(animator); + writeButton.setOutlineProvider(new ViewOutlineProvider() { + @Override + public void getOutline(View view, Outline outline) { + outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56)); + } + }); + } + layoutParams = (FrameLayout.LayoutParams) writeButton.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.leftMargin = AndroidUtilities.dp(LocaleController.isRTL ? 16 : 0); + layoutParams.rightMargin = AndroidUtilities.dp(LocaleController.isRTL ? 0 : 16); + layoutParams.gravity = (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT); + writeButton.setLayoutParams(layoutParams); + writeButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (getParentActivity() == null) { + return; + } + if (user_id != 0) { + TLRPC.User user = MessagesController.getInstance().getUser(user_id); + if (user == null || user instanceof TLRPC.TL_userEmpty) { return; } + NotificationCenter.getInstance().removeObserver(ProfileActivity.this, NotificationCenter.closeChats); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); Bundle args = new Bundle(); args.putInt("user_id", user_id); - presentFragment(new ProfileActivity(args)); + presentFragment(new ChatActivity(args), true); + } else if (chat_id != 0) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + CharSequence[] items; + TLRPC.Chat chat = MessagesController.getInstance().getChat(chat_id); + if (chat.photo == null || chat.photo.photo_big == null || chat.photo instanceof TLRPC.TL_chatPhotoEmpty) { + items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley)}; + } else { + items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("DeletePhoto", R.string.DeletePhoto)}; + } + + builder.setItems(items, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + int action = 0; + if (i == 0) { + avatarUpdater.openCamera(); + } else if (i == 1) { + avatarUpdater.openGallery(); + } else if (i == 2) { + MessagesController.getInstance().changeChatAvatar(chat_id, null); + } + } + }); + showAlertDialog(builder); } } }); - if (chat_id != 0) { - listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { - @Override - public boolean onItemLongClick(AdapterView adapterView, View view, int i, long l) { - if (i > emptyRowChat2 && i < membersEndRow) { - if (getParentActivity() == null) { - return false; - } - - TLRPC.TL_chatParticipant user = info.participants.get(sortedUsers.get(i - emptyRowChat2 - 1)); - if (user.user_id == UserConfig.getClientUserId()) { - return false; - } - if (info.admin_id != UserConfig.getClientUserId() && user.inviter_id != UserConfig.getClientUserId()) { - return false; - } - selectedUser = user; - - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - CharSequence[] items = new CharSequence[]{chat_id > 0 ? LocaleController.getString("KickFromGroup", R.string.KickFromGroup) : LocaleController.getString("KickFromBroadcast", R.string.KickFromBroadcast)}; - - builder.setItems(items, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - if (i == 0) { - kickUser(selectedUser); - } - } - }); - showAlertDialog(builder); - - return true; - } - return false; - } - }); - } - if (dialog_id != 0) { - SharedMediaQuery.getMediaCount(dialog_id, SharedMediaQuery.MEDIA_PHOTOVIDEO, classGuid, true); - } else { - SharedMediaQuery.getMediaCount(user_id, SharedMediaQuery.MEDIA_PHOTOVIDEO, classGuid, true); - } - - frameLayout.addView(actionBar); - - if (user_id != 0 || chat_id >= 0 && !currentChat.left) { - writeButton = new ImageView(getParentActivity()); - writeButton.setBackgroundResource(R.drawable.floating_user_states); - writeButton.setScaleType(ImageView.ScaleType.CENTER); - if (user_id != 0) { - writeButton.setImageResource(R.drawable.floating_message); - writeButton.setPadding(0, AndroidUtilities.dp(3), 0, 0); - } else if (chat_id != 0) { - writeButton.setImageResource(R.drawable.floating_camera); - } - frameLayout.addView(writeButton); - if (Build.VERSION.SDK_INT >= 21) { - StateListAnimator animator = new StateListAnimator(); - animator.addState(new int[] {android.R.attr.state_pressed}, ObjectAnimator.ofFloat(writeButton, "translationZ", AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200)); - animator.addState(new int[] {}, ObjectAnimator.ofFloat(writeButton, "translationZ", AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200)); - writeButton.setStateListAnimator(animator); - writeButton.setOutlineProvider(new ViewOutlineProvider() { - @Override - public void getOutline(View view, Outline outline) { - outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56)); - } - }); - } - layoutParams = (FrameLayout.LayoutParams) writeButton.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.leftMargin = AndroidUtilities.dp(LocaleController.isRTL ? 16 : 0); - layoutParams.rightMargin = AndroidUtilities.dp(LocaleController.isRTL ? 0 : 16); - layoutParams.gravity = (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT); - writeButton.setLayoutParams(layoutParams); - writeButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (getParentActivity() == null) { - return; - } - if (user_id != 0) { - TLRPC.User user = MessagesController.getInstance().getUser(user_id); - if (user == null || user instanceof TLRPC.TL_userEmpty) { - return; - } - NotificationCenter.getInstance().removeObserver(ProfileActivity.this, NotificationCenter.closeChats); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); - Bundle args = new Bundle(); - args.putInt("user_id", user_id); - presentFragment(new ChatActivity(args), true); - } else if (chat_id != 0) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - CharSequence[] items; - TLRPC.Chat chat = MessagesController.getInstance().getChat(chat_id); - if (chat.photo == null || chat.photo.photo_big == null || chat.photo instanceof TLRPC.TL_chatPhotoEmpty) { - items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley)}; - } else { - items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("DeletePhoto", R.string.DeletePhoto)}; - } - - builder.setItems(items, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - int action = 0; - if (i == 0) { - avatarUpdater.openCamera(); - } else if (i == 1) { - avatarUpdater.openGallery(); - } else if (i == 2) { - MessagesController.getInstance().changeChatAvatar(chat_id, null); - } - } - }); - showAlertDialog(builder); - } - } - }); - } - - listView.setOnScrollListener(new AbsListView.OnScrollListener() { - @Override - public void onScrollStateChanged(AbsListView view, int scrollState) { - - } - - @Override - public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - checkListViewScroll(); - } - }); - - updateProfileData(); - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); - } } + + listView.setOnScrollListener(new AbsListView.OnScrollListener() { + @Override + public void onScrollStateChanged(AbsListView view, int scrollState) { + + } + + @Override + public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + checkListViewScroll(); + } + }); + return fragmentView; } @@ -733,7 +720,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } } - avatarImage.imageReceiver.setRoundRadius(AndroidUtilities.dp(avatarSize / 2)); + avatarImage.setRoundRadius(AndroidUtilities.dp(avatarSize / 2)); layoutParams = (FrameLayout.LayoutParams) avatarImage.getLayoutParams(); layoutParams.width = AndroidUtilities.dp(avatarSize); layoutParams.height = AndroidUtilities.dp(avatarSize); @@ -889,6 +876,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. if (listAdapter != null) { listAdapter.notifyDataSetChanged(); } + updateProfileData(); fixLayout(); } @@ -924,11 +912,11 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. object.viewX = coords[0]; object.viewY = coords[1] - AndroidUtilities.statusBarHeight; object.parentView = avatarImage; - object.imageReceiver = avatarImage.imageReceiver; + object.imageReceiver = avatarImage.getImageReceiver(); object.user_id = user_id; object.thumb = object.imageReceiver.getBitmap(); object.size = -1; - object.radius = avatarImage.imageReceiver.getRoundRadius(); + object.radius = avatarImage.getImageReceiver().getRoundRadius(); return object; } return null; @@ -944,7 +932,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. @Override public void willHidePhotoViewer() { - avatarImage.imageReceiver.setVisible(true, true); + avatarImage.getImageReceiver().setVisible(true, true); } @Override @@ -1044,7 +1032,6 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. NotificationCenter.getInstance().removeObserver(this, NotificationCenter.closeChats); NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); MessagesController.getInstance().deleteUserFromChat(chat_id, MessagesController.getInstance().getUser(UserConfig.getClientUserId()), info); - MessagesController.getInstance().deleteDialog(-chat_id, 0, false); finishFragment(); } } @@ -1123,7 +1110,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } onlineTextView.setText(LocaleController.formatUserStatus(user)); - avatarImage.imageReceiver.setVisible(!PhotoViewer.getInstance().isShowingImage(photoBig), false); + avatarImage.getImageReceiver().setVisible(!PhotoViewer.getInstance().isShowingImage(photoBig), false); } else if (chat_id != 0) { TLRPC.Chat chat = MessagesController.getInstance().getChat(chat_id); if (chat != null) { @@ -1137,7 +1124,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } if (count != 0 && onlineCount > 1) { - onlineTextView.setText(Html.fromHtml(String.format("%s, %s", LocaleController.formatPluralString("Members", count), LocaleController.formatPluralString("Online", onlineCount)))); + onlineTextView.setText(String.format("%s, %s", LocaleController.formatPluralString("Members", count), LocaleController.formatPluralString("Online", onlineCount))); } else { onlineTextView.setText(LocaleController.formatPluralString("Members", count)); } @@ -1150,7 +1137,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } avatarImage.setImage(photo, "50_50", new AvatarDrawable(chat, true)); - avatarImage.imageReceiver.setVisible(!PhotoViewer.getInstance().isShowingImage(photoBig), false); + avatarImage.getImageReceiver().setVisible(!PhotoViewer.getInstance().isShowingImage(photoBig), false); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ProfileNotificationsActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ProfileNotificationsActivity.java index 59514828c..e845fd4de 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ProfileNotificationsActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ProfileNotificationsActivity.java @@ -85,220 +85,214 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - actionBar.setTitle(LocaleController.getString("NotificationsAndSounds", R.string.NotificationsAndSounds)); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setAllowOverlayTitle(true); + actionBar.setTitle(LocaleController.getString("NotificationsAndSounds", R.string.NotificationsAndSounds)); + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); } - }); - - fragmentView = new FrameLayout(getParentActivity()); - FrameLayout frameLayout = (FrameLayout) fragmentView; - - listView = new ListView(getParentActivity()); - listView.setDivider(null); - listView.setDividerHeight(0); - listView.setVerticalScrollBarEnabled(false); - AndroidUtilities.setListViewEdgeEffectColor(listView, AvatarDrawable.getProfileBackColorForId(5)); - frameLayout.addView(listView); - FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - listView.setLayoutParams(layoutParams); - listView.setAdapter(new ListAdapter(getParentActivity())); - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, final int i, long l) { - if (i == settingsVibrateRow) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("Vibrate", R.string.Vibrate)); - builder.setItems(new CharSequence[] { - LocaleController.getString("VibrationDisabled", R.string.VibrationDisabled), - LocaleController.getString("SettingsDefault", R.string.SettingsDefault), - LocaleController.getString("SystemDefault", R.string.SystemDefault), - LocaleController.getString("Short", R.string.Short), - LocaleController.getString("Long", R.string.Long) - }, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - if (which == 0) { - editor.putInt("vibrate_" + dialog_id, 2); - } else if (which == 1) { - editor.putInt("vibrate_" + dialog_id, 0); - } else if (which == 2) { - editor.putInt("vibrate_" + dialog_id, 4); - } else if (which == 3) { - editor.putInt("vibrate_" + dialog_id, 1); - } else if (which == 4) { - editor.putInt("vibrate_" + dialog_id, 3); - } - editor.commit(); - if (listView != null) { - listView.invalidateViews(); - } - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } else if (i == settingsNotificationsRow) { - if (getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setItems(new CharSequence[] { - LocaleController.getString("Default", R.string.Default), - LocaleController.getString("Enabled", R.string.Enabled), - LocaleController.getString("NotificationsDisabled", R.string.NotificationsDisabled) - }, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface d, int which) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - editor.putInt("notify2_" + dialog_id, which); - MessagesStorage.getInstance().setDialogFlags(dialog_id, which == 2 ? 1 : 0); - editor.commit(); - TLRPC.TL_dialog dialog = MessagesController.getInstance().dialogs_dict.get(dialog_id); - if (dialog != null) { - dialog.notify_settings = new TLRPC.TL_peerNotifySettings(); - if (which == 2) { - dialog.notify_settings.mute_until = Integer.MAX_VALUE; - } - } - if (listView != null) { - listView.invalidateViews(); - } - NotificationsController.updateServerNotificationsSettings(dialog_id); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } else if (i == settingsSoundRow) { - try { - Intent tmpIntent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER); - tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION); - tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true); - tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - Uri currentSound = null; - - String defaultPath = null; - Uri defaultUri = Settings.System.DEFAULT_NOTIFICATION_URI; - if (defaultUri != null) { - defaultPath = defaultUri.getPath(); - } - - String path = preferences.getString("sound_path_" + dialog_id, defaultPath); - if (path != null && !path.equals("NoSound")) { - if (path.equals(defaultPath)) { - currentSound = defaultUri; - } else { - currentSound = Uri.parse(path); - } - } - - tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, currentSound); - startActivityForResult(tmpIntent, 12); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } else if (i == settingsLedRow) { - if (getParentActivity() == null) { - return; - } - - LayoutInflater li = (LayoutInflater)getParentActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); - view = li.inflate(R.layout.settings_color_dialog_layout, null, false); - final ColorPickerView colorPickerView = (ColorPickerView)view.findViewById(R.id.color_picker); - - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - if (preferences.contains("color_" + dialog_id)) { - colorPickerView.setOldCenterColor(preferences.getInt("color_" + dialog_id, 0xff00ff00)); - } else { - if ((int)dialog_id < 0) { - colorPickerView.setOldCenterColor(preferences.getInt("GroupLed", 0xff00ff00)); - } else { - colorPickerView.setOldCenterColor(preferences.getInt("MessagesLed", 0xff00ff00)); - } - } - - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("LedColor", R.string.LedColor)); - builder.setView(view); - builder.setPositiveButton(LocaleController.getString("Set", R.string.Set), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int which) { - final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - editor.putInt("color_" + dialog_id, colorPickerView.getColor()); - editor.commit(); - listView.invalidateViews(); - } - }); - builder.setNeutralButton(LocaleController.getString("LedDisabled", R.string.LedDisabled), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - editor.putInt("color_" + dialog_id, 0); - editor.commit(); - listView.invalidateViews(); - } - }); - builder.setNegativeButton(LocaleController.getString("Default", R.string.Default), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - editor.remove("color_" + dialog_id); - editor.commit(); - listView.invalidateViews(); - } - }); - showAlertDialog(builder); - } else if (i == settingsPriorityRow) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("NotificationsPriority", R.string.NotificationsPriority)); - builder.setItems(new CharSequence[] { - LocaleController.getString("SettingsDefault", R.string.SettingsDefault), - LocaleController.getString("NotificationsPriorityDefault", R.string.NotificationsPriorityDefault), - LocaleController.getString("NotificationsPriorityHigh", R.string.NotificationsPriorityHigh), - LocaleController.getString("NotificationsPriorityMax", R.string.NotificationsPriorityMax) - }, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - if (which == 0) { - which = 3; - } else { - which--; - } - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - preferences.edit().putInt("priority_" + dialog_id, which).commit(); - if (listView != null) { - listView.invalidateViews(); - } - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } - } - }); - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); } - } + }); + + fragmentView = new FrameLayout(context); + FrameLayout frameLayout = (FrameLayout) fragmentView; + + listView = new ListView(context); + listView.setDivider(null); + listView.setDividerHeight(0); + listView.setVerticalScrollBarEnabled(false); + AndroidUtilities.setListViewEdgeEffectColor(listView, AvatarDrawable.getProfileBackColorForId(5)); + frameLayout.addView(listView); + FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + listView.setLayoutParams(layoutParams); + listView.setAdapter(new ListAdapter(context)); + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, final int i, long l) { + if (i == settingsVibrateRow) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("Vibrate", R.string.Vibrate)); + builder.setItems(new CharSequence[]{ + LocaleController.getString("VibrationDisabled", R.string.VibrationDisabled), + LocaleController.getString("SettingsDefault", R.string.SettingsDefault), + LocaleController.getString("SystemDefault", R.string.SystemDefault), + LocaleController.getString("Short", R.string.Short), + LocaleController.getString("Long", R.string.Long) + }, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + if (which == 0) { + editor.putInt("vibrate_" + dialog_id, 2); + } else if (which == 1) { + editor.putInt("vibrate_" + dialog_id, 0); + } else if (which == 2) { + editor.putInt("vibrate_" + dialog_id, 4); + } else if (which == 3) { + editor.putInt("vibrate_" + dialog_id, 1); + } else if (which == 4) { + editor.putInt("vibrate_" + dialog_id, 3); + } + editor.commit(); + if (listView != null) { + listView.invalidateViews(); + } + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } else if (i == settingsNotificationsRow) { + if (getParentActivity() == null) { + return; + } + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + builder.setItems(new CharSequence[]{ + LocaleController.getString("Default", R.string.Default), + LocaleController.getString("Enabled", R.string.Enabled), + LocaleController.getString("NotificationsDisabled", R.string.NotificationsDisabled) + }, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface d, int which) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + editor.putInt("notify2_" + dialog_id, which); + MessagesStorage.getInstance().setDialogFlags(dialog_id, which == 2 ? 1 : 0); + editor.commit(); + TLRPC.TL_dialog dialog = MessagesController.getInstance().dialogs_dict.get(dialog_id); + if (dialog != null) { + dialog.notify_settings = new TLRPC.TL_peerNotifySettings(); + if (which == 2) { + dialog.notify_settings.mute_until = Integer.MAX_VALUE; + } + } + if (listView != null) { + listView.invalidateViews(); + } + NotificationsController.updateServerNotificationsSettings(dialog_id); + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } else if (i == settingsSoundRow) { + try { + Intent tmpIntent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER); + tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION); + tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true); + tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + Uri currentSound = null; + + String defaultPath = null; + Uri defaultUri = Settings.System.DEFAULT_NOTIFICATION_URI; + if (defaultUri != null) { + defaultPath = defaultUri.getPath(); + } + + String path = preferences.getString("sound_path_" + dialog_id, defaultPath); + if (path != null && !path.equals("NoSound")) { + if (path.equals(defaultPath)) { + currentSound = defaultUri; + } else { + currentSound = Uri.parse(path); + } + } + + tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, currentSound); + startActivityForResult(tmpIntent, 12); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } else if (i == settingsLedRow) { + if (getParentActivity() == null) { + return; + } + + LayoutInflater li = (LayoutInflater) getParentActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); + view = li.inflate(R.layout.settings_color_dialog_layout, null, false); + final ColorPickerView colorPickerView = (ColorPickerView) view.findViewById(R.id.color_picker); + + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + if (preferences.contains("color_" + dialog_id)) { + colorPickerView.setOldCenterColor(preferences.getInt("color_" + dialog_id, 0xff00ff00)); + } else { + if ((int) dialog_id < 0) { + colorPickerView.setOldCenterColor(preferences.getInt("GroupLed", 0xff00ff00)); + } else { + colorPickerView.setOldCenterColor(preferences.getInt("MessagesLed", 0xff00ff00)); + } + } + + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("LedColor", R.string.LedColor)); + builder.setView(view); + builder.setPositiveButton(LocaleController.getString("Set", R.string.Set), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int which) { + final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + editor.putInt("color_" + dialog_id, colorPickerView.getColor()); + editor.commit(); + listView.invalidateViews(); + } + }); + builder.setNeutralButton(LocaleController.getString("LedDisabled", R.string.LedDisabled), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + editor.putInt("color_" + dialog_id, 0); + editor.commit(); + listView.invalidateViews(); + } + }); + builder.setNegativeButton(LocaleController.getString("Default", R.string.Default), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + editor.remove("color_" + dialog_id); + editor.commit(); + listView.invalidateViews(); + } + }); + showAlertDialog(builder); + } else if (i == settingsPriorityRow) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("NotificationsPriority", R.string.NotificationsPriority)); + builder.setItems(new CharSequence[]{ + LocaleController.getString("SettingsDefault", R.string.SettingsDefault), + LocaleController.getString("NotificationsPriorityDefault", R.string.NotificationsPriorityDefault), + LocaleController.getString("NotificationsPriorityHigh", R.string.NotificationsPriorityHigh), + LocaleController.getString("NotificationsPriorityMax", R.string.NotificationsPriorityMax) + }, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + if (which == 0) { + which = 3; + } else { + which--; + } + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + preferences.edit().putInt("priority_" + dialog_id, which).commit(); + if (listView != null) { + listView.invalidateViews(); + } + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } + } + }); + return fragmentView; } @@ -314,7 +308,7 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi Ringtone rng = RingtoneManager.getRingtone(ApplicationLoader.applicationContext, ringtone); if (rng != null) { if(ringtone.equals(Settings.System.DEFAULT_NOTIFICATION_URI)) { - name = LocaleController.getString("Default", R.string.Default); + name = LocaleController.getString("SoundDefault", R.string.SoundDefault); } else { name = rng.getTitle(getParentActivity()); } @@ -437,7 +431,7 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi } } } else if (i == settingsSoundRow) { - String value = preferences.getString("sound_" + dialog_id, LocaleController.getString("Default", R.string.Default)); + String value = preferences.getString("sound_" + dialog_id, LocaleController.getString("SoundDefault", R.string.SoundDefault)); if (value.equals("NoSound")) { value = LocaleController.getString("NoSound", R.string.NoSound); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/SessionsActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/SessionsActivity.java new file mode 100644 index 000000000..fb90c3100 --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/ui/SessionsActivity.java @@ -0,0 +1,475 @@ +/* + * This is the source code of Telegram for Android v. 2.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-2015. + */ + +package org.telegram.ui; + +import android.app.AlertDialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.os.Build; +import android.util.TypedValue; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AbsListView; +import android.widget.AdapterView; +import android.widget.FrameLayout; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ListView; +import android.widget.ProgressBar; +import android.widget.TextView; +import android.widget.Toast; + +import org.telegram.android.AndroidUtilities; +import org.telegram.android.LocaleController; +import org.telegram.android.MessagesController; +import org.telegram.android.NotificationCenter; +import org.telegram.messenger.ConnectionsManager; +import org.telegram.messenger.FileLog; +import org.telegram.messenger.R; +import org.telegram.messenger.RPCRequest; +import org.telegram.messenger.TLObject; +import org.telegram.messenger.TLRPC; +import org.telegram.messenger.UserConfig; +import org.telegram.ui.ActionBar.ActionBar; +import org.telegram.ui.ActionBar.BaseFragment; +import org.telegram.ui.Adapters.BaseFragmentAdapter; +import org.telegram.ui.Cells.HeaderCell; +import org.telegram.ui.Cells.SessionCell; +import org.telegram.ui.Cells.TextInfoPrivacyCell; +import org.telegram.ui.Cells.TextSettingsCell; + +import java.util.ArrayList; + +public class SessionsActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate { + + private ListAdapter listAdapter; + private ArrayList sessions = new ArrayList<>(); + private TLRPC.TL_authorization currentSession = null; + private boolean loading; + private LinearLayout emptyLayout; + + private int currentSessionSectionRow; + private int currentSessionRow; + private int terminateAllSessionsRow; + private int terminateAllSessionsDetailRow; + private int otherSessionsSectionRow; + private int otherSessionsStartRow; + private int otherSessionsEndRow; + private int otherSessionsTerminateDetail; + private int noOtherSessionsRow; + private int rowCount; + + @Override + public boolean onFragmentCreate() { + super.onFragmentCreate(); + updateRows(); + loadSessions(false); + NotificationCenter.getInstance().addObserver(this, NotificationCenter.newSessionReceived); + return true; + } + + @Override + public void onFragmentDestroy() { + super.onFragmentDestroy(); + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.newSessionReceived); + } + + @Override + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setAllowOverlayTitle(true); + actionBar.setTitle(LocaleController.getString("SessionsTitle", R.string.SessionsTitle)); + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); + } + } + }); + + listAdapter = new ListAdapter(context); + + fragmentView = new FrameLayout(context); + FrameLayout frameLayout = (FrameLayout) fragmentView; + frameLayout.setBackgroundColor(0xfff0f0f0); + + emptyLayout = new LinearLayout(context); + emptyLayout.setOrientation(LinearLayout.VERTICAL); + emptyLayout.setGravity(Gravity.CENTER); + emptyLayout.setBackgroundResource(R.drawable.greydivider_bottom); + emptyLayout.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AndroidUtilities.displaySize.y - AndroidUtilities.getCurrentActionBarHeight())); + + ImageView imageView = new ImageView(context); + imageView.setImageResource(R.drawable.devices); + emptyLayout.addView(imageView); + LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) imageView.getLayoutParams(); + layoutParams2.width = LinearLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.height = LinearLayout.LayoutParams.WRAP_CONTENT; + imageView.setLayoutParams(layoutParams2); + + TextView textView = new TextView(context); + textView.setTextColor(0xff8a8a8a); + textView.setGravity(Gravity.CENTER); + textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17); + textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); + textView.setText(LocaleController.getString("NoOtherSessions", R.string.NoOtherSessions)); + emptyLayout.addView(textView); + layoutParams2 = (LinearLayout.LayoutParams) textView.getLayoutParams(); + layoutParams2.topMargin = AndroidUtilities.dp(16); + layoutParams2.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.gravity = Gravity.CENTER; + textView.setLayoutParams(layoutParams2); + + textView = new TextView(context); + textView.setTextColor(0xff8a8a8a); + textView.setGravity(Gravity.CENTER); + textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17); + textView.setPadding(AndroidUtilities.dp(20), 0, AndroidUtilities.dp(20), 0); + textView.setText(LocaleController.getString("NoOtherSessionsInfo", R.string.NoOtherSessionsInfo)); + emptyLayout.addView(textView); + layoutParams2 = (LinearLayout.LayoutParams) textView.getLayoutParams(); + layoutParams2.topMargin = AndroidUtilities.dp(14); + layoutParams2.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams2.gravity = Gravity.CENTER; + textView.setLayoutParams(layoutParams2); + + FrameLayout progressView = new FrameLayout(context); + frameLayout.addView(progressView); + FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + progressView.setLayoutParams(layoutParams); + progressView.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + + ProgressBar progressBar = new ProgressBar(context); + progressView.addView(progressBar); + layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.gravity = Gravity.CENTER; + progressView.setLayoutParams(layoutParams); + + ListView listView = new ListView(context); + listView.setDivider(null); + listView.setDividerHeight(0); + listView.setVerticalScrollBarEnabled(false); + listView.setDrawSelectorOnTop(true); + listView.setEmptyView(progressView); + frameLayout.addView(listView); + layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.gravity = Gravity.TOP; + listView.setLayoutParams(layoutParams); + listView.setAdapter(listAdapter); + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, final int i, long l) { + if (i == terminateAllSessionsRow) { + if (getParentActivity() == null) { + return; + } + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setMessage(LocaleController.getString("AreYouSureSessions", R.string.AreYouSureSessions)); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + TLRPC.TL_auth_resetAuthorizations req = new TLRPC.TL_auth_resetAuthorizations(); + ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(final TLObject response, final TLRPC.TL_error error) { + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + if (getParentActivity() == null) { + return; + } + if (error == null && response instanceof TLRPC.TL_boolTrue) { + Toast toast = Toast.makeText(getParentActivity(), LocaleController.getString("TerminateAllSessions", R.string.TerminateAllSessions), Toast.LENGTH_SHORT); + toast.show(); + } else { + Toast toast = Toast.makeText(getParentActivity(), LocaleController.getString("UnknownError", R.string.UnknownError), Toast.LENGTH_SHORT); + toast.show(); + } + finishFragment(); + } + }); + UserConfig.registeredForPush = false; + UserConfig.registeredForInternalPush = false; + UserConfig.saveConfig(false); + MessagesController.getInstance().registerForPush(UserConfig.pushString); + ConnectionsManager.getInstance().initPushConnection(); + } + }); + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } else if (i >= otherSessionsStartRow && i < otherSessionsEndRow) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setMessage(LocaleController.getString("TerminateSessionQuestion", R.string.TerminateSessionQuestion)); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int option) { + final ProgressDialog progressDialog = new ProgressDialog(getParentActivity()); + progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading)); + progressDialog.setCanceledOnTouchOutside(false); + progressDialog.setCancelable(false); + progressDialog.show(); + + final TLRPC.TL_authorization authorization = sessions.get(i - otherSessionsStartRow); + TLRPC.TL_account_resetAuthorization req = new TLRPC.TL_account_resetAuthorization(); + req.hash = authorization.hash; + ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(final TLObject response, final TLRPC.TL_error error) { + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + try { + progressDialog.dismiss(); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + if (error == null) { + sessions.remove(authorization); + updateRows(); + if (listAdapter != null) { + listAdapter.notifyDataSetChanged(); + } + } + } + }); + } + }); + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } + } + }); + + return fragmentView; + } + + @Override + public void onResume() { + super.onResume(); + if (listAdapter != null) { + listAdapter.notifyDataSetChanged(); + } + } + + @Override + public void didReceivedNotification(int id, Object... args) { + if (id == NotificationCenter.newSessionReceived) { + loadSessions(true); + } + } + + private void loadSessions(boolean silent) { + if (loading) { + return; + } + if (!silent) { + loading = true; + } + TLRPC.TL_account_getAuthorizations req = new TLRPC.TL_account_getAuthorizations(); + long reqId = ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(final TLObject response, final TLRPC.TL_error error) { + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + loading = false; + if (error == null) { + sessions.clear(); + TLRPC.TL_account_authorizations res = (TLRPC.TL_account_authorizations) response; + for (TLRPC.TL_authorization authorization : res.authorizations) { + if ((authorization.flags & 1) != 0) { + currentSession = authorization; + } else { + sessions.add(authorization); + } + } + updateRows(); + } + if (listAdapter != null) { + listAdapter.notifyDataSetChanged(); + } + } + }); + } + }); + ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid); + } + + private void updateRows() { + rowCount = 0; + if (currentSession != null) { + currentSessionSectionRow = rowCount++; + currentSessionRow = rowCount++; + } else { + currentSessionRow = -1; + currentSessionSectionRow = -1; + } + if (sessions.isEmpty()) { + noOtherSessionsRow = -1; + terminateAllSessionsRow = -1; + terminateAllSessionsDetailRow = -1; + otherSessionsSectionRow = -1; + otherSessionsStartRow = -1; + otherSessionsEndRow = -1; + otherSessionsTerminateDetail = -1; + } else { + noOtherSessionsRow = -1; + terminateAllSessionsRow = rowCount++; + terminateAllSessionsDetailRow = rowCount++; + otherSessionsSectionRow = rowCount++; + otherSessionsStartRow = otherSessionsSectionRow + 1; + otherSessionsEndRow = otherSessionsStartRow + sessions.size(); + rowCount += sessions.size(); + otherSessionsTerminateDetail = rowCount++; + } + } + + private class ListAdapter extends BaseFragmentAdapter { + private Context mContext; + + public ListAdapter(Context context) { + mContext = context; + } + + @Override + public boolean areAllItemsEnabled() { + return false; + } + + @Override + public boolean isEnabled(int i) { + return i == terminateAllSessionsRow || i >= otherSessionsStartRow && i < otherSessionsEndRow; + } + + @Override + public int getCount() { + return loading ? 0 : rowCount; + } + + @Override + public Object getItem(int i) { + return null; + } + + @Override + public long getItemId(int i) { + return i; + } + + @Override + public boolean hasStableIds() { + return false; + } + + @Override + public View getView(int i, View view, ViewGroup viewGroup) { + int type = getItemViewType(i); + if (type == 0) { + if (view == null) { + view = new TextSettingsCell(mContext); + view.setBackgroundColor(0xffffffff); + } + TextSettingsCell textCell = (TextSettingsCell) view; + if (i == terminateAllSessionsRow) { + textCell.setTextColor(0xffdb5151); + textCell.setText(LocaleController.getString("TerminateAllSessions", R.string.TerminateAllSessions), false); + } + } else if (type == 1) { + if (view == null) { + view = new TextInfoPrivacyCell(mContext); + } + if (i == terminateAllSessionsDetailRow) { + ((TextInfoPrivacyCell) view).setText(LocaleController.getString("ClearOtherSessionsHelp", R.string.ClearOtherSessionsHelp)); + view.setBackgroundResource(R.drawable.greydivider); + } else if (i == otherSessionsTerminateDetail) { + ((TextInfoPrivacyCell) view).setText(LocaleController.getString("TerminateSessionInfo", R.string.TerminateSessionInfo)); + view.setBackgroundResource(R.drawable.greydivider_bottom); + } + } else if (type == 2) { + if (view == null) { + view = new HeaderCell(mContext); + view.setBackgroundColor(0xffffffff); + } + if (i == currentSessionSectionRow) { + ((HeaderCell) view).setText(LocaleController.getString("CurrentSession", R.string.CurrentSession)); + } else if (i == otherSessionsSectionRow) { + ((HeaderCell) view).setText(LocaleController.getString("OtherSessions", R.string.OtherSessions)); + } + } else if (type == 3) { + ViewGroup.LayoutParams layoutParams = emptyLayout.getLayoutParams(); + if (layoutParams != null) { + layoutParams.height = Math.max(AndroidUtilities.dp(220), AndroidUtilities.displaySize.y - AndroidUtilities.getCurrentActionBarHeight() - AndroidUtilities.dp(128) - (Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0)); + emptyLayout.setLayoutParams(layoutParams); + } + return emptyLayout; + } else if (type == 4) { + if (view == null) { + view = new SessionCell(mContext); + view.setBackgroundColor(0xffffffff); + } + if (i == currentSessionRow) { + ((SessionCell) view).setSession(currentSession, !sessions.isEmpty()); + } else { + ((SessionCell) view).setSession(sessions.get(i - otherSessionsStartRow), i != otherSessionsEndRow - 1); + } + } + return view; + } + + @Override + public int getItemViewType(int i) { + if (i == terminateAllSessionsRow) { + return 0; + } else if (i == terminateAllSessionsDetailRow || i == otherSessionsTerminateDetail) { + return 1; + } else if (i == currentSessionSectionRow || i == otherSessionsSectionRow) { + return 2; + } else if (i == noOtherSessionsRow) { + return 3; + } else if (i == currentSessionRow || i >= otherSessionsStartRow && i < otherSessionsEndRow) { + return 4; + } + return 0; + } + + @Override + public int getViewTypeCount() { + return 5; + } + + @Override + public boolean isEmpty() { + return loading; + } + } +} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/SettingsActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/SettingsActivity.java index e3a5eef4f..f6ac527a5 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/SettingsActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/SettingsActivity.java @@ -268,439 +268,430 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setBackgroundColor(AvatarDrawable.getProfileBackColorForId(5)); - actionBar.setItemsBackground(AvatarDrawable.getButtonColorForId(5)); - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setExtraHeight(AndroidUtilities.dp(88), false); - if (AndroidUtilities.isTablet()) { - actionBar.setOccupyStatusBar(false); + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackgroundColor(AvatarDrawable.getProfileBackColorForId(5)); + actionBar.setItemsBackground(AvatarDrawable.getButtonColorForId(5)); + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setExtraHeight(AndroidUtilities.dp(88), false); + if (AndroidUtilities.isTablet()) { + actionBar.setOccupyStatusBar(false); + } + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); + } else if (id == edit_name) { + presentFragment(new ChangeNameActivity()); + } else if (id == logout) { + if (getParentActivity() == null) { + return; + } + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setMessage(LocaleController.getString("AreYouSureLogout", R.string.AreYouSureLogout)); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + editor.clear().commit(); + MessagesController.getInstance().unregistedPush(); + MessagesController.getInstance().logOut(); + UserConfig.clearConfig(); + NotificationCenter.getInstance().postNotificationName(NotificationCenter.appDidLogout); + MessagesStorage.getInstance().cleanUp(false); + MessagesController.getInstance().cleanUp(); + ContactsController.getInstance().deleteAllAppAccounts(); + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } } - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } else if (id == edit_name) { - presentFragment(new ChangeNameActivity()); - } else if (id == logout) { - if (getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setMessage(LocaleController.getString("AreYouSureLogout", R.string.AreYouSureLogout)); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - editor.clear().commit(); - MessagesController.getInstance().unregistedPush(); - MessagesController.getInstance().logOut(); - UserConfig.clearConfig(); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.appDidLogout); - MessagesStorage.getInstance().cleanUp(false); - MessagesController.getInstance().cleanUp(); - ContactsController.getInstance().deleteAllAppAccounts(); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } + }); + ActionBarMenu menu = actionBar.createMenu(); + ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_other); + item.addSubItem(edit_name, LocaleController.getString("EditName", R.string.EditName), 0); + item.addSubItem(logout, LocaleController.getString("LogOut", R.string.LogOut), 0); + + listAdapter = new ListAdapter(context); + + fragmentView = new FrameLayout(context); + FrameLayout frameLayout = (FrameLayout) fragmentView; + + avatarImage = new BackupImageView(context); + avatarImage.setRoundRadius(AndroidUtilities.dp(30)); + actionBar.addView(avatarImage); + FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) avatarImage.getLayoutParams(); + layoutParams.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.BOTTOM; + layoutParams.width = AndroidUtilities.dp(60); + layoutParams.height = AndroidUtilities.dp(60); + layoutParams.leftMargin = LocaleController.isRTL ? 0 : AndroidUtilities.dp(17); + layoutParams.rightMargin = LocaleController.isRTL ? AndroidUtilities.dp(17) : 0; + layoutParams.bottomMargin = AndroidUtilities.dp(22); + avatarImage.setLayoutParams(layoutParams); + avatarImage.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); + if (user.photo != null && user.photo.photo_big != null) { + PhotoViewer.getInstance().setParentActivity(getParentActivity()); + PhotoViewer.getInstance().openPhoto(user.photo.photo_big, SettingsActivity.this); } - }); - ActionBarMenu menu = actionBar.createMenu(); - ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_other); - item.addSubItem(edit_name, LocaleController.getString("EditName", R.string.EditName), 0); - item.addSubItem(logout, LocaleController.getString("LogOut", R.string.LogOut), 0); - - listAdapter = new ListAdapter(getParentActivity()); - - fragmentView = new FrameLayout(getParentActivity()); - FrameLayout frameLayout = (FrameLayout) fragmentView; - - avatarImage = new BackupImageView(getParentActivity()); - avatarImage.imageReceiver.setRoundRadius(AndroidUtilities.dp(30)); - avatarImage.processDetach = false; - actionBar.addView(avatarImage); - FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) avatarImage.getLayoutParams(); - layoutParams.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.BOTTOM; - layoutParams.width = AndroidUtilities.dp(60); - layoutParams.height = AndroidUtilities.dp(60); - layoutParams.leftMargin = LocaleController.isRTL ? 0 : AndroidUtilities.dp(17); - layoutParams.rightMargin = LocaleController.isRTL ? AndroidUtilities.dp(17) : 0; - layoutParams.bottomMargin = AndroidUtilities.dp(22); - avatarImage.setLayoutParams(layoutParams); - avatarImage.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); - if (user.photo != null && user.photo.photo_big != null) { - PhotoViewer.getInstance().setParentActivity(getParentActivity()); - PhotoViewer.getInstance().openPhoto(user.photo.photo_big, SettingsActivity.this); - } - } - }); - - nameTextView = new TextView(getParentActivity()); - nameTextView.setTextColor(0xffffffff); - nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); - nameTextView.setLines(1); - nameTextView.setMaxLines(1); - nameTextView.setSingleLine(true); - nameTextView.setEllipsize(TextUtils.TruncateAt.END); - nameTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); - nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - actionBar.addView(nameTextView); - layoutParams = (FrameLayout.LayoutParams) nameTextView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.leftMargin = AndroidUtilities.dp(LocaleController.isRTL ? 16 : 97); - layoutParams.rightMargin = AndroidUtilities.dp(LocaleController.isRTL ? 97 : 16); - layoutParams.bottomMargin = AndroidUtilities.dp(51); - layoutParams.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.BOTTOM; - nameTextView.setLayoutParams(layoutParams); - - onlineTextView = new TextView(getParentActivity()); - onlineTextView.setTextColor(AvatarDrawable.getProfileTextColorForId(5)); - onlineTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - onlineTextView.setLines(1); - onlineTextView.setMaxLines(1); - onlineTextView.setSingleLine(true); - onlineTextView.setEllipsize(TextUtils.TruncateAt.END); - onlineTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); - actionBar.addView(onlineTextView); - layoutParams = (FrameLayout.LayoutParams) onlineTextView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.leftMargin = AndroidUtilities.dp(LocaleController.isRTL ? 16 : 97); - layoutParams.rightMargin = AndroidUtilities.dp(LocaleController.isRTL ? 97 : 16); - layoutParams.bottomMargin = AndroidUtilities.dp(30); - layoutParams.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.BOTTOM; - onlineTextView.setLayoutParams(layoutParams); - - listView = new ListView(getParentActivity()); - listView.setDivider(null); - listView.setDividerHeight(0); - listView.setVerticalScrollBarEnabled(false); - AndroidUtilities.setListViewEdgeEffectColor(listView, AvatarDrawable.getProfileBackColorForId(5)); - frameLayout.addView(listView); - layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; - layoutParams.gravity = Gravity.TOP; - listView.setLayoutParams(layoutParams); - listView.setAdapter(listAdapter); - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, final int i, long l) { - if (i == textSizeRow) { - if (getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("TextSize", R.string.TextSize)); - final NumberPicker numberPicker = new NumberPicker(getParentActivity()); - numberPicker.setMinValue(12); - numberPicker.setMaxValue(30); - numberPicker.setValue(MessagesController.getInstance().fontSize); - builder.setView(numberPicker); - builder.setNegativeButton(LocaleController.getString("Done", R.string.Done), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - editor.putInt("fons_size", numberPicker.getValue()); - MessagesController.getInstance().fontSize = numberPicker.getValue(); - editor.commit(); - if (listView != null) { - listView.invalidateViews(); - } - } - }); - showAlertDialog(builder); - } else if (i == enableAnimationsRow) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); - boolean animations = preferences.getBoolean("view_animations", true); - SharedPreferences.Editor editor = preferences.edit(); - editor.putBoolean("view_animations", !animations); - editor.commit(); - if (view instanceof TextCheckCell) { - ((TextCheckCell) view).setChecked(!animations); - } - } else if (i == notificationRow) { - presentFragment(new NotificationsSettingsActivity()); - } else if (i == backgroundRow) { - presentFragment(new WallpapersActivity()); - } else if (i == askQuestionRow) { - if (getParentActivity() == null) { - return; - } - final TextView message = new TextView(getParentActivity()); - message.setText(Html.fromHtml(LocaleController.getString("AskAQuestionInfo", R.string.AskAQuestionInfo))); - message.setTextSize(18); - message.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(5), AndroidUtilities.dp(8), AndroidUtilities.dp(6)); - message.setMovementMethod(new LinkMovementMethodMy()); - - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setView(message); - builder.setPositiveButton(LocaleController.getString("AskButton", R.string.AskButton), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - performAskAQuestion(); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } else if (i == sendLogsRow) { - sendLogs(); - } else if (i == clearLogsRow) { - FileLog.cleanupLogs(); - } else if (i == sendByEnterRow) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); - boolean send = preferences.getBoolean("send_by_enter", false); - SharedPreferences.Editor editor = preferences.edit(); - editor.putBoolean("send_by_enter", !send); - editor.commit(); - if (view instanceof TextCheckCell) { - ((TextCheckCell) view).setChecked(!send); - } - } else if (i == saveToGalleryRow) { - MediaController.getInstance().toggleSaveToGallery(); - if (view instanceof TextCheckCell) { - ((TextCheckCell) view).setChecked(MediaController.getInstance().canSaveToGallery()); - } - } else if (i == privacyRow) { - presentFragment(new PrivacySettingsActivity()); - } else if (i == languageRow) { - presentFragment(new LanguageSelectActivity()); - } else if (i == switchBackendButtonRow) { - if (getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure)); - builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - ConnectionsManager.getInstance().switchBackend(); - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } else if (i == telegramFaqRow) { - try { - Intent pickIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(LocaleController.getString("TelegramFaqUrl", R.string.TelegramFaqUrl))); - getParentActivity().startActivityForResult(pickIntent, 500); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } else if (i == contactsReimportRow) { - - } else if (i == contactsSortRow) { - if (getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("SortBy", R.string.SortBy)); - builder.setItems(new CharSequence[] { - LocaleController.getString("Default", R.string.Default), - LocaleController.getString("SortFirstName", R.string.SortFirstName), - LocaleController.getString("SortLastName", R.string.SortLastName) - }, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - editor.putInt("sortContactsBy", which); - editor.commit(); - if (listView != null) { - listView.invalidateViews(); - } - } - }); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - showAlertDialog(builder); - } else if (i == wifiDownloadRow || i == mobileDownloadRow || i == roamingDownloadRow) { - if (getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - - int mask = 0; - if (i == mobileDownloadRow) { - builder.setTitle(LocaleController.getString("WhenUsingMobileData", R.string.WhenUsingMobileData)); - mask = MediaController.getInstance().mobileDataDownloadMask; - } else if (i == wifiDownloadRow) { - builder.setTitle(LocaleController.getString("WhenConnectedOnWiFi", R.string.WhenConnectedOnWiFi)); - mask = MediaController.getInstance().wifiDownloadMask; - } else if (i == roamingDownloadRow) { - builder.setTitle(LocaleController.getString("WhenRoaming", R.string.WhenRoaming)); - mask = MediaController.getInstance().roamingDownloadMask; - } - builder.setMultiChoiceItems( - new CharSequence[]{LocaleController.getString("AttachPhoto", R.string.AttachPhoto), LocaleController.getString("AttachAudio", R.string.AttachAudio), LocaleController.getString("AttachVideo", R.string.AttachVideo), LocaleController.getString("AttachDocument", R.string.AttachDocument)}, - new boolean[]{(mask & MediaController.AUTODOWNLOAD_MASK_PHOTO) != 0, (mask & MediaController.AUTODOWNLOAD_MASK_AUDIO) != 0, (mask & MediaController.AUTODOWNLOAD_MASK_VIDEO) != 0, (mask & MediaController.AUTODOWNLOAD_MASK_DOCUMENT) != 0}, - new DialogInterface.OnMultiChoiceClickListener() { - @Override - public void onClick(DialogInterface dialog, int which, boolean isChecked) { - int mask = 0; - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - if (i == mobileDownloadRow) { - mask = MediaController.getInstance().mobileDataDownloadMask; - } else if (i == wifiDownloadRow) { - mask = MediaController.getInstance().wifiDownloadMask; - } else if (i == roamingDownloadRow) { - mask = MediaController.getInstance().roamingDownloadMask; - } - - int maskDiff = 0; - if (which == 0) { - maskDiff = MediaController.AUTODOWNLOAD_MASK_PHOTO; - } else if (which == 1) { - maskDiff = MediaController.AUTODOWNLOAD_MASK_AUDIO; - } else if (which == 2) { - maskDiff = MediaController.AUTODOWNLOAD_MASK_VIDEO; - } else if (which == 3) { - maskDiff = MediaController.AUTODOWNLOAD_MASK_DOCUMENT; - } - - if (isChecked) { - mask |= maskDiff; - } else { - mask &= ~maskDiff; - } - - if (i == mobileDownloadRow) { - editor.putInt("mobileDataDownloadMask", mask); - mask = MediaController.getInstance().mobileDataDownloadMask = mask; - } else if (i == wifiDownloadRow) { - editor.putInt("wifiDownloadMask", mask); - MediaController.getInstance().wifiDownloadMask = mask; - } else if (i == roamingDownloadRow) { - editor.putInt("roamingDownloadMask", mask); - MediaController.getInstance().roamingDownloadMask = mask; - } - editor.commit(); - if (listView != null) { - listView.invalidateViews(); - } - } - }); - builder.setNegativeButton(LocaleController.getString("OK", R.string.OK), null); - showAlertDialog(builder); - } else if (i == usernameRow) { - presentFragment(new ChangeUsernameActivity()); - } else if (i == numberRow) { - presentFragment(new ChangePhoneHelpActivity()); - } - } - }); - - frameLayout.addView(actionBar); - - writeButton = new ImageView(getParentActivity()); - writeButton.setBackgroundResource(R.drawable.floating_user_states); - writeButton.setImageResource(R.drawable.floating_camera); - writeButton.setScaleType(ImageView.ScaleType.CENTER); - if (Build.VERSION.SDK_INT >= 21) { - StateListAnimator animator = new StateListAnimator(); - animator.addState(new int[] {android.R.attr.state_pressed}, ObjectAnimator.ofFloat(writeButton, "translationZ", AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200)); - animator.addState(new int[] {}, ObjectAnimator.ofFloat(writeButton, "translationZ", AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200)); - writeButton.setStateListAnimator(animator); - writeButton.setOutlineProvider(new ViewOutlineProvider() { - @Override - public void getOutline(View view, Outline outline) { - outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56)); - } - }); } - frameLayout.addView(writeButton); - layoutParams = (FrameLayout.LayoutParams) writeButton.getLayoutParams(); - layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; - layoutParams.leftMargin = AndroidUtilities.dp(LocaleController.isRTL ? 16 : 0); - layoutParams.rightMargin = AndroidUtilities.dp(LocaleController.isRTL ? 0 : 16); - layoutParams.gravity = (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT); - writeButton.setLayoutParams(layoutParams); - writeButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { + }); + + nameTextView = new TextView(context); + nameTextView.setTextColor(0xffffffff); + nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); + nameTextView.setLines(1); + nameTextView.setMaxLines(1); + nameTextView.setSingleLine(true); + nameTextView.setEllipsize(TextUtils.TruncateAt.END); + nameTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); + nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); + actionBar.addView(nameTextView); + layoutParams = (FrameLayout.LayoutParams) nameTextView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.leftMargin = AndroidUtilities.dp(LocaleController.isRTL ? 16 : 97); + layoutParams.rightMargin = AndroidUtilities.dp(LocaleController.isRTL ? 97 : 16); + layoutParams.bottomMargin = AndroidUtilities.dp(51); + layoutParams.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.BOTTOM; + nameTextView.setLayoutParams(layoutParams); + + onlineTextView = new TextView(context); + onlineTextView.setTextColor(AvatarDrawable.getProfileTextColorForId(5)); + onlineTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + onlineTextView.setLines(1); + onlineTextView.setMaxLines(1); + onlineTextView.setSingleLine(true); + onlineTextView.setEllipsize(TextUtils.TruncateAt.END); + onlineTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); + actionBar.addView(onlineTextView); + layoutParams = (FrameLayout.LayoutParams) onlineTextView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.leftMargin = AndroidUtilities.dp(LocaleController.isRTL ? 16 : 97); + layoutParams.rightMargin = AndroidUtilities.dp(LocaleController.isRTL ? 97 : 16); + layoutParams.bottomMargin = AndroidUtilities.dp(30); + layoutParams.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.BOTTOM; + onlineTextView.setLayoutParams(layoutParams); + + listView = new ListView(context); + listView.setDivider(null); + listView.setDividerHeight(0); + listView.setVerticalScrollBarEnabled(false); + AndroidUtilities.setListViewEdgeEffectColor(listView, AvatarDrawable.getProfileBackColorForId(5)); + frameLayout.addView(listView); + layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.gravity = Gravity.TOP; + listView.setLayoutParams(layoutParams); + listView.setAdapter(listAdapter); + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, final int i, long l) { + if (i == textSizeRow) { + if (getParentActivity() == null) { + return; + } + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("TextSize", R.string.TextSize)); + final NumberPicker numberPicker = new NumberPicker(getParentActivity()); + numberPicker.setMinValue(12); + numberPicker.setMaxValue(30); + numberPicker.setValue(MessagesController.getInstance().fontSize); + builder.setView(numberPicker); + builder.setNegativeButton(LocaleController.getString("Done", R.string.Done), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + editor.putInt("fons_size", numberPicker.getValue()); + MessagesController.getInstance().fontSize = numberPicker.getValue(); + editor.commit(); + if (listView != null) { + listView.invalidateViews(); + } + } + }); + showAlertDialog(builder); + } else if (i == enableAnimationsRow) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); + boolean animations = preferences.getBoolean("view_animations", true); + SharedPreferences.Editor editor = preferences.edit(); + editor.putBoolean("view_animations", !animations); + editor.commit(); + if (view instanceof TextCheckCell) { + ((TextCheckCell) view).setChecked(!animations); + } + } else if (i == notificationRow) { + presentFragment(new NotificationsSettingsActivity()); + } else if (i == backgroundRow) { + presentFragment(new WallpapersActivity()); + } else if (i == askQuestionRow) { + if (getParentActivity() == null) { + return; + } + final TextView message = new TextView(getParentActivity()); + message.setText(Html.fromHtml(LocaleController.getString("AskAQuestionInfo", R.string.AskAQuestionInfo))); + message.setTextSize(18); + message.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(5), AndroidUtilities.dp(8), AndroidUtilities.dp(6)); + message.setMovementMethod(new LinkMovementMethodMy()); + + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setView(message); + builder.setPositiveButton(LocaleController.getString("AskButton", R.string.AskButton), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + performAskAQuestion(); + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } else if (i == sendLogsRow) { + sendLogs(); + } else if (i == clearLogsRow) { + FileLog.cleanupLogs(); + } else if (i == sendByEnterRow) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); + boolean send = preferences.getBoolean("send_by_enter", false); + SharedPreferences.Editor editor = preferences.edit(); + editor.putBoolean("send_by_enter", !send); + editor.commit(); + if (view instanceof TextCheckCell) { + ((TextCheckCell) view).setChecked(!send); + } + } else if (i == saveToGalleryRow) { + MediaController.getInstance().toggleSaveToGallery(); + if (view instanceof TextCheckCell) { + ((TextCheckCell) view).setChecked(MediaController.getInstance().canSaveToGallery()); + } + } else if (i == privacyRow) { + presentFragment(new PrivacySettingsActivity()); + } else if (i == languageRow) { + presentFragment(new LanguageSelectActivity()); + } else if (i == switchBackendButtonRow) { + if (getParentActivity() == null) { + return; + } + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure)); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + ConnectionsManager.getInstance().switchBackend(); + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } else if (i == telegramFaqRow) { + try { + Intent pickIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(LocaleController.getString("TelegramFaqUrl", R.string.TelegramFaqUrl))); + getParentActivity().startActivityForResult(pickIntent, 500); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } else if (i == contactsReimportRow) { + + } else if (i == contactsSortRow) { + if (getParentActivity() == null) { + return; + } + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("SortBy", R.string.SortBy)); + builder.setItems(new CharSequence[]{ + LocaleController.getString("Default", R.string.Default), + LocaleController.getString("SortFirstName", R.string.SortFirstName), + LocaleController.getString("SortLastName", R.string.SortLastName) + }, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + editor.putInt("sortContactsBy", which); + editor.commit(); + if (listView != null) { + listView.invalidateViews(); + } + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } else if (i == wifiDownloadRow || i == mobileDownloadRow || i == roamingDownloadRow) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - CharSequence[] items; + int mask = 0; + if (i == mobileDownloadRow) { + builder.setTitle(LocaleController.getString("WhenUsingMobileData", R.string.WhenUsingMobileData)); + mask = MediaController.getInstance().mobileDataDownloadMask; + } else if (i == wifiDownloadRow) { + builder.setTitle(LocaleController.getString("WhenConnectedOnWiFi", R.string.WhenConnectedOnWiFi)); + mask = MediaController.getInstance().wifiDownloadMask; + } else if (i == roamingDownloadRow) { + builder.setTitle(LocaleController.getString("WhenRoaming", R.string.WhenRoaming)); + mask = MediaController.getInstance().roamingDownloadMask; + } + builder.setMultiChoiceItems( + new CharSequence[]{LocaleController.getString("AttachPhoto", R.string.AttachPhoto), LocaleController.getString("AttachAudio", R.string.AttachAudio), LocaleController.getString("AttachVideo", R.string.AttachVideo), LocaleController.getString("AttachDocument", R.string.AttachDocument)}, + new boolean[]{(mask & MediaController.AUTODOWNLOAD_MASK_PHOTO) != 0, (mask & MediaController.AUTODOWNLOAD_MASK_AUDIO) != 0, (mask & MediaController.AUTODOWNLOAD_MASK_VIDEO) != 0, (mask & MediaController.AUTODOWNLOAD_MASK_DOCUMENT) != 0}, + new DialogInterface.OnMultiChoiceClickListener() { + @Override + public void onClick(DialogInterface dialog, int which, boolean isChecked) { + int mask = 0; + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + if (i == mobileDownloadRow) { + mask = MediaController.getInstance().mobileDataDownloadMask; + } else if (i == wifiDownloadRow) { + mask = MediaController.getInstance().wifiDownloadMask; + } else if (i == roamingDownloadRow) { + mask = MediaController.getInstance().roamingDownloadMask; + } - TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); - if (user == null) { - user = UserConfig.getCurrentUser(); - } - if (user == null) { - return; - } - boolean fullMenu = false; - if (user.photo != null && user.photo.photo_big != null && !(user.photo instanceof TLRPC.TL_userProfilePhotoEmpty)) { - items = new CharSequence[] {LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("DeletePhoto", R.string.DeletePhoto)}; - fullMenu = true; - } else { - items = new CharSequence[] {LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley)}; - } + int maskDiff = 0; + if (which == 0) { + maskDiff = MediaController.AUTODOWNLOAD_MASK_PHOTO; + } else if (which == 1) { + maskDiff = MediaController.AUTODOWNLOAD_MASK_AUDIO; + } else if (which == 2) { + maskDiff = MediaController.AUTODOWNLOAD_MASK_VIDEO; + } else if (which == 3) { + maskDiff = MediaController.AUTODOWNLOAD_MASK_DOCUMENT; + } - final boolean full = fullMenu; - builder.setItems(items, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - if (i == 0) { - avatarUpdater.openCamera(); - } else if (i == 1) { - avatarUpdater.openGallery(); - } else if (i == 2) { - MessagesController.getInstance().deleteUserPhoto(null); - } - } - }); + if (isChecked) { + mask |= maskDiff; + } else { + mask &= ~maskDiff; + } + + if (i == mobileDownloadRow) { + editor.putInt("mobileDataDownloadMask", mask); + mask = MediaController.getInstance().mobileDataDownloadMask = mask; + } else if (i == wifiDownloadRow) { + editor.putInt("wifiDownloadMask", mask); + MediaController.getInstance().wifiDownloadMask = mask; + } else if (i == roamingDownloadRow) { + editor.putInt("roamingDownloadMask", mask); + MediaController.getInstance().roamingDownloadMask = mask; + } + editor.commit(); + if (listView != null) { + listView.invalidateViews(); + } + } + }); + builder.setNegativeButton(LocaleController.getString("OK", R.string.OK), null); showAlertDialog(builder); + } else if (i == usernameRow) { + presentFragment(new ChangeUsernameActivity()); + } else if (i == numberRow) { + presentFragment(new ChangePhoneHelpActivity()); } - }); - - listView.setOnScrollListener(new AbsListView.OnScrollListener() { - @Override - public void onScrollStateChanged(AbsListView view, int scrollState) { - - } - - @Override - public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - if (totalItemCount == 0) { - return; - } - int height = 0; - View child = view.getChildAt(0); - if (child != null) { - if (firstVisibleItem == 0) { - height = AndroidUtilities.dp(88) + (child.getTop() < 0 ? child.getTop() : 0); - } - if (actionBar.getExtraHeight() != height) { - actionBar.setExtraHeight(height, true); - needLayout(); - } - } - } - }); - - updateUserData(); - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); } + }); + + frameLayout.addView(actionBar); + + writeButton = new ImageView(context); + writeButton.setBackgroundResource(R.drawable.floating_user_states); + writeButton.setImageResource(R.drawable.floating_camera); + writeButton.setScaleType(ImageView.ScaleType.CENTER); + if (Build.VERSION.SDK_INT >= 21) { + StateListAnimator animator = new StateListAnimator(); + animator.addState(new int[]{android.R.attr.state_pressed}, ObjectAnimator.ofFloat(writeButton, "translationZ", AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200)); + animator.addState(new int[]{}, ObjectAnimator.ofFloat(writeButton, "translationZ", AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200)); + writeButton.setStateListAnimator(animator); + writeButton.setOutlineProvider(new ViewOutlineProvider() { + @Override + public void getOutline(View view, Outline outline) { + outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56)); + } + }); } + frameLayout.addView(writeButton); + layoutParams = (FrameLayout.LayoutParams) writeButton.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.leftMargin = AndroidUtilities.dp(LocaleController.isRTL ? 16 : 0); + layoutParams.rightMargin = AndroidUtilities.dp(LocaleController.isRTL ? 0 : 16); + layoutParams.gravity = (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT); + writeButton.setLayoutParams(layoutParams); + writeButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (getParentActivity() == null) { + return; + } + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + + CharSequence[] items; + + TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); + if (user == null) { + user = UserConfig.getCurrentUser(); + } + if (user == null) { + return; + } + boolean fullMenu = false; + if (user.photo != null && user.photo.photo_big != null && !(user.photo instanceof TLRPC.TL_userProfilePhotoEmpty)) { + items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("DeletePhoto", R.string.DeletePhoto)}; + fullMenu = true; + } else { + items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley)}; + } + + final boolean full = fullMenu; + builder.setItems(items, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + if (i == 0) { + avatarUpdater.openCamera(); + } else if (i == 1) { + avatarUpdater.openGallery(); + } else if (i == 2) { + MessagesController.getInstance().deleteUserPhoto(null); + } + } + }); + showAlertDialog(builder); + } + }); + + listView.setOnScrollListener(new AbsListView.OnScrollListener() { + @Override + public void onScrollStateChanged(AbsListView view, int scrollState) { + + } + + @Override + public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + if (totalItemCount == 0) { + return; + } + int height = 0; + View child = view.getChildAt(0); + if (child != null) { + if (firstVisibleItem == 0) { + height = AndroidUtilities.dp(88) + (child.getTop() < 0 ? child.getTop() : 0); + } + if (actionBar.getExtraHeight() != height) { + actionBar.setExtraHeight(height, true); + needLayout(); + } + } + } + }); + return fragmentView; } @@ -729,11 +720,11 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter object.viewX = coords[0]; object.viewY = coords[1] - AndroidUtilities.statusBarHeight; object.parentView = avatarImage; - object.imageReceiver = avatarImage.imageReceiver; + object.imageReceiver = avatarImage.getImageReceiver(); object.user_id = UserConfig.getClientUserId(); object.thumb = object.imageReceiver.getBitmap(); object.size = -1; - object.radius = avatarImage.imageReceiver.getRoundRadius(); + object.radius = avatarImage.getImageReceiver().getRoundRadius(); return object; } } @@ -750,7 +741,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter @Override public void willHidePhotoViewer() { - avatarImage.imageReceiver.setVisible(true, true); + avatarImage.getImageReceiver().setVisible(true, true); } @Override @@ -888,6 +879,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter if (listAdapter != null) { listAdapter.notifyDataSetChanged(); } + updateUserData(); fixLayout(); } @@ -927,7 +919,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter writeButton.clearAnimation(); } - avatarImage.imageReceiver.setRoundRadius(AndroidUtilities.dp(avatarSize / 2)); + avatarImage.setRoundRadius(AndroidUtilities.dp(avatarSize / 2)); layoutParams = (FrameLayout.LayoutParams) avatarImage.getLayoutParams(); layoutParams.width = AndroidUtilities.dp(avatarSize); layoutParams.height = AndroidUtilities.dp(avatarSize); @@ -982,12 +974,12 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter avatarDrawable.setColor(0xff5c98cd); if (avatarImage != null) { avatarImage.setImage(photo, "50_50", avatarDrawable); - avatarImage.imageReceiver.setVisible(!PhotoViewer.getInstance().isShowingImage(photoBig), false); + avatarImage.getImageReceiver().setVisible(!PhotoViewer.getInstance().isShowingImage(photoBig), false); nameTextView.setText(ContactsController.formatName(user.first_name, user.last_name)); onlineTextView.setText(LocaleController.getString("Online", R.string.Online)); - avatarImage.imageReceiver.setVisible(!PhotoViewer.getInstance().isShowingImage(photoBig), false); + avatarImage.getImageReceiver().setVisible(!PhotoViewer.getInstance().isShowingImage(photoBig), false); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/TwoStepVerificationActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/TwoStepVerificationActivity.java new file mode 100644 index 000000000..74f7e9de3 --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/ui/TwoStepVerificationActivity.java @@ -0,0 +1,1085 @@ +/* + * This is the source code of Telegram for Android v. 2.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-2015. + */ + +package org.telegram.ui; + +import android.app.AlertDialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.graphics.Typeface; +import android.os.Vibrator; +import android.text.InputType; +import android.text.method.PasswordTransformationMethod; +import android.util.TypedValue; +import android.view.ActionMode; +import android.view.ContextMenu; +import android.view.Gravity; +import android.view.KeyEvent; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewGroup; +import android.view.WindowManager; +import android.view.inputmethod.EditorInfo; +import android.widget.AdapterView; +import android.widget.EditText; +import android.widget.FrameLayout; +import android.widget.LinearLayout; +import android.widget.ListView; +import android.widget.ProgressBar; +import android.widget.ScrollView; +import android.widget.TextView; +import android.widget.Toast; + +import org.telegram.android.AndroidUtilities; +import org.telegram.android.LocaleController; +import org.telegram.android.NotificationCenter; +import org.telegram.messenger.ConnectionsManager; +import org.telegram.messenger.FileLog; +import org.telegram.messenger.R; +import org.telegram.messenger.RPCRequest; +import org.telegram.messenger.TLObject; +import org.telegram.messenger.TLRPC; +import org.telegram.messenger.Utilities; +import org.telegram.ui.ActionBar.ActionBar; +import org.telegram.ui.ActionBar.ActionBarMenu; +import org.telegram.ui.ActionBar.ActionBarMenuItem; +import org.telegram.ui.ActionBar.BaseFragment; +import org.telegram.ui.Adapters.BaseFragmentAdapter; +import org.telegram.ui.Cells.TextInfoPrivacyCell; +import org.telegram.ui.Cells.TextSettingsCell; + +public class TwoStepVerificationActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate { + + private ListAdapter listAdapter; + private ListView listView; + private TextView titleTextView; + private TextView bottomTextView; + private TextView bottomButton; + private EditText passwordEditText; + private ProgressDialog progressDialog; + private FrameLayout progressView; + private ActionBarMenuItem doneItem; + private ScrollView scrollView; + + private int type; + private int passwordSetState; + private String firstPassword; + private String hint; + private String email; + private boolean emailOnly; + private boolean loading; + private boolean destroyed; + private boolean waitingForEmail; + private TLRPC.account_Password currentPassword; + private boolean passwordEntered = true; + private byte[] currentPasswordHash = new byte[0]; + private Runnable shortPollRunnable; + + private int setPasswordRow; + private int setPasswordDetailRow; + private int changePasswordRow; + private int shadowRow; + private int turnPasswordOffRow; + private int setRecoveryEmailRow; + private int changeRecoveryEmailRow; + private int abortPasswordRow; + private int passwordSetupDetailRow; + private int passwordEnabledDetailRow; + private int passwordEmailVerifyDetailRow; + private int rowCount; + + private final static int done_button = 1; + + public TwoStepVerificationActivity(int type) { + super(); + this.type = type; + if (type == 0) { + loadPasswordInfo(false); + } + } + + @Override + public boolean onFragmentCreate() { + super.onFragmentCreate(); + updateRows(); + if (type == 0) { + NotificationCenter.getInstance().addObserver(this, NotificationCenter.didSetTwoStepPassword); + } + return true; + } + + @Override + public void onFragmentDestroy() { + super.onFragmentDestroy(); + if (type == 0) { + NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didSetTwoStepPassword); + if (shortPollRunnable != null) { + AndroidUtilities.cancelRunOnUIThread(shortPollRunnable); + shortPollRunnable = null; + } + destroyed = true; + } + if (progressDialog != null) { + try { + progressDialog.dismiss(); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + progressDialog = null; + } + if (!AndroidUtilities.isTablet() && getParentActivity() != null) { + getParentActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); + } + } + + @Override + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setAllowOverlayTitle(false); + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); + } else if (id == done_button) { + processDone(); + } + } + }); + + fragmentView = new FrameLayout(context); + FrameLayout frameLayout = (FrameLayout) fragmentView; + frameLayout.setBackgroundColor(0xfff0f0f0); + + ActionBarMenu menu = actionBar.createMenu(); + doneItem = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); + + scrollView = new ScrollView(context); + scrollView.setFillViewport(true); + frameLayout.addView(scrollView); + FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) scrollView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + scrollView.setLayoutParams(layoutParams); + + LinearLayout linearLayout = new LinearLayout(context); + linearLayout.setOrientation(LinearLayout.VERTICAL); + scrollView.addView(linearLayout); + ScrollView.LayoutParams layoutParams2 = (ScrollView.LayoutParams) linearLayout.getLayoutParams(); + layoutParams2.width = ScrollView.LayoutParams.MATCH_PARENT; + layoutParams2.height = ScrollView.LayoutParams.WRAP_CONTENT; + linearLayout.setLayoutParams(layoutParams2); + + titleTextView = new TextView(context); + titleTextView.setTextColor(0xff757575); + titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); + titleTextView.setGravity(Gravity.CENTER_HORIZONTAL); + linearLayout.addView(titleTextView); + LinearLayout.LayoutParams layoutParams3 = (LinearLayout.LayoutParams) titleTextView.getLayoutParams(); + layoutParams3.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams3.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams3.gravity = Gravity.CENTER_HORIZONTAL; + layoutParams3.topMargin = AndroidUtilities.dp(38); + titleTextView.setLayoutParams(layoutParams3); + + passwordEditText = new EditText(context); + passwordEditText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); + passwordEditText.setTextColor(0xff000000); + passwordEditText.setMaxLines(1); + passwordEditText.setLines(1); + passwordEditText.setGravity(Gravity.CENTER_HORIZONTAL); + passwordEditText.setSingleLine(true); + passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); + passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance()); + passwordEditText.setTypeface(Typeface.DEFAULT); + AndroidUtilities.clearCursorDrawable(passwordEditText); + linearLayout.addView(passwordEditText); + layoutParams3 = (LinearLayout.LayoutParams) passwordEditText.getLayoutParams(); + layoutParams3.topMargin = AndroidUtilities.dp(32); + layoutParams3.height = AndroidUtilities.dp(36); + layoutParams3.leftMargin = AndroidUtilities.dp(40); + layoutParams3.rightMargin = AndroidUtilities.dp(40); + layoutParams3.gravity = Gravity.TOP | Gravity.LEFT; + layoutParams3.width = LinearLayout.LayoutParams.MATCH_PARENT; + passwordEditText.setLayoutParams(layoutParams3); + passwordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { + @Override + public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { + if (i == EditorInfo.IME_ACTION_NEXT || i == EditorInfo.IME_ACTION_DONE) { + processDone(); + return true; + } + return false; + } + }); + if (android.os.Build.VERSION.SDK_INT < 11) { + passwordEditText.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() { + public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { + menu.clear(); + } + }); + } else { + passwordEditText.setCustomSelectionActionModeCallback(new ActionMode.Callback() { + public boolean onPrepareActionMode(ActionMode mode, Menu menu) { + return false; + } + + public void onDestroyActionMode(ActionMode mode) { + } + + public boolean onCreateActionMode(ActionMode mode, Menu menu) { + return false; + } + + public boolean onActionItemClicked(ActionMode mode, MenuItem item) { + return false; + } + }); + } + + bottomTextView = new TextView(context); + bottomTextView.setTextColor(0xff757575); + bottomTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + bottomTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); + bottomTextView.setText(LocaleController.getString("YourEmailInfo", R.string.YourEmailInfo)); + linearLayout.addView(bottomTextView); + layoutParams3 = (LinearLayout.LayoutParams) bottomTextView.getLayoutParams(); + layoutParams3.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams3.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams3.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP; + layoutParams3.topMargin = AndroidUtilities.dp(30); + layoutParams3.leftMargin = AndroidUtilities.dp(40); + layoutParams3.rightMargin = AndroidUtilities.dp(40); + bottomTextView.setLayoutParams(layoutParams3); + + LinearLayout linearLayout2 = new LinearLayout(context); + linearLayout2.setGravity(Gravity.BOTTOM | Gravity.CENTER_VERTICAL); + linearLayout.addView(linearLayout2); + layoutParams3 = (LinearLayout.LayoutParams) linearLayout2.getLayoutParams(); + layoutParams3.width = LinearLayout.LayoutParams.MATCH_PARENT; + layoutParams3.height = LinearLayout.LayoutParams.MATCH_PARENT; + linearLayout2.setLayoutParams(layoutParams3); + + bottomButton = new TextView(context); + bottomButton.setTextColor(0xff4d83b3); + bottomButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + bottomButton.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.BOTTOM); + bottomButton.setText(LocaleController.getString("YourEmailSkip", R.string.YourEmailSkip)); + bottomButton.setPadding(0, AndroidUtilities.dp(10), 0, 0); + linearLayout2.addView(bottomButton); + layoutParams3 = (LinearLayout.LayoutParams) bottomButton.getLayoutParams(); + layoutParams3.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams3.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams3.gravity = (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.BOTTOM; + layoutParams3.bottomMargin = AndroidUtilities.dp(14); + layoutParams3.leftMargin = AndroidUtilities.dp(40); + layoutParams3.rightMargin = AndroidUtilities.dp(40); + bottomButton.setLayoutParams(layoutParams3); + bottomButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (type == 0) { + if (currentPassword.has_recovery) { + needShowProgress(); + TLRPC.TL_auth_requestPasswordRecovery req = new TLRPC.TL_auth_requestPasswordRecovery(); + ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(final TLObject response, final TLRPC.TL_error error) { + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + needHideProgress(); + if (error == null) { + final TLRPC.TL_auth_passwordRecovery res = (TLRPC.TL_auth_passwordRecovery) response; + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setMessage(LocaleController.formatString("RestoreEmailSent", R.string.RestoreEmailSent, res.email_pattern)); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + TwoStepVerificationActivity fragment = new TwoStepVerificationActivity(1); + fragment.currentPassword = currentPassword; + fragment.currentPassword.email_unconfirmed_pattern = res.email_pattern; + fragment.passwordSetState = 4; + presentFragment(fragment); + } + }); + AlertDialog dialog = showAlertDialog(builder); + if (dialog != null) { + dialog.setCanceledOnTouchOutside(false); + dialog.setCancelable(false); + } + } else { + if (error.text.startsWith("FLOOD_WAIT")) { + int time = Utilities.parseInt(error.text); + String timeString; + if (time < 60) { + timeString = LocaleController.formatPluralString("Seconds", time); + } else { + timeString = LocaleController.formatPluralString("Minutes", time / 60); + } + showAlertWithText(LocaleController.getString("AppName", R.string.AppName), LocaleController.formatString("FloodWaitTime", R.string.FloodWaitTime, timeString)); + } else { + showAlertWithText(LocaleController.getString("AppName", R.string.AppName), error.text); + } + } + } + }); + } + }, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassWithoutLogin); + } else { + showAlertWithText(LocaleController.getString("RestorePasswordNoEmailTitle", R.string.RestorePasswordNoEmailTitle), LocaleController.getString("RestorePasswordNoEmailText", R.string.RestorePasswordNoEmailText)); + } + } else { + if (passwordSetState == 4) { + showAlertWithText(LocaleController.getString("RestorePasswordNoEmailTitle", R.string.RestorePasswordNoEmailTitle), LocaleController.getString("RestoreEmailTroubleText", R.string.RestoreEmailTroubleText)); + } else { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setMessage(LocaleController.getString("YourEmailSkipWarningText", R.string.YourEmailSkipWarningText)); + builder.setTitle(LocaleController.getString("YourEmailSkipWarning", R.string.YourEmailSkipWarning)); + builder.setPositiveButton(LocaleController.getString("YourEmailSkip", R.string.YourEmailSkip), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + email = ""; + setNewPassword(false); + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } + } + } + }); + + if (type == 0) { + progressView = new FrameLayout(context); + frameLayout.addView(progressView); + layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + progressView.setLayoutParams(layoutParams); + progressView.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + return true; + } + }); + + ProgressBar progressBar = new ProgressBar(context); + progressView.addView(progressBar); + layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.height = FrameLayout.LayoutParams.WRAP_CONTENT; + layoutParams.gravity = Gravity.CENTER; + progressView.setLayoutParams(layoutParams); + + listView = new ListView(context); + listView.setDivider(null); + listView.setEmptyView(progressView); + listView.setDividerHeight(0); + listView.setVerticalScrollBarEnabled(false); + listView.setDrawSelectorOnTop(true); + frameLayout.addView(listView); + layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); + layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; + layoutParams.gravity = Gravity.TOP; + listView.setLayoutParams(layoutParams); + listView.setAdapter(listAdapter = new ListAdapter(context)); + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, final int i, long l) { + if (i == setPasswordRow || i == changePasswordRow) { + TwoStepVerificationActivity fragment = new TwoStepVerificationActivity(1); + fragment.currentPasswordHash = currentPasswordHash; + fragment.currentPassword = currentPassword; + presentFragment(fragment); + } else if (i == setRecoveryEmailRow || i == changeRecoveryEmailRow) { + TwoStepVerificationActivity fragment = new TwoStepVerificationActivity(1); + fragment.currentPasswordHash = currentPasswordHash; + fragment.currentPassword = currentPassword; + fragment.emailOnly = true; + fragment.passwordSetState = 3; + presentFragment(fragment); + } else if (i == turnPasswordOffRow || i == abortPasswordRow) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setMessage(LocaleController.getString("TurnPasswordOffQuestion", R.string.TurnPasswordOffQuestion)); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + setNewPassword(true); + } + }); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + showAlertDialog(builder); + } + } + }); + + updateRows(); + + actionBar.setTitle(LocaleController.getString("TwoStepVerification", R.string.TwoStepVerification)); + titleTextView.setText(LocaleController.getString("PleaseEnterCurrentPassword", R.string.PleaseEnterCurrentPassword)); + } else if (type == 1) { + setPasswordSetState(passwordSetState); + } + + return fragmentView; + } + + @Override + public void didReceivedNotification(int id, Object... args) { + if (id == NotificationCenter.didSetTwoStepPassword) { + if (args != null && args.length > 0) { + currentPasswordHash = (byte[]) args[0]; + } + loadPasswordInfo(false); + updateRows(); + } + } + + @Override + public void onResume() { + super.onResume(); + if (type == 1) { + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + if (passwordEditText != null) { + passwordEditText.requestFocus(); + AndroidUtilities.showKeyboard(passwordEditText); + } + } + }, 200); + } + if (!AndroidUtilities.isTablet()) { + getParentActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); + } + } + + @Override + public void onOpenAnimationEnd() { + super.onOpenAnimationEnd(); + if (type == 1) { + AndroidUtilities.showKeyboard(passwordEditText); + } + } + + private void loadPasswordInfo(final boolean silent) { + if (!silent) { + loading = true; + } + TLRPC.TL_account_getPassword req = new TLRPC.TL_account_getPassword(); + ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(final TLObject response, final TLRPC.TL_error error) { + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + loading = false; + if (error == null) { + if (!silent) { + passwordEntered = currentPassword != null || currentPassword == null && response instanceof TLRPC.TL_account_noPassword; + } + currentPassword = (TLRPC.account_Password) response; + waitingForEmail = currentPassword.email_unconfirmed_pattern.length() > 0; + byte[] salt = new byte[currentPassword.new_salt.length + 8]; + Utilities.random.nextBytes(salt); + System.arraycopy(currentPassword.new_salt, 0, salt, 0, currentPassword.new_salt.length); + currentPassword.new_salt = salt; + } + if (type == 0 && !destroyed && shortPollRunnable == null) { + shortPollRunnable = new Runnable() { + @Override + public void run() { + if (shortPollRunnable == null) { + return; + } + loadPasswordInfo(true); + shortPollRunnable = null; + } + }; + AndroidUtilities.runOnUIThread(shortPollRunnable, 5000); + } + updateRows(); + } + }); + } + }, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassWithoutLogin); + } + + private void setPasswordSetState(int state) { + if (passwordEditText == null) { + return; + } + passwordSetState = state; + if (passwordSetState == 0) { + actionBar.setTitle(LocaleController.getString("YourPassword", R.string.YourPassword)); + if (currentPassword instanceof TLRPC.TL_account_noPassword) { + titleTextView.setText(LocaleController.getString("PleaseEnterFirstPassword", R.string.PleaseEnterFirstPassword)); + } else { + titleTextView.setText(LocaleController.getString("PleaseEnterPassword", R.string.PleaseEnterPassword)); + } + passwordEditText.setImeOptions(EditorInfo.IME_ACTION_NEXT); + passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance()); + bottomTextView.setVisibility(View.INVISIBLE); + bottomButton.setVisibility(View.INVISIBLE); + } else if (passwordSetState == 1) { + actionBar.setTitle(LocaleController.getString("YourPassword", R.string.YourPassword)); + titleTextView.setText(LocaleController.getString("PleaseReEnterPassword", R.string.PleaseReEnterPassword)); + passwordEditText.setImeOptions(EditorInfo.IME_ACTION_NEXT); + passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance()); + bottomTextView.setVisibility(View.INVISIBLE); + bottomButton.setVisibility(View.INVISIBLE); + } else if (passwordSetState == 2) { + actionBar.setTitle(LocaleController.getString("PasswordHint", R.string.PasswordHint)); + titleTextView.setText(LocaleController.getString("PasswordHintText", R.string.PasswordHintText)); + passwordEditText.setImeOptions(EditorInfo.IME_ACTION_NEXT); + passwordEditText.setTransformationMethod(null); + bottomTextView.setVisibility(View.INVISIBLE); + bottomButton.setVisibility(View.INVISIBLE); + } else if (passwordSetState == 3) { + actionBar.setTitle(LocaleController.getString("RecoveryEmail", R.string.RecoveryEmail)); + titleTextView.setText(LocaleController.getString("YourEmail", R.string.YourEmail)); + passwordEditText.setImeOptions(EditorInfo.IME_ACTION_DONE); + passwordEditText.setTransformationMethod(null); + passwordEditText.setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS); + bottomTextView.setVisibility(View.VISIBLE); + bottomButton.setVisibility(emailOnly ? View.INVISIBLE : View.VISIBLE); + } else if (passwordSetState == 4) { + actionBar.setTitle(LocaleController.getString("PasswordRecovery", R.string.PasswordRecovery)); + titleTextView.setText(LocaleController.getString("PasswordCode", R.string.PasswordCode)); + bottomTextView.setText(LocaleController.getString("RestoreEmailSentInfo", R.string.RestoreEmailSentInfo)); + bottomButton.setText(LocaleController.formatString("RestoreEmailTrouble", R.string.RestoreEmailTrouble, currentPassword.email_unconfirmed_pattern)); + passwordEditText.setImeOptions(EditorInfo.IME_ACTION_DONE); + passwordEditText.setTransformationMethod(null); + passwordEditText.setInputType(InputType.TYPE_CLASS_PHONE); + bottomTextView.setVisibility(View.VISIBLE); + bottomButton.setVisibility(View.VISIBLE); + } + passwordEditText.setText(""); + } + + private void updateRows() { + rowCount = 0; + setPasswordRow = -1; + setPasswordDetailRow = -1; + changePasswordRow = -1; + turnPasswordOffRow = -1; + setRecoveryEmailRow = -1; + changeRecoveryEmailRow = -1; + abortPasswordRow = -1; + passwordSetupDetailRow = -1; + passwordEnabledDetailRow = -1; + passwordEmailVerifyDetailRow = -1; + shadowRow = -1; + if (!loading && currentPassword != null) { + if (currentPassword instanceof TLRPC.TL_account_noPassword) { + if (waitingForEmail) { + passwordSetupDetailRow = rowCount++; + abortPasswordRow = rowCount++; + shadowRow = rowCount++; + } else { + setPasswordRow = rowCount++; + setPasswordDetailRow = rowCount++; + } + } else if (currentPassword instanceof TLRPC.TL_account_password) { + changePasswordRow = rowCount++; + turnPasswordOffRow = rowCount++; + if (currentPassword.has_recovery) { + changeRecoveryEmailRow = rowCount++; + } else { + setRecoveryEmailRow = rowCount++; + } + if (waitingForEmail) { + passwordEmailVerifyDetailRow = rowCount++; + } else { + passwordEnabledDetailRow = rowCount++; + } + } + } + + if (listAdapter != null) { + listAdapter.notifyDataSetChanged(); + } + if (passwordEntered) { + if (listView != null) { + listView.setVisibility(View.VISIBLE); + scrollView.setVisibility(View.INVISIBLE); + progressView.setVisibility(View.VISIBLE); + listView.setEmptyView(progressView); + } + if (passwordEditText != null) { + doneItem.setVisibility(View.GONE); + passwordEditText.setVisibility(View.INVISIBLE); + titleTextView.setVisibility(View.INVISIBLE); + bottomTextView.setVisibility(View.INVISIBLE); + bottomButton.setVisibility(View.INVISIBLE); + } + } else { + if (listView != null) { + listView.setEmptyView(null); + listView.setVisibility(View.INVISIBLE); + scrollView.setVisibility(View.VISIBLE); + progressView.setVisibility(View.INVISIBLE); + } + if (passwordEditText != null) { + doneItem.setVisibility(View.VISIBLE); + passwordEditText.setVisibility(View.VISIBLE); + titleTextView.setVisibility(View.VISIBLE); + bottomButton.setVisibility(View.VISIBLE); + bottomTextView.setVisibility(View.INVISIBLE); + bottomButton.setText(LocaleController.getString("ForgotPassword", R.string.ForgotPassword)); + if (currentPassword.hint != null && currentPassword.hint.length() > 0) { + passwordEditText.setHint(currentPassword.hint); + } else { + passwordEditText.setHint(""); + } + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + if (passwordEditText != null) { + passwordEditText.requestFocus(); + AndroidUtilities.showKeyboard(passwordEditText); + } + } + }, 200); + } + } + } + + private void needShowProgress() { + if (getParentActivity() == null || getParentActivity().isFinishing() || progressDialog != null) { + return; + } + progressDialog = new ProgressDialog(getParentActivity()); + progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading)); + progressDialog.setCanceledOnTouchOutside(false); + progressDialog.setCancelable(false); + progressDialog.show(); + } + + private void needHideProgress() { + if (progressDialog == null) { + return; + } + try { + progressDialog.dismiss(); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + progressDialog = null; + } + + private boolean isValidEmail(String text) { + if (text == null || text.length() < 3) { + return false; + } + int dot = text.lastIndexOf("."); + int dog = text.lastIndexOf("@"); + return !(dot < 0 || dog < 0 || dot < dog); + } + + private void showAlertWithText(String title, String text) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); + builder.setTitle(title); + builder.setMessage(text); + showAlertDialog(builder); + } + + private void setNewPassword(final boolean clear) { + final TLRPC.TL_account_updatePasswordSettings req = new TLRPC.TL_account_updatePasswordSettings(); + req.current_password_hash = currentPasswordHash; + req.new_settings = new TLRPC.TL_account_passwordInputSettings(); + if (clear) { + if (waitingForEmail && currentPassword instanceof TLRPC.TL_account_noPassword) { + req.new_settings.flags = 2; + req.new_settings.email = ""; + } else { + req.new_settings.flags = 3; + req.new_settings.hint = ""; + req.new_settings.new_password_hash = new byte[0]; + req.new_settings.new_salt = new byte[0]; + req.new_settings.email = ""; + } + } else { + if (firstPassword != null && firstPassword.length() > 0) { + byte[] newPasswordBytes = null; + try { + newPasswordBytes = firstPassword.getBytes("UTF-8"); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + + byte[] new_salt = currentPassword.new_salt; + byte[] hash = new byte[new_salt.length * 2 + newPasswordBytes.length]; + System.arraycopy(new_salt, 0, hash, 0, new_salt.length); + System.arraycopy(newPasswordBytes, 0, hash, new_salt.length, newPasswordBytes.length); + System.arraycopy(new_salt, 0, hash, hash.length - new_salt.length, new_salt.length); + req.new_settings.flags |= 1; + req.new_settings.hint = hint; + req.new_settings.new_password_hash = Utilities.computeSHA256(hash, 0, hash.length); + req.new_settings.new_salt = new_salt; + } + if (email.length() > 0) { + req.new_settings.flags |= 2; + req.new_settings.email = email; + } + } + needShowProgress(); + ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(final TLObject response, final TLRPC.TL_error error) { + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + needHideProgress(); + if (error == null && response instanceof TLRPC.TL_boolTrue) { + if (clear) { + currentPassword = null; + currentPasswordHash = new byte[0]; + loadPasswordInfo(false); + updateRows(); + } else { + if (getParentActivity() == null) { + return; + } + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + NotificationCenter.getInstance().postNotificationName(NotificationCenter.didSetTwoStepPassword, (Object) req.new_settings.new_password_hash); + finishFragment(); + } + }); + builder.setMessage(LocaleController.getString("YourPasswordSuccessText", R.string.YourPasswordSuccessText)); + builder.setTitle(LocaleController.getString("YourPasswordSuccess", R.string.YourPasswordSuccess)); + AlertDialog dialog = showAlertDialog(builder); + if (dialog != null) { + dialog.setCanceledOnTouchOutside(false); + dialog.setCancelable(false); + } + } + } else { + if (error.text.equals("EMAIL_UNCONFIRMED")) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + NotificationCenter.getInstance().postNotificationName(NotificationCenter.didSetTwoStepPassword, (Object) req.new_settings.new_password_hash); + finishFragment(); + } + }); + builder.setMessage(LocaleController.getString("YourEmailAlmostThereText", R.string.YourEmailAlmostThereText)); + builder.setTitle(LocaleController.getString("YourEmailAlmostThere", R.string.YourEmailAlmostThere)); + AlertDialog dialog = showAlertDialog(builder); + if (dialog != null) { + dialog.setCanceledOnTouchOutside(false); + dialog.setCancelable(false); + } + } else { + if (error.text.equals("EMAIL_INVALID")) { + showAlertWithText(LocaleController.getString("AppName", R.string.AppName), LocaleController.getString("PasswordEmailInvalid", R.string.PasswordEmailInvalid)); + } else if (error.text.startsWith("FLOOD_WAIT")) { + int time = Utilities.parseInt(error.text); + String timeString; + if (time < 60) { + timeString = LocaleController.formatPluralString("Seconds", time); + } else { + timeString = LocaleController.formatPluralString("Minutes", time / 60); + } + showAlertWithText(LocaleController.getString("AppName", R.string.AppName), LocaleController.formatString("FloodWaitTime", R.string.FloodWaitTime, timeString)); + } else { + showAlertWithText(LocaleController.getString("AppName", R.string.AppName), error.text); + } + } + } + } + }); + } + }, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassWithoutLogin); + } + + private void processDone() { + if (type == 0) { + if (!passwordEntered) { + String oldPassword = passwordEditText.getText().toString(); + if (oldPassword.length() == 0) { + onPasscodeError(false); + return; + } + byte[] oldPasswordBytes = null; + try { + oldPasswordBytes = oldPassword.getBytes("UTF-8"); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + + needShowProgress(); + byte[] hash = new byte[currentPassword.current_salt.length * 2 + oldPasswordBytes.length]; + System.arraycopy(currentPassword.current_salt, 0, hash, 0, currentPassword.current_salt.length); + System.arraycopy(oldPasswordBytes, 0, hash, currentPassword.current_salt.length, oldPasswordBytes.length); + System.arraycopy(currentPassword.current_salt, 0, hash, hash.length - currentPassword.current_salt.length, currentPassword.current_salt.length); + + final TLRPC.TL_account_getPasswordSettings req = new TLRPC.TL_account_getPasswordSettings(); + req.current_password_hash = Utilities.computeSHA256(hash, 0, hash.length); + ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(final TLObject response, final TLRPC.TL_error error) { + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + needHideProgress(); + if (error == null) { + currentPasswordHash = req.current_password_hash; + passwordEntered = true; + AndroidUtilities.hideKeyboard(passwordEditText); + updateRows(); + } else { + if (error.text.equals("PASSWORD_HASH_INVALID")) { + onPasscodeError(true); + } else if (error.text.startsWith("FLOOD_WAIT")) { + int time = Utilities.parseInt(error.text); + String timeString; + if (time < 60) { + timeString = LocaleController.formatPluralString("Seconds", time); + } else { + timeString = LocaleController.formatPluralString("Minutes", time / 60); + } + showAlertWithText(LocaleController.getString("AppName", R.string.AppName), LocaleController.formatString("FloodWaitTime", R.string.FloodWaitTime, timeString)); + } else { + showAlertWithText(LocaleController.getString("AppName", R.string.AppName), error.text); + } + } + } + }); + } + }, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassWithoutLogin); + } + } else if (type == 1) { + if (passwordSetState == 0) { + if (passwordEditText.getText().length() == 0) { + onPasscodeError(false); + return; + } + titleTextView.setText(LocaleController.getString("ReEnterYourPasscode", R.string.ReEnterYourPasscode)); + firstPassword = passwordEditText.getText().toString(); + setPasswordSetState(1); + } else if (passwordSetState == 1) { + if (!firstPassword.equals(passwordEditText.getText().toString())) { + try { + Toast.makeText(getParentActivity(), LocaleController.getString("PasswordDoNotMatch", R.string.PasswordDoNotMatch), Toast.LENGTH_SHORT).show(); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + onPasscodeError(true); + return; + } + setPasswordSetState(2); + } else if (passwordSetState == 2) { + hint = passwordEditText.getText().toString(); + if (hint.toLowerCase().equals(firstPassword.toLowerCase())) { + try { + Toast.makeText(getParentActivity(), LocaleController.getString("PasswordAsHintError", R.string.PasswordAsHintError), Toast.LENGTH_SHORT).show(); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + onPasscodeError(false); + return; + } + if (!currentPassword.has_recovery) { + setPasswordSetState(3); + } else { + email = ""; + setNewPassword(false); + } + } else if (passwordSetState == 3) { + email = passwordEditText.getText().toString(); + if (!isValidEmail(email)) { + onPasscodeError(false); + return; + } + setNewPassword(false); + } else if (passwordSetState == 4) { + String code = passwordEditText.getText().toString(); + if (code.length() == 0) { + onPasscodeError(false); + return; + } + TLRPC.TL_auth_recoverPassword req = new TLRPC.TL_auth_recoverPassword(); + req.code = code; + ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { + @Override + public void run(TLObject response, final TLRPC.TL_error error) { + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + if (error == null) { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + NotificationCenter.getInstance().postNotificationName(NotificationCenter.didSetTwoStepPassword); + finishFragment(); + } + }); + builder.setMessage(LocaleController.getString("PasswordReset", R.string.PasswordReset)); + builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); + AlertDialog dialog = showAlertDialog(builder); + if (dialog != null) { + dialog.setCanceledOnTouchOutside(false); + dialog.setCancelable(false); + } + } else { + if (error.text.startsWith("CODE_INVALID")) { + onPasscodeError(true); + } else if (error.text.startsWith("FLOOD_WAIT")) { + int time = Utilities.parseInt(error.text); + String timeString; + if (time < 60) { + timeString = LocaleController.formatPluralString("Seconds", time); + } else { + timeString = LocaleController.formatPluralString("Minutes", time / 60); + } + showAlertWithText(LocaleController.getString("AppName", R.string.AppName), LocaleController.formatString("FloodWaitTime", R.string.FloodWaitTime, timeString)); + } else { + showAlertWithText(LocaleController.getString("AppName", R.string.AppName), error.text); + } + } + } + }); + } + }, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassWithoutLogin); + } + } + } + + private void onPasscodeError(boolean clear) { + if (getParentActivity() == null) { + return; + } + Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE); + if (v != null) { + v.vibrate(200); + } + if (clear) { + passwordEditText.setText(""); + } + AndroidUtilities.shakeTextView(titleTextView, 2, 0); + } + + private class ListAdapter extends BaseFragmentAdapter { + private Context mContext; + + public ListAdapter(Context context) { + mContext = context; + } + + @Override + public boolean areAllItemsEnabled() { + return false; + } + + @Override + public boolean isEnabled(int i) { + return i != setPasswordDetailRow && i != shadowRow && i != passwordSetupDetailRow && i != passwordEmailVerifyDetailRow; + } + + @Override + public int getCount() { + return loading || currentPassword == null ? 0 : rowCount; + } + + @Override + public Object getItem(int i) { + return null; + } + + @Override + public long getItemId(int i) { + return i; + } + + @Override + public boolean hasStableIds() { + return false; + } + + @Override + public View getView(int i, View view, ViewGroup viewGroup) { + int viewType = getItemViewType(i); + if (viewType == 0) { + if (view == null) { + view = new TextSettingsCell(mContext); + view.setBackgroundColor(0xffffffff); + } + TextSettingsCell textCell = (TextSettingsCell) view; + textCell.setTextColor(0xff212121); + if (i == changePasswordRow) { + textCell.setText(LocaleController.getString("ChangePassword", R.string.ChangePassword), true); + } else if (i == setPasswordRow) { + textCell.setText(LocaleController.getString("SetAdditionalPassword", R.string.SetAdditionalPassword), true); + } else if (i == turnPasswordOffRow) { + textCell.setText(LocaleController.getString("TurnPasswordOff", R.string.TurnPasswordOff), true); + } else if (i == changeRecoveryEmailRow) { + textCell.setText(LocaleController.getString("ChangeRecoveryEmail", R.string.ChangeRecoveryEmail), abortPasswordRow != -1); + } else if (i == setRecoveryEmailRow) { + textCell.setText(LocaleController.getString("SetRecoveryEmail", R.string.SetRecoveryEmail), false); + } else if (i == abortPasswordRow) { + textCell.setTextColor(0xffd24949); + textCell.setText(LocaleController.getString("AbortPassword", R.string.AbortPassword), false); + } + } else if (viewType == 1) { + if (view == null) { + view = new TextInfoPrivacyCell(mContext); + } + if (i == setPasswordDetailRow) { + ((TextInfoPrivacyCell) view).setText(LocaleController.getString("SetAdditionalPasswordInfo", R.string.SetAdditionalPasswordInfo)); + view.setBackgroundResource(R.drawable.greydivider_bottom); + } else if (i == shadowRow) { + ((TextInfoPrivacyCell) view).setText(""); + view.setBackgroundResource(R.drawable.greydivider_bottom); + } else if (i == passwordSetupDetailRow) { + ((TextInfoPrivacyCell) view).setText(LocaleController.formatString("EmailPasswordConfirmText", R.string.EmailPasswordConfirmText, currentPassword.email_unconfirmed_pattern)); + view.setBackgroundResource(R.drawable.greydivider_top); + } else if (i == passwordEnabledDetailRow) { + ((TextInfoPrivacyCell) view).setText(LocaleController.getString("EnabledPasswordText", R.string.EnabledPasswordText)); + view.setBackgroundResource(R.drawable.greydivider_bottom); + } else if (i == passwordEmailVerifyDetailRow) { + ((TextInfoPrivacyCell) view).setText(LocaleController.formatString("PendingEmailText", R.string.PendingEmailText, currentPassword.email_unconfirmed_pattern)); + view.setBackgroundResource(R.drawable.greydivider_bottom); + } + } + return view; + } + + @Override + public int getItemViewType(int i) { + if (i == setPasswordDetailRow || i == shadowRow || i == passwordSetupDetailRow || i == passwordEnabledDetailRow || i == passwordEmailVerifyDetailRow) { + return 1; + } + return 0; + } + + @Override + public int getViewTypeCount() { + return 2; + } + + @Override + public boolean isEmpty() { + return loading || currentPassword == null; + } + } +} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/VideoEditorActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/VideoEditorActivity.java index 440ee7616..7121d0a42 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/VideoEditorActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/VideoEditorActivity.java @@ -10,6 +10,7 @@ package org.telegram.ui; import android.annotation.TargetApi; import android.app.Activity; +import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; import android.graphics.SurfaceTexture; @@ -22,7 +23,6 @@ import android.view.LayoutInflater; import android.view.Surface; import android.view.TextureView; import android.view.View; -import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.CheckBox; import android.widget.CompoundButton; @@ -224,189 +224,183 @@ public class VideoEditorActivity extends BaseFragment implements TextureView.Sur } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setBackgroundColor(0xff333333); - actionBar.setItemsBackground(R.drawable.bar_selector_white); - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setTitle(LocaleController.getString("EditVideo", R.string.EditVideo)); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } else if (id == 1) { - synchronized (sync) { - if (videoPlayer != null) { - try { - videoPlayer.stop(); - videoPlayer.release(); - videoPlayer = null; - } catch (Exception e) { - FileLog.e("tmessages", e); - } + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackgroundColor(0xff333333); + actionBar.setItemsBackground(R.drawable.bar_selector_white); + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setTitle(LocaleController.getString("EditVideo", R.string.EditVideo)); + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); + } else if (id == 1) { + synchronized (sync) { + if (videoPlayer != null) { + try { + videoPlayer.stop(); + videoPlayer.release(); + videoPlayer = null; + } catch (Exception e) { + FileLog.e("tmessages", e); } } - if (delegate != null) { - if (compressVideo.getVisibility() == View.GONE || compressVideo.getVisibility() == View.VISIBLE && !compressVideo.isChecked()) { - delegate.didFinishEditVideo(videoPath, startTime, endTime, originalWidth, originalHeight, rotationValue, originalWidth, originalHeight, bitrate, estimatedSize, esimatedDuration); - } else { - delegate.didFinishEditVideo(videoPath, startTime, endTime, resultWidth, resultHeight, rotationValue, originalWidth, originalHeight, bitrate, estimatedSize, esimatedDuration); - } - } - finishFragment(); } + if (delegate != null) { + if (compressVideo.getVisibility() == View.GONE || compressVideo.getVisibility() == View.VISIBLE && !compressVideo.isChecked()) { + delegate.didFinishEditVideo(videoPath, startTime, endTime, originalWidth, originalHeight, rotationValue, originalWidth, originalHeight, bitrate, estimatedSize, esimatedDuration); + } else { + delegate.didFinishEditVideo(videoPath, startTime, endTime, resultWidth, resultHeight, rotationValue, originalWidth, originalHeight, bitrate, estimatedSize, esimatedDuration); + } + } + finishFragment(); } - }); + } + }); - ActionBarMenu menu = actionBar.createMenu(); - menu.addItemWithWidth(1, R.drawable.ic_done, AndroidUtilities.dp(56)); + ActionBarMenu menu = actionBar.createMenu(); + menu.addItemWithWidth(1, R.drawable.ic_done, AndroidUtilities.dp(56)); - fragmentView = inflater.inflate(R.layout.video_editor_layout, null, false); - originalSizeTextView = (TextView) fragmentView.findViewById(R.id.original_size); - editedSizeTextView = (TextView) fragmentView.findViewById(R.id.edited_size); - videoContainerView = fragmentView.findViewById(R.id.video_container); - textContainerView = fragmentView.findViewById(R.id.info_container); - controlView = fragmentView.findViewById(R.id.control_layout); - compressVideo = (CheckBox) fragmentView.findViewById(R.id.compress_video); - compressVideo.setText(LocaleController.getString("CompressVideo", R.string.CompressVideo)); - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); - compressVideo.setVisibility(originalHeight != resultHeight || originalWidth != resultWidth ? View.VISIBLE : View.GONE); - compressVideo.setChecked(preferences.getBoolean("compress_video", true)); - compressVideo.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - editor.putBoolean("compress_video", isChecked); - editor.commit(); - updateVideoEditedInfo(); - } - }); + fragmentView = inflater.inflate(R.layout.video_editor_layout, null, false); + originalSizeTextView = (TextView) fragmentView.findViewById(R.id.original_size); + editedSizeTextView = (TextView) fragmentView.findViewById(R.id.edited_size); + videoContainerView = fragmentView.findViewById(R.id.video_container); + textContainerView = fragmentView.findViewById(R.id.info_container); + controlView = fragmentView.findViewById(R.id.control_layout); + compressVideo = (CheckBox) fragmentView.findViewById(R.id.compress_video); + compressVideo.setText(LocaleController.getString("CompressVideo", R.string.CompressVideo)); + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); + compressVideo.setVisibility(originalHeight != resultHeight || originalWidth != resultWidth ? View.VISIBLE : View.GONE); + compressVideo.setChecked(preferences.getBoolean("compress_video", true)); + compressVideo.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { + @Override + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + editor.putBoolean("compress_video", isChecked); + editor.commit(); + updateVideoEditedInfo(); + } + }); - if (Build.VERSION.SDK_INT < 18) { - try { - MediaCodecInfo codecInfo = MediaController.selectCodec(MediaController.MIME_TYPE); - if (codecInfo == null) { + if (Build.VERSION.SDK_INT < 18) { + try { + MediaCodecInfo codecInfo = MediaController.selectCodec(MediaController.MIME_TYPE); + if (codecInfo == null) { + compressVideo.setVisibility(View.GONE); + } else { + String name = codecInfo.getName(); + if (name.equals("OMX.google.h264.encoder") || + name.equals("OMX.ST.VFM.H264Enc") || + name.equals("OMX.Exynos.avc.enc") || + name.equals("OMX.MARVELL.VIDEO.HW.CODA7542ENCODER") || + name.equals("OMX.MARVELL.VIDEO.H264ENCODER") || + name.equals("OMX.k3.video.encoder.avc") || //fix this later + name.equals("OMX.TI.DUCATI1.VIDEO.H264E")) { //fix this later compressVideo.setVisibility(View.GONE); } else { - String name = codecInfo.getName(); - if (name.equals("OMX.google.h264.encoder") || - name.equals("OMX.ST.VFM.H264Enc") || - name.equals("OMX.Exynos.avc.enc") || - name.equals("OMX.MARVELL.VIDEO.HW.CODA7542ENCODER") || - name.equals("OMX.MARVELL.VIDEO.H264ENCODER") || - name.equals("OMX.k3.video.encoder.avc") || //fix this later - name.equals("OMX.TI.DUCATI1.VIDEO.H264E")) { //fix this later + if (MediaController.selectColorFormat(codecInfo, MediaController.MIME_TYPE) == 0) { compressVideo.setVisibility(View.GONE); - } else { - if (MediaController.selectColorFormat(codecInfo, MediaController.MIME_TYPE) == 0) { - compressVideo.setVisibility(View.GONE); - } } } - } catch (Exception e) { - compressVideo.setVisibility(View.GONE); - FileLog.e("tmessages", e); } - } - - TextView titleTextView = (TextView) fragmentView.findViewById(R.id.original_title); - titleTextView.setText(LocaleController.getString("OriginalVideo", R.string.OriginalVideo)); - titleTextView = (TextView) fragmentView.findViewById(R.id.edited_title); - titleTextView.setText(LocaleController.getString("EditedVideo", R.string.EditedVideo)); - - videoTimelineView = (VideoTimelineView) fragmentView.findViewById(R.id.video_timeline_view); - videoTimelineView.setVideoPath(videoPath); - videoTimelineView.setDelegate(new VideoTimelineView.VideoTimelineViewDelegate() { - @Override - public void onLeftProgressChanged(float progress) { - if (videoPlayer == null || !playerPrepared) { - return; - } - try { - if (videoPlayer.isPlaying()) { - videoPlayer.pause(); - playButton.setImageResource(R.drawable.video_play); - } - videoPlayer.setOnSeekCompleteListener(null); - videoPlayer.seekTo((int) (videoDuration * progress)); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - needSeek = true; - videoSeekBarView.setProgress(videoTimelineView.getLeftProgress()); - updateVideoEditedInfo(); - } - - @Override - public void onRifhtProgressChanged(float progress) { - if (videoPlayer == null || !playerPrepared) { - return; - } - try { - if (videoPlayer.isPlaying()) { - videoPlayer.pause(); - playButton.setImageResource(R.drawable.video_play); - } - videoPlayer.setOnSeekCompleteListener(null); - videoPlayer.seekTo((int) (videoDuration * progress)); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - needSeek = true; - videoSeekBarView.setProgress(videoTimelineView.getLeftProgress()); - updateVideoEditedInfo(); - } - }); - - videoSeekBarView = (VideoSeekBarView) fragmentView.findViewById(R.id.video_seekbar); - videoSeekBarView.delegate = new VideoSeekBarView.SeekBarDelegate() { - @Override - public void onSeekBarDrag(float progress) { - if (progress < videoTimelineView.getLeftProgress()) { - progress = videoTimelineView.getLeftProgress(); - videoSeekBarView.setProgress(progress); - } else if (progress > videoTimelineView.getRightProgress()) { - progress = videoTimelineView.getRightProgress(); - videoSeekBarView.setProgress(progress); - } - if (videoPlayer == null || !playerPrepared) { - return; - } - if (videoPlayer.isPlaying()) { - try { - videoPlayer.seekTo((int) (videoDuration * progress)); - lastProgress = progress; - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } else { - lastProgress = progress; - needSeek = true; - } - } - }; - - playButton = (ImageView) fragmentView.findViewById(R.id.play_button); - playButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - play(); - } - }); - - textureView = (TextureView) fragmentView.findViewById(R.id.video_view); - textureView.setSurfaceTextureListener(this); - - updateVideoOriginalInfo(); - updateVideoEditedInfo(); - } else { - ViewGroup parent = (ViewGroup) fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); + } catch (Exception e) { + compressVideo.setVisibility(View.GONE); + FileLog.e("tmessages", e); } } + + TextView titleTextView = (TextView) fragmentView.findViewById(R.id.original_title); + titleTextView.setText(LocaleController.getString("OriginalVideo", R.string.OriginalVideo)); + titleTextView = (TextView) fragmentView.findViewById(R.id.edited_title); + titleTextView.setText(LocaleController.getString("EditedVideo", R.string.EditedVideo)); + + videoTimelineView = (VideoTimelineView) fragmentView.findViewById(R.id.video_timeline_view); + videoTimelineView.setVideoPath(videoPath); + videoTimelineView.setDelegate(new VideoTimelineView.VideoTimelineViewDelegate() { + @Override + public void onLeftProgressChanged(float progress) { + if (videoPlayer == null || !playerPrepared) { + return; + } + try { + if (videoPlayer.isPlaying()) { + videoPlayer.pause(); + playButton.setImageResource(R.drawable.video_play); + } + videoPlayer.setOnSeekCompleteListener(null); + videoPlayer.seekTo((int) (videoDuration * progress)); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + needSeek = true; + videoSeekBarView.setProgress(videoTimelineView.getLeftProgress()); + updateVideoEditedInfo(); + } + + @Override + public void onRifhtProgressChanged(float progress) { + if (videoPlayer == null || !playerPrepared) { + return; + } + try { + if (videoPlayer.isPlaying()) { + videoPlayer.pause(); + playButton.setImageResource(R.drawable.video_play); + } + videoPlayer.setOnSeekCompleteListener(null); + videoPlayer.seekTo((int) (videoDuration * progress)); + } catch (Exception e) { + FileLog.e("tmessages", e); + } + needSeek = true; + videoSeekBarView.setProgress(videoTimelineView.getLeftProgress()); + updateVideoEditedInfo(); + } + }); + + videoSeekBarView = (VideoSeekBarView) fragmentView.findViewById(R.id.video_seekbar); + videoSeekBarView.delegate = new VideoSeekBarView.SeekBarDelegate() { + @Override + public void onSeekBarDrag(float progress) { + if (progress < videoTimelineView.getLeftProgress()) { + progress = videoTimelineView.getLeftProgress(); + videoSeekBarView.setProgress(progress); + } else if (progress > videoTimelineView.getRightProgress()) { + progress = videoTimelineView.getRightProgress(); + videoSeekBarView.setProgress(progress); + } + if (videoPlayer == null || !playerPrepared) { + return; + } + if (videoPlayer.isPlaying()) { + try { + videoPlayer.seekTo((int) (videoDuration * progress)); + lastProgress = progress; + } catch (Exception e) { + FileLog.e("tmessages", e); + } + } else { + lastProgress = progress; + needSeek = true; + } + } + }; + + playButton = (ImageView) fragmentView.findViewById(R.id.play_button); + playButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + play(); + } + }); + + textureView = (TextureView) fragmentView.findViewById(R.id.video_view); + textureView.setSurfaceTextureListener(this); + + updateVideoOriginalInfo(); + updateVideoEditedInfo(); + return fragmentView; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/WallpapersActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/WallpapersActivity.java index b6fe28272..ab3380f21 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/WallpapersActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/WallpapersActivity.java @@ -101,120 +101,114 @@ public class WallpapersActivity extends BaseFragment implements NotificationCent } @Override - public View createView(LayoutInflater inflater) { - if (fragmentView == null) { - actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setAllowOverlayTitle(true); - actionBar.setTitle(LocaleController.getString("ChatBackground", R.string.ChatBackground)); - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if (id == -1) { - finishFragment(); - } else if (id == done_button) { - boolean done; - TLRPC.WallPaper wallPaper = wallpappersByIds.get(selectedBackground); - if (wallPaper != null && wallPaper.id != 1000001 && wallPaper instanceof TLRPC.TL_wallPaper) { - int width = AndroidUtilities.displaySize.x; - int height = AndroidUtilities.displaySize.y; - if (width > height) { - int temp = width; - width = height; - height = temp; - } - TLRPC.PhotoSize size = FileLoader.getClosestPhotoSizeWithSize(wallPaper.sizes, Math.min(width, height)); - String fileName = size.location.volume_id + "_" + size.location.local_id + ".jpg"; - File f = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), fileName); + public View createView(Context context, LayoutInflater inflater) { + actionBar.setBackButtonImage(R.drawable.ic_ab_back); + actionBar.setAllowOverlayTitle(true); + actionBar.setTitle(LocaleController.getString("ChatBackground", R.string.ChatBackground)); + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if (id == -1) { + finishFragment(); + } else if (id == done_button) { + boolean done; + TLRPC.WallPaper wallPaper = wallpappersByIds.get(selectedBackground); + if (wallPaper != null && wallPaper.id != 1000001 && wallPaper instanceof TLRPC.TL_wallPaper) { + int width = AndroidUtilities.displaySize.x; + int height = AndroidUtilities.displaySize.y; + if (width > height) { + int temp = width; + width = height; + height = temp; + } + TLRPC.PhotoSize size = FileLoader.getClosestPhotoSizeWithSize(wallPaper.sizes, Math.min(width, height)); + String fileName = size.location.volume_id + "_" + size.location.local_id + ".jpg"; + File f = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), fileName); + File toFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "wallpaper.jpg"); + try { + done = Utilities.copyFile(f, toFile); + } catch (Exception e) { + done = false; + FileLog.e("tmessages", e); + } + } else { + if (selectedBackground == -1) { + File fromFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "wallpaper-temp.jpg"); File toFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "wallpaper.jpg"); + done = fromFile.renameTo(toFile); + } else { + done = true; + } + } + + if (done) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + editor.putInt("selectedBackground", selectedBackground); + editor.putInt("selectedColor", selectedColor); + editor.commit(); + ApplicationLoader.reloadWallpaper(); + } + finishFragment(); + } + } + }); + + ActionBarMenu menu = actionBar.createMenu(); + doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); + + fragmentView = inflater.inflate(R.layout.settings_wallpapers_layout, null, false); + listAdapter = new ListAdapter(context); + + progressBar = (ProgressBar) fragmentView.findViewById(R.id.action_progress); + backgroundImage = (ImageView) fragmentView.findViewById(R.id.background_image); + listView = (HorizontalListView) fragmentView.findViewById(R.id.listView); + listView.setAdapter(listAdapter); + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, int i, long l) { + if (i == 0) { + if (getParentActivity() == null) { + return; + } + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + + CharSequence[] items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("Cancel", R.string.Cancel)}; + + builder.setItems(items, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { try { - done = Utilities.copyFile(f, toFile); + if (i == 0) { + Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); + File image = Utilities.generatePicturePath(); + if (image != null) { + takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image)); + currentPicturePath = image.getAbsolutePath(); + } + startActivityForResult(takePictureIntent, 10); + } else if (i == 1) { + Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); + photoPickerIntent.setType("image/*"); + startActivityForResult(photoPickerIntent, 11); + } } catch (Exception e) { - done = false; FileLog.e("tmessages", e); } - } else { - if (selectedBackground == -1) { - File fromFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "wallpaper-temp.jpg"); - File toFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "wallpaper.jpg"); - done = fromFile.renameTo(toFile); - } else { - done = true; - } } - - if (done) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - editor.putInt("selectedBackground", selectedBackground); - editor.putInt("selectedColor", selectedColor); - editor.commit(); - ApplicationLoader.reloadWallpaper(); - } - finishFragment(); - } + }); + showAlertDialog(builder); + } else { + TLRPC.WallPaper wallPaper = wallPapers.get(i - 1); + selectedBackground = wallPaper.id; + listAdapter.notifyDataSetChanged(); + processSelectedBackground(); } - }); - - ActionBarMenu menu = actionBar.createMenu(); - doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56)); - - fragmentView = inflater.inflate(R.layout.settings_wallpapers_layout, null, false); - listAdapter = new ListAdapter(getParentActivity()); - - progressBar = (ProgressBar)fragmentView.findViewById(R.id.action_progress); - backgroundImage = (ImageView)fragmentView.findViewById(R.id.background_image); - listView = (HorizontalListView)fragmentView.findViewById(R.id.listView); - listView.setAdapter(listAdapter); - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView adapterView, View view, int i, long l) { - if (i == 0) { - if (getParentActivity() == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - - CharSequence[] items = new CharSequence[] {LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("Cancel", R.string.Cancel)}; - - builder.setItems(items, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialogInterface, int i) { - try { - if (i == 0) { - Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); - File image = Utilities.generatePicturePath(); - if (image != null) { - takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image)); - currentPicturePath = image.getAbsolutePath(); - } - startActivityForResult(takePictureIntent, 10); - } else if (i == 1) { - Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); - photoPickerIntent.setType("image/*"); - startActivityForResult(photoPickerIntent, 11); - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - }); - showAlertDialog(builder); - } else { - TLRPC.WallPaper wallPaper = wallPapers.get(i - 1); - selectedBackground = wallPaper.id; - listAdapter.notifyDataSetChanged(); - processSelectedBackground(); - } - } - }); - - processSelectedBackground(); - } else { - ViewGroup parent = (ViewGroup)fragmentView.getParent(); - if (parent != null) { - parent.removeView(fragmentView); } - } + }); + + processSelectedBackground(); + return fragmentView; } diff --git a/TMessagesProj/src/main/res/drawable-hdpi/devices.png b/TMessagesProj/src/main/res/drawable-hdpi/devices.png new file mode 100755 index 000000000..768704968 Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-hdpi/devices.png differ diff --git a/TMessagesProj/src/main/res/drawable-hdpi/greydivider_top.9.png b/TMessagesProj/src/main/res/drawable-hdpi/greydivider_top.9.png new file mode 100644 index 000000000..4523e953c Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-hdpi/greydivider_top.9.png differ diff --git a/TMessagesProj/src/main/res/drawable-hdpi/igvideo.png b/TMessagesProj/src/main/res/drawable-hdpi/igvideo.png new file mode 100644 index 000000000..92c22481f Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-hdpi/igvideo.png differ diff --git a/TMessagesProj/src/main/res/drawable-hdpi/link.png b/TMessagesProj/src/main/res/drawable-hdpi/link.png new file mode 100644 index 000000000..5ad1fcb8f Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-hdpi/link.png differ diff --git a/TMessagesProj/src/main/res/drawable-mdpi/devices.png b/TMessagesProj/src/main/res/drawable-mdpi/devices.png new file mode 100755 index 000000000..b6bd7a72c Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-mdpi/devices.png differ diff --git a/TMessagesProj/src/main/res/drawable-mdpi/greydivider_top.9.png b/TMessagesProj/src/main/res/drawable-mdpi/greydivider_top.9.png new file mode 100644 index 000000000..1faeb2636 Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-mdpi/greydivider_top.9.png differ diff --git a/TMessagesProj/src/main/res/drawable-mdpi/igvideo.png b/TMessagesProj/src/main/res/drawable-mdpi/igvideo.png new file mode 100644 index 000000000..e7b93b3b7 Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-mdpi/igvideo.png differ diff --git a/TMessagesProj/src/main/res/drawable-mdpi/link.png b/TMessagesProj/src/main/res/drawable-mdpi/link.png new file mode 100644 index 000000000..24125b57e Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-mdpi/link.png differ diff --git a/TMessagesProj/src/main/res/drawable-xhdpi/devices.png b/TMessagesProj/src/main/res/drawable-xhdpi/devices.png new file mode 100755 index 000000000..9b5663ff9 Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-xhdpi/devices.png differ diff --git a/TMessagesProj/src/main/res/drawable-xhdpi/greydivider_top.9.png b/TMessagesProj/src/main/res/drawable-xhdpi/greydivider_top.9.png new file mode 100644 index 000000000..aeb9cc803 Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-xhdpi/greydivider_top.9.png differ diff --git a/TMessagesProj/src/main/res/drawable-xhdpi/igvideo.png b/TMessagesProj/src/main/res/drawable-xhdpi/igvideo.png new file mode 100644 index 000000000..bad393640 Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-xhdpi/igvideo.png differ diff --git a/TMessagesProj/src/main/res/drawable-xhdpi/link.png b/TMessagesProj/src/main/res/drawable-xhdpi/link.png new file mode 100644 index 000000000..ba82f35b9 Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-xhdpi/link.png differ diff --git a/TMessagesProj/src/main/res/drawable-xxhdpi/devices.png b/TMessagesProj/src/main/res/drawable-xxhdpi/devices.png new file mode 100755 index 000000000..3afa7788d Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-xxhdpi/devices.png differ diff --git a/TMessagesProj/src/main/res/drawable-xxhdpi/greydivider_top.9.png b/TMessagesProj/src/main/res/drawable-xxhdpi/greydivider_top.9.png new file mode 100644 index 000000000..4c3d0b316 Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-xxhdpi/greydivider_top.9.png differ diff --git a/TMessagesProj/src/main/res/drawable-xxhdpi/igvideo.png b/TMessagesProj/src/main/res/drawable-xxhdpi/igvideo.png new file mode 100644 index 000000000..d13eab929 Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-xxhdpi/igvideo.png differ diff --git a/TMessagesProj/src/main/res/drawable-xxhdpi/link.png b/TMessagesProj/src/main/res/drawable-xxhdpi/link.png new file mode 100644 index 000000000..655dc9e9a Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-xxhdpi/link.png differ diff --git a/TMessagesProj/src/main/res/values-ar/strings.xml b/TMessagesProj/src/main/res/values-ar/strings.xml index 2e2b6bdd3..743678431 100644 --- a/TMessagesProj/src/main/res/values-ar/strings.xml +++ b/TMessagesProj/src/main/res/values-ar/strings.xml @@ -85,6 +85,10 @@ جاري الكتابة… يكتب… يكتبون… + %1$s يقوم بإرسال مقطع صوتي... + %1$s يقوم بإرسال صورة... + %1$s يقوم بإرسال مقطع مرئي... + %1$s يقوم بإرسال ملف... هل يوجد لديك سؤال\nحول تيليجرام؟ التقط صورة صورة @@ -117,6 +121,7 @@ المرفق غير مدعوم عداد التدمير الذاتي إشعارات الخدمة + جاري جلب معلومات الرابط... %1$s قام بتعيين عداد التدمير الذاتي إلى to %2$s لقد قمت بتعيين التدمير الذاتي إلى %1$s @@ -150,7 +155,7 @@ %1$s قام بإخراجك من المجموعة %2$s %1$s قام بمغادرة المجموعة %2$s %1$s قام بالتسجيل في تيليجرام! - %1$s,\nتم تسجيل الدخول لحسابك من جهاز جديد يوم %2$s\n\nالجهاز: %3$s\nالموقع: %4$s\n\nإذا لم يكن أنت من سجل الدخول، يمكنك الذهاب للإعدادات ثم تسجيل الخروج من كافة الأجهزة الأخرى.\n\nشكرًا,\nفريق عمل تيليجرام + %1$s,\nتم تسجيل الدخول لحسابك من جهاز جديد يوم %2$s\n\nالجهاز: %3$s\nالموقع: %4$s\n\nإذا لم يكن أنت من سجل الدخول، يمكنك الذهاب للإعدادات ثم تسجيل الخروج من كافة الأجهزة الأخرى. كما يمكنك تفعيل التحقق بخطوتين إذا رغبت بذلك عن طريق إعدادات الخصوصية.\n\nشكرًا,\nفريق عمل تيليجرام %1$s قام بتغيير صورته الشخصية الرد الرد على %1$s @@ -245,7 +250,7 @@ لا يوجد صوت افتراضي الدعم - إذا كان على الصامت + فقط في وضع الصامت خلفية الدردشة الرسائل أرسل بزر الإدخال @@ -305,14 +310,26 @@ تعطيل إيقاف الأصوات داخل المحادثات + افتراضي + + الأجهزة المسجّل دخول منها + الجهاز الحالي + لا يوجد أجهزة مسجّل دخول منها أخرى + يمكنك تسجيل الدخول لحسابك في تيليجرام من جوال آخر، جهاز لوحي، أو أجهزة الكمبيوتر، باستخدام نفس رقم الهاتف. تيليجرام سيقوم بمزامنة كافة بياناتك بشكل لحظي. + الأجهزة المسجّل دخول منها + قم بالتحكم بالأجهزة المسجل دخول منها. + اضغط على الجهاز لتسجيل الخروج منه. + هل ترغب في تسجيل الخروج من هذا الجهاز؟ + تطبيق غير رسمي - رمز المرور + قفل رمز المرور غيًر رمز المرور عندما تختار رمز مرور، ستظهر علامة قفل في صفحة المحادثات. اضغط عليها لقفل أو فتح تيليجرام.\n\nملاحظة: إذا نسيت رمز المرور، ستحتاج لحذف وإعادة تنزيل التطبيق. وستخسر كافة محادثاتك السرية وستعود المحادثات العادية فور إعادة تسجيل الدخول. سوف ترى الآن أيقونة قفل في صفحة المحادثات. اضغط عليها لقفل تطبيق تيليجرام برمز المرور الجديد الخاص بك. الرمز كلمة المرور قم بإدخال رمز المرور الخاص بك الحالي + قم بإدخال رمز مرور قم بإدخال رمز المرور الخاص بك الجديد قم بإدخال رمز المرور الخاص بك قم بإعادة إدخال رمز المرور الخاص بك الجديدة @@ -372,29 +389,55 @@ هل ترغب في مسح سجل البحث؟ مسح - Password - Change password - Old password - Enter old password - New password - Enter new password - Verify new password - Enter your password - Hint - Enter hint - Important: you will lose all your chats, messages and media in the case of a forgotten password. - Passwords do not match - Incorrect old password - Incorrect password - Incorrect new password - Hint shouldn\'t contain password - Enter password - Important: you will lose all your chats, messages and media. - Delete account - Delete my account - Hint: %1$s - Are you sure you want to delete your account? - We deeply clarify you that you will lose all your chats, messages and media. Are you really sure? + التحقق بخطوتين + تعيين كلمة مرور إضافية + يمكنك تعيين كلمة مرور يتم طلبها عند محاولة تسجيل الدخول من جهاز جديد بالإضافة إلى الرمز الذي يأتيك في رسالة قصيرة. + كلمة المرور الخاصة بك + يرجى إعادة إدخال كلمة المرور الخاصة بك: + قم بإدخال كلمة مرور + يرجى إدخال كلمة المرور الجديدة الخاصة بك: + يرجى إعادة إدخال كلمة المرور الخاصة بك: + بريد إسترداد الحساب + بريدك الإلكتروني + فضلًا أضف بريد إلكتروني صحيح. هذه هي الطريقة الوحيدة لإستعادة كلمة المرور بعد نسيانها. + تخطّي + تحذير + الموضوع جدّيّ.\n\nإذا نسيت كلمة المرور الخاصة بك، لن تستطيع الدخول على حساب تيليجرام الخاص بك. لن يكون هناك طريقة لإستعادته. + تقريبًا انتهينا! + يرجى الذهاب لبريدك الإلكتروني والضغط على رابط التأكيد لإنهاء إعدادات التحقق بخطوتين. تأكد من الإطّلاع على مجلد الرسائل الغير مرغوب بها أيضًا. + تم بنجاح! + تم تفعيل كلمة المرور الخاصة بالتحقق بخطوتين. + تغيير كلة المرور + إيقاف كلمة المرور + اختر بريد إلكتروني لإسترداد الحساب + غيّر البريد الإلكتروني لإسترداد الحساب + هل أنت متأكد من رغبتك في تعطيل كلمة المرور؟ + تلميحة كلمة المرور + فضلًا اختر تلميحة لكلمة المرور الخاصة بك: + كلمتي المرور غير متطابقة + إنهاء عملية إعداد التحقق بخطوتين + فضلًا اتّبع هذه الخطوات لإكمال إعدادات التحقق بخطوتين:\n\n١. قم بالإطلاع على بريدة الإلكتروني بما فيه مجلد الرسائل الغير مرغوب بها\n%1$s\n\n٢. اضغط على رابط التأكيد + التلميحة يجب أن تكون مختلفة عن كلمة المرور ذاتها + بريد إلكتروني غير صحيح + عذرًا + لم تقم بإضافة بريد إلكتروني لإستعادة كلمة المرور عند اختيارها، لذلك خياراتك المتبقية هي تذكّر كلمة المرور أو إعادة تعيين حسابك. + لقد قمنا بإرسال رمز الإستعادة إلى بريدك الإلكتروني الذي اخترته مسبقًا:\n\n%1$s + يرجى الإطلاع على بريدك الإلكتروني وإدخال الرمز المكون من ٦ أرقام الذي قمنا بإرساله هنا. + هل تواجه صعوبات في الدخول على بريدك الإلكتروني %1$s؟ + إذا لم تستطع الدخول على بريد الإسترداد الخاص بك، خياراتك المتبقية هي تذكّر كلمة المرور أو إعادة تعيين حسابك. + إعادة تعيين حسابي + إذا قمت بإعادة تعيين حسابك، ستفقد كافّة محادثاتك ورسائلك، بالإضافة إلى الوسائط والملفات التي تمت مشاركتها. + تحذير + لا يمكن الرجوع عن هذا الخيار.\n\nإذا قمت بإعادة تعيين حسابك، كافة رسائلك ومحادثاتك سيتم حذفها. + إعادة تعيين + كلمة المرور + تم تفعيل التحقق بخطوتين، لذلك حسابك محميّ بكلمة مرور إضافية. + هل نسيت كلمة المرور؟ + كلمة مرور الإسترداد + الرمز + تم تعطيل كلمة المرور + لقد قمت بتفعيل التحقق بخطوتين.\nعند محاولة تسجيل الدخول على حساب تيليجرام الخاص بك من جهاز جديد، سيتم طلب كلمة المرور التي اخترتها هنا منك. + البريد الإلكتروني لإسترداد الحساب %1$s غير فعّال بعد ويلزم تفعيله الخصوصية والأمان الخصوصية @@ -486,6 +529,7 @@ رقم الهاتف غير صحيح انتهت صلاحية الرمز الخاص بك، يرجى تسجيل الدخول مرة أخرى محاولات كثيرة خاطئة، نرجو المحاولة لاحقًا + محاولات كثيرة خاطئة، يرجى المحاولة خلال %1$s الرمز غير صحيح الاسم الأول غير صحيح اسم العائلة غير صحيح diff --git a/TMessagesProj/src/main/res/values-de/strings.xml b/TMessagesProj/src/main/res/values-de/strings.xml index b38245a61..fd4c0035a 100644 --- a/TMessagesProj/src/main/res/values-de/strings.xml +++ b/TMessagesProj/src/main/res/values-de/strings.xml @@ -85,6 +85,10 @@ schreibt… schreibt... tippen… + %1$s nimmt etwas auf... + %1$s schickt Bild... + %1$s schickt Video... + %1$s schickt Datei... Hast du eine Frage\nzu Telegram? Foto aufnehmen Galerie @@ -117,6 +121,7 @@ Nicht unterstützte Datei Selbstzerstörungs-Timer setzen Servicemeldungen + Lade Linkvorschau... %1$s hat den Selbstzerstörungs-Timer auf %2$s gesetzt Du hast den Selbstzerstörungs-Timer auf %1$s gesetzt @@ -150,7 +155,7 @@ %1$s hat dich aus der Gruppe %2$s entfernt %1$s hat die Gruppe %2$s verlassen %1$s benutzt jetzt Telegram! - %1$s,\nWir haben eine Anmeldung von einem neuen Gerät am %2$s festgestellt.\n\nGerät: %3$s\nStandort: %4$s\n\nWenn du das nicht selbst gewesen bist, melde alle anderen Sitzungen in den Telegram Einstellungen unverzüglich ab.\n\nMit freundlichen Grüßen,\nDein Telegram Team + %1$s,\nWir haben eine Anmeldung von einem neuen Gerät am %2$s festgestellt.\n\nGerät: %3$s\nStandort: %4$s\n\nWenn du das nicht selbst gewesen bist, melde alle anderen Sitzungen in den Telegram Einstellungen unverzüglich ab.\n\nBeachte unsere zweistufige Bestätigung, welche du in den Telegram Einstellungen unter Privatsphäre und Sicherheit optional aktivieren kannst.\n\nDein Telegram Team %1$s hat das Profilbild geändert Antworten %1$s antworten @@ -245,17 +250,17 @@ Kein Ton Standard Support - Nur wenn stumm + Wenn lautlos Chat-Hintergrundbild Nachrichten Mit Enter senden - Alle anderen Sitzungen beenden + Alle anderen Geräte abmelden Ereignisse Kontakt ist Telegram beigetreten PEBBLE Sprache Bedenke bitte, dass der Telegram Support von einem ehrenamtlichen Team betreut wird. Wir versuchen so schnell wie möglich zu antworten, dies kann jedoch manchmal ein bisschen dauern.
]]>Bitte schau auch in den Fragen und Antworten ]]> nach. Dort findest du Antworten auf die meisten Fragen und wichtige Tipps zur Problembehandlung]]>.
- Frage einen Freiwilligen + Eine Frage stellen Fragen und Antworten https://telegram.org/faq/de Lokalisierung löschen? @@ -305,14 +310,26 @@ Deaktiviert Aus In-Chat Töne + Standard + + Sitzungen + Aktuelle Sitzung + Keine anderen Geräte + Du kannst dich von jedem Handy, Tablet und Computer bei Telegram mit derselben Telefonnummer anmelden. Alles wird immer sofort synchronisiert. + Andere Geräte + Überprüfe alle deine angemeldeten Geräte. + Tippe auf eine Sitzung um sie zu beenden. + Dieses Gerät abmelden? + inoffizielle Version - Pincode + Pincode-Sperre Pincode ändern Wenn du die Code-Sperre aktivierst, erscheint ein Schloss ganz oben über der Chatliste. Tippe auf das Schloss, um deine Chats zu sperren und zu entsperren.\n\nÜbrigens: Wenn du den Pincode vergisst, musst du Telegram löschen und neu installieren. Dadurch verlierst du alle Geheimen Chats. Du wirst nun ein Schloss über der Chatliste sehen. Tippe darauf um deine Chats mit dem neuen Pincode zu sperren. Pincode Kennwort Aktuellen Pincode eingeben + Pincode eingeben Neuen Pincode eingeben Deinen Pincode eingeben Neuen Pincode erneut eingben @@ -372,29 +389,55 @@ Suchverlauf löschen? Löschen - Password - Change password - Old password - Enter old password - New password - Enter new password - Verify new password - Enter your password - Hint - Enter hint - Important: you will lose all your chats, messages and media in the case of a forgotten password. - Passwords do not match - Incorrect old password - Incorrect password - Incorrect new password - Hint shouldn\'t contain password - Enter password - Important: you will lose all your chats, messages and media. - Delete account - Delete my account - Hint: %1$s - Are you sure you want to delete your account? - We deeply clarify you that you will lose all your chats, messages and media. Are you really sure? + Zweistufige Bestätigung + Zusätzliches Kennwort festlegen + Du kannst ein eigenes Kennwort festlegen, um dich an einem neuen Gerät anzumelden, zusätzlich zum SMS-Code. + Dein Kennwort + Bitte aktuelles Kennwort eingeben + Kennwort eingeben + Bitte neues Kennwort eingeben + Bitte erneut dein Kennwort eingeben + Wiederherstellung + Deine E-Mail + Falls du dein Kennwort vergisst, benötigen wir deine richtige Email Adresse. + Überspringen + Warnung + Keine gute Idee.\n\nWenn du dein Passwort vergisst, verlierst du den Zugang zu deinem Telegram Konto. Für immer, ohne Ausnahme. + Fast geschafft! + Bitte überprüfe deine Mails (auch den Spam-Ordner) um die zweistufige Bestätigung abzuschließen. + Geschafft! + Dein Kennwort für die zweistufige Bestätigung ist jetzt aktiv. + Kennwort ändern + Kennwort deaktivieren + E-Mailadresse festlegen + E‑Mail-Adresse zur Wiederherstellung ändern + Sicher, dass du dein Kennwort deaktivieren willst? + Kennwort-Erinnerung + Bitte Hinweis auf dein Kennwort eingeben + Kennwörter stimmen nicht überein + Einrichten abbrechen + Bitte folge diesen Schritten um die zweistufige Bestätigung abzuschließen:\n\n1. Überprüfe deine Mails (auch den Spam-Ordner)\n%1$s\n\n2. Auf den Link klicken. + Der Hinweis darf nicht das Kennwort sein. + Ungültige E-Mail + Tut uns leid + Da du für diesen Fall keine Email Adresse hinterlegt hast, kannst du nur noch hoffen, dass dir dein Kennwort wieder einfällt oder du musst dein Telegram Konto zurückzusetzen. + Wir haben den Wiederherstellungscode an diese Adresse geschickt:\n\n%1$s + Überprüfe deine Mails und gib den 6-stelligen Code aus userer Email ein. + Du hast keinen Zugang zu deiner Adresse %1$s? + Wenn du nicht in deine Emails kommst, kannst du nur hoffen, dass dir dein Kennwort wieder einfällt oder du musst dein Telegram Konto zurückzusetzen. + KONTO ZURÜCKSETZEN + Wenn du dein Konto zurücksetzt, verlierst du alle Chats und Nachrichten, ebenso deine geteilten Bilder und Videos. + Warnung + Dies kann nicht rückgängig gemacht werden.\n\nWenn du dein Konto zurücksetzt, sind alle Chats gelöscht. + Zurücksetzen + Kennwort + Du hast die zweistufige Bestätigung aktiviert. Dein Konto ist mit einem zusätzlichem Kennwort geschützt. + Kennwort vergessen? + Kennwort zurücksetzen + Code + Kennwort deaktiviert + Du hast die zweistufige Bestätigung aktiviert.\nWenn du dich bei Telegram anmeldest, brauchst du dein Kennwort. + Deine E-Mail Adresse %1$s wurde noch verifiziert und ist daher noch nicht aktiv. Privatsphäre und Sicherheit Privatsphäre @@ -486,6 +529,7 @@ Ungültige Telefonnummer Code ist abgelaufen, bitte melde dich erneut an Zu viele Versuche in zu kurzer Zeit, versuche es bitte später erneut. + Zu viele Versuche, bitte erneut in %1$s versuchen Ungültiger Code Ungültiger Vorname Ungültiger Nachname diff --git a/TMessagesProj/src/main/res/values-es/strings.xml b/TMessagesProj/src/main/res/values-es/strings.xml index 6056de8d2..b2b2f7b37 100644 --- a/TMessagesProj/src/main/res/values-es/strings.xml +++ b/TMessagesProj/src/main/res/values-es/strings.xml @@ -85,6 +85,10 @@ escribiendo... está escribiendo... están escribiendo... + %1$s está grabando un audio... + %1$s está enviando una foto... + %1$s está enviando un vídeo... + %1$s está enviando un archivo... ¿Tienes preguntas\nsobre Telegram? Hacer foto Galería @@ -117,6 +121,7 @@ Adjunto no soportado Establecer autodestrucción Servicio de notificaciones + Obteniendo información... %1$s activó la autodestrucción en %2$s Activaste la autodestrucción en %1$s @@ -150,7 +155,7 @@ %1$s te expulsó del grupo %2$s %1$s dejó el grupo %2$s ¡%1$s se unió a Telegram! - %1$s,\nDetectamos un inicio de sesión en tu cuenta desde un nuevo dispositivo, el %2$s\n\nDispositivo: %3$s\nUbicación: %4$s\n\nSi no eras tú, puedes ir a Ajustes - Privacidad y seguridad - Cerrar todas las otras sesiones.\n\nAtentamente,\nEl equipo de Telegram + %1$s,\nDetectamos un inicio de sesión en tu cuenta desde un nuevo dispositivo, el %2$s\n\nDispositivo: %3$s\nUbicación: %4$s\n\nSi no eras tú, puedes ir a Ajustes - Privacidad y seguridad - Cerrar todas las otras sesiones.\n\nSi crees que alguien ha iniciado la sesión sin tu consentimiento, puedes activar la verificación en dos pasos, en los ajustes de privacidad y seguridad.\n\nAtentamente,\nEl equipo de Telegram %1$s actualizó su foto de perfil Responder Responder a %1$s @@ -245,7 +250,7 @@ Sin sonido Por defecto Soporte - Only if silent + Sólo si está silenciado Fondo de chat Mensajes Enviar con \'Intro\' @@ -305,6 +310,17 @@ Desactivado Apagado Sonidos en el chat + Por defecto + + Sesiones activas + Sesión actual + Sin otras sesiones activas + Puedes iniciar sesión en Telegram desde otro móvil, tablet o computador, usando el mismo número de teléfono. Todos tus datos se sincronizarán al instante. + Sesiones activas + Controla tus sesiones en otros dispositivos. + Pulsa una sesión para cerrarla. + ¿Cerrar esta sesión? + aplicación no oficial Código de acceso Cambiar código de acceso @@ -313,6 +329,7 @@ PIN Contraseña Pon tu código de acceso actual + Pon un código de acceso Pon tu nuevo código de acceso Pon tu código de acceso Pon, otra vez, tu nuevo código @@ -372,29 +389,55 @@ ¿Quieres borrar el historial de búsqueda? Borrar - Password - Change password - Old password - Enter old password - New password - Enter new password - Verify new password - Enter your password - Hint - Enter hint - Important: you will lose all your chats, messages and media in the case of a forgotten password. - Passwords do not match - Incorrect old password - Incorrect password - Incorrect new password - Hint shouldn\'t contain password - Enter password - Important: you will lose all your chats, messages and media. - Delete account - Delete my account - Hint: %1$s - Are you sure you want to delete your account? - We deeply clarify you that you will lose all your chats, messages and media. Are you really sure? + Verificación en dos pasos + Poner contraseña adicional + Puedes poner una contraseña, que será requerida cuando inicies sesión en un nuevo dispositivo, además del código que recibes vía SMS. + Tu contraseña + Por favor, pon tu contraseña + Pon una contraseña + Por favor, pon tu nueva contraseña + Pon, otra vez, tu contraseña + E-mail de recuperación + Tu e-mail + Por favor, añade un e-mail válido. Es la única forma de recuperar una contraseña olvidada. + Omitir + Advertencia + En serio.\n\nSi olvidas tu contraseña, perderás el acceso a tu cuenta de Telegram. No habrá manera de recuperarla. + ¡Ya casi! + Por favor, revisa tu e-mail (no olvides la carpeta de spam) para completar la configuración de la verificación en dos pasos. + ¡Listo! + Tu contraseña para la verificación en dos pasos está activada. + Cambiar contraseña + Desactivar la contraseña + Poner e-mail de recuperación + Cambiar e-mail de recuperación + ¿Quieres desactivar tu contraseña? + Pista para la contraseña + Por favor, crea una pista para tu contraseña + Las contraseñas no coinciden + Anular la configuración de la verificación en dos pasos + Por favor, sigue estos pasos para completar la configuración de la verificación en dos pasos:\n\n1. Revisa tu e-mail (no olvides la carpeta de spam).\n%1$s\n\n2. Haz click en el enlace de validación. + La pista debe ser diferente de tu contraseña + E-mail inválido + Lo sentimos + Como no estableciste un e-mail de recuperación cuando configuraste tu contraseña, las opciones restantes son recordar tu contraseña o restablecer tu cuenta. + Enviamos un código de recuperación al e-mail que nos diste:\n\n%1$s + Por favor, revisa tu e-mail y pon el código de 6 dígitos que te enviamos ahí. + ¿Tienes problemas para acceder a tu e-mail %1$s? + Si no puedes acceder a tu e-mail, las opciones restantes son recordar tu contraseña o restablecer tu cuenta. + RESTABLECER MI CUENTA + Si continúas con el reinicio de tu cuenta, perderás todos tus chats y mensajes, junto con toda la multimedia y archivos que compartiste. + Advertencia + Esta acción no puede deshacerse.\n\nSi reinicias tu cuenta, todos tus mensajes y chats se eliminarán. + Restablecer + Contraseña + Activaste la verificación en dos pasos, así que tu cuenta está protegida con una contraseña adicional. + ¿Olvidaste la contraseña? + Recuperar contraseña + Código + Contraseña desactivada + Tienes activada la verificación en dos pasos.\nNecesitarás la contraseña que configuraste para iniciar tu sesión en Telegram. + Tu e-mail de recuperación %1$s aún no está activo y su confirmación está pendiente. Privacidad y seguridad Privacidad @@ -486,6 +529,7 @@ Número de teléfono inválido Código expirado. Por favor, vuelve a iniciar sesión. Muchos intentos. Por favor, prueba de nuevo más tarde. + Demasiados intentos. Por favor, reinténtalo en %1$s Código inválido Nombre inválido Apellidos inválidos diff --git a/TMessagesProj/src/main/res/values-it/strings.xml b/TMessagesProj/src/main/res/values-it/strings.xml index afe56a4fd..8d827737c 100644 --- a/TMessagesProj/src/main/res/values-it/strings.xml +++ b/TMessagesProj/src/main/res/values-it/strings.xml @@ -85,6 +85,10 @@ sta scrivendo… sta scrivendo… stanno scrivendo… + %1$s sta registrando un audio... + %1$s sta inviando una foto... + %1$s sta inviando un video... + %1$s sta inviando un file... Hai una domanda\nsu Telegram? Scatta una foto Galleria @@ -113,10 +117,11 @@ ANNULLA Salva in download Condividi - Applica file di localizzazione + Applica traduzione Allegato non supportato Timer di autodistruzione Notifiche di servizio + Recupero le info del link... %1$s ha impostato il timer di autodistruzione a %2$s Hai impostato il timer di autodistruzione a %1$s @@ -150,7 +155,7 @@ %1$s ti ha espulso dal gruppo %2$s %1$s ha lasciato il gruppo %2$s %1$s ha iniziato a usare Telegram! - %1$s,\nAbbiamo rilevato un accesso al tuo account da un nuovo dispositivo il %2$s\n\nDispositivo: %3$s\nPosizione: %4$s\n\nSe non sei stato tu, puoi andare su Impostazioni - Privacy e Sicurezza - Termina tutte le sessioni.\n\nGrazie,\nil team di Telegram + %1$s,\nAbbiamo rilevato un accesso al tuo account da un nuovo dispositivo il %2$s\n\nDispositivo: %3$s\nPosizione: %4$s\n\nSe non sei stato tu, puoi andare su Impostazioni - Privacy e Sicurezza - Sessioni - Termina tutte le sessioni.\n\nSe pensi che qualcuno si sia collegato al tuo account contro il tuo volere, ti raccomandiamo di attivare la verifica in due passaggi nelle impostazioni di Privacy e Sicurezza.\n\nGrazie,\nil team di Telegram %1$s ha aggiornato la foto del profilo Rispondi Rispondi a %1$s @@ -230,7 +235,7 @@ Avviso Anteprima messaggio Notifiche di gruppo - Suoni + Suono Notifiche in-app Suoni in-app Vibrazione in-app @@ -243,13 +248,13 @@ Utenti bloccati Disconnetti Nessun suono - Default + Predefinita Supporto Solo se silenzioso Sfondo chat Messaggi Spedisci con Invio - Chiudi tutte le altre sessioni + Termina le altre sessioni Eventi Un contatto ha iniziato a usare Telegram PEBBLE @@ -258,8 +263,8 @@ Chiedi a un volontario FAQ di Telegram https://telegram.org/faq/it - Eliminare la localizzazione? - File della localizzazione non valido + Eliminare la traduzione? + File di traduzione non valido Abilitate Disabilitata Servizio notifiche @@ -287,7 +292,7 @@ Salva nella galleria Modifica nome Priorità - Default + Predefinita Bassa Alta Massima @@ -305,14 +310,26 @@ Disabilitato No Suoni in-chat + Predefinito + + Sessioni attive + Sessione corrente + Nessun\'altra sessione attiva + Ti puoi connettere a Telegram da altri dispositivi mobili, tablet e desktop usando lo stesso numero. Tutti i tuoi dati saranno sincronizzati istantaneamente. + Sessioni attive + Controlla le tue sessioni sugli altri dispositivi. + Premi su una sessione per terminarla. + Terminare questa sessione? + app non ufficiale - Codice + Blocco con codice Cambia codice Quando imposti un codice, un\'icona col lucchetto apparirà nella pagina delle chat. Premi su di essa per bloccare e sbloccare l\'app.\n\nNota: se ti dimentichi il codice, dovrai disinstallare e reinstallare l\'app. Tutte le chat segrete verranno perse. Ora visualizzerai un\'icona col lucchetto nella pagina delle chat. Premi su di essa per bloccare la tua app Telegram con il codice. PIN Password Inserisci il tuo codice + Inserisci un codice Inserisci il nuovo codice Inserisci il tuo codice Reinserisci il nuovo codice @@ -372,29 +389,55 @@ Cancellare la cronologia di ricerca? Pulisci - Password - Change password - Old password - Enter old password - New password - Enter new password - Verify new password - Enter your password - Hint - Enter hint - Important: you will lose all your chats, messages and media in the case of a forgotten password. - Passwords do not match - Incorrect old password - Incorrect password - Incorrect new password - Hint shouldn\'t contain password - Enter password - Important: you will lose all your chats, messages and media. - Delete account - Delete my account - Hint: %1$s - Are you sure you want to delete your account? - We deeply clarify you that you will lose all your chats, messages and media. Are you really sure? + Verifica in due passaggi + Imposta password aggiuntiva + Puoi impostare una password che ti verrà richiesta quando ti connetti da un nuovo dispositivo in aggiunta al codice che riceverai via SMS. + La tua password + Inserisci la tua password + Inserisci una password + Inserisci la tua nuova password + Reinserisci la tua password + E-mail di recupero + La tua e-mail + Per favore inserisci un\'e-mail valida. È l\'unico modo di recuperare una password dimenticata. + Salta + Attenzione + No, seriamente.\n\nSe dimentichi la tua password, perderai l\'accesso al tuo account Telegram. Non ci sarà modo di ripristinarlo. + Ci siamo quasi! + Per favore controlla la tua e-mail (anche lo spam) per completare la configurazione della verifica in due passaggi. + Fatto! + La password per la verifica in due passaggi è ora attiva. + Cambia password + Disattiva password + Imposta e-mail di recupero + Cambia e-mail di recupero + Sei sicuro di voler disabilitare la tua password? + Suggerimento password + Per favore crea un suggerimento per la tua password + Le password non corrispondono + Annulla configurazione della verifica in due passaggi + Per favore segui questi step per completare la configurazione della verifica in due passaggi:\n\n1. Controlla la tua e-mail (anche lo spam)\n%1$s\n\n2. Clicca sul link di conferma. + Il suggerimento deve essere diverso dalla password + E-mail non valida + Scusa + Siccome non hai fornito un\'email di recupero quando hai impostato la tua password, non ti resta che ricordarti la password o ripristinare il tuo account. + Abbiamo inviato un codice di ripristino alla e-mail che ci hai fornito:\n\n%1$s + Per favore controlla la tua e-mail e inserisci il codice a 6 cifre che ti abbiamo inviato. + Hai problemi ad accedere alla tua e-mail %1$s? + Se non puoi ripristinare l\'accesso alla tua e-mail, non ti resta che ricordarti la password o ripristinare il tuo account. + RIPRISTINA IL MIO ACCOUNT + Perderai tutte le chat e i messaggi, insieme ai media e ai file condivisi, se procederai a ripristinare il tuo account. + Attenzione + Questa azione non può essere annullata.\n\n Se ripristini il tuo account, tutti i tuoi messaggi e chat saranno eliminati. + Ripristina + Password + Hai attivato la verifica in due passaggi, così il tuo account è protetto con una password aggiuntiva. + Password dimenticata? + Recupero password + Codice + Password disattivata + Hai attivato la verifica in due passaggi.\nAvrai bisogno della password che hai impostato per accedere al tuo account Telegram. + La tua e-mail di recupero %1$s non è ancora attiva e attende la conferma. Privacy e Sicurezza Privacy @@ -486,6 +529,7 @@ Numero di telefono non valido Codice scaduto, effettua di nuovo l\'accesso Troppi tentativi, riprova più tardi + Troppi tentativi, per favore riprova di nuova tra %1$s Codice non valido Nome non valido Cognome non valido @@ -499,7 +543,7 @@ Vuoi inoltrare i messaggi a %1$s? Inviare i messaggi a %1$s? Sei sicuro di volerti disconnettere?\n\nRicorda che puoi usare Telegram su tutti i tuoi device insieme.\n\nRicorda, disconnettersi elimina tutte le Chat Segrete. - Chiudere tutte le altre sessioni? + Terminare tutte le altre sessioni? Eliminare il gruppo e uscire da esso? Eliminare questa chat? Condividere le informazioni del proprio contatto? diff --git a/TMessagesProj/src/main/res/values-ko/strings.xml b/TMessagesProj/src/main/res/values-ko/strings.xml index c03fdfe2d..e4c80afb8 100644 --- a/TMessagesProj/src/main/res/values-ko/strings.xml +++ b/TMessagesProj/src/main/res/values-ko/strings.xml @@ -85,6 +85,10 @@ 입력 중... 님이 입력 중... 님이 입력 중... + %1$s님이 녹음 중... + %1$s님이 사진 보내는 중... + %1$s님이 동영상 보내는 중... + %1$s님이 파일 보내는 중... 텔레그램에 관해\n궁금한 사항이 있나요? 사진 촬영 앨범 @@ -117,6 +121,7 @@ 지원하지 않는 형식입니다 자동삭제 타이머 설정 서비스 알림 + 링크 정보를 가져오는 중... %1$s님이 자동삭제를 %2$s 후로 설정했습니다 자동삭제를 %1$s 후로 설정했습니다 @@ -150,7 +155,7 @@ %1$s님이 %2$s 그룹에서 추방했습니다 %1$s님이 %2$s 그룹을 떠났습니다 %1$s님이 텔레그램에 가입했습니다! - %1$s님,\n%2$s에 새 기기에서 회원님의 계정에 로그인하였습니다.\n\n기기: %3$s\n위치: %4$s\n\n본인의 접속이 아니라면 \'설정\'으로 가서 \'다른 모든 세션 종료\'를 실행하세요.\n\n감사합니다.\n텔레그램 팀 드림 + %1$s님,\n%2$s에 새 기기에서 회원님의 계정 로그인이 감지되었습니다. \n\n기기: %3$s\n위치: %4$s\n\n본인의 접속이 아니라면 \'설정\' 창에서 \'모든 세션 종료\' 기능을 실행하세요.\n\n만약 강제접속 의심이 되신다면 2단계 인증을 설정 - 개인정보 및 보안에서 설정할 수 있습니다.\n\n감사합니다.\n텔레그램 팀 %1$s님이 프로필 사진을 변경했습니다 답장 %1$s 그룹에 답장하기 @@ -245,7 +250,7 @@ 알림음 없음 기본값 지원 - Only if silent + 음소거일 중에만 채팅방 배경화면 메시지 엔터키로 메시지 전송 @@ -305,14 +310,26 @@ 비활성화됨 채팅중 소리 설정 + 기본값 + + 활성화된 세션 + 현재 세션 + 활성화된 세션이 없음 + 동일한 휴대번호로 다른 휴대기기,태블릿과 데스크탑에서 텔레그램 로그인이 가능합니다. 모든 데이터는 즉시 동기화 됩니다. + 활성화된 세션 + 다른 기기 세션 관리 + 탭하여 세션 종료 + 해당 세션을 종료하시겠습니까? + 비공식앱 - 잠금번호 + 잠금코드 잠금 잠금번호 변경 잠금코드를 설정하셨을 경우, 대화방에 잠금 아이콘이 표시됩니다. 해당 아이콘을 클릭하여 텔레그램 잠금 설정을 할 수 있습니다.\n\n주의: 잠금코드를 잊어버렸을 경우 앱 삭제후 재설치를 해주셔야합니다. 이 경우 비밀대화 내용은 삭제가 됩니다. 대화방에 잠금아이콘이 표시가 됩니다. 해당 아이콘을 클릭하여 새로운 잠금코드를 설정하여 텔레그램을 잠글수 있습니다. 핀코드 잠금번호 현재 잠금코드 입력 + 잠금코드 입력 새로운 잠금코드 입력 잠금코드를 입력해주세요 잠금코드 재입력 @@ -372,29 +389,55 @@ 검색기록을 지우시겠습니까? 지우기 - Password - Change password - Old password - Enter old password - New password - Enter new password - Verify new password - Enter your password - Hint - Enter hint - Important: you will lose all your chats, messages and media in the case of a forgotten password. - Passwords do not match - Incorrect old password - Incorrect password - Incorrect new password - Hint shouldn\'t contain password - Enter password - Important: you will lose all your chats, messages and media. - Delete account - Delete my account - Hint: %1$s - Are you sure you want to delete your account? - We deeply clarify you that you will lose all your chats, messages and media. Are you really sure? + 2단계 인증 + 개별 비밀번호 설정 + 새로운 기기에 로그인시 수신되는 SMS와는 별도로 개별 비밀번호를 설정 할 수 있습니다. + 비밀번호 + 비밀번호를 입력해주세요 + 비밀번호 입력 + 새로운 비밀번호 입력 + 비밀번호 재입력 + 복구 이메일 + 이메일 + 올바른 이메일을 입력해주세요. 비밀번호 분실시 유일하게 복구가 가능한 수단입니다. + 건너뛱 + 경고 + 비밀번호 분실시\n\n텔레그램에 대한 모든 접속 권한을 상실하시게 됩니다.\n비밀번호 분실시 복구는 불가능 합니다. + 거의 마무리 되었습니다! + 2단계 인증을 완료하시려면 이메일(스팸 폴더도 확인)을 확인해주세요. + 성공! + 2단계 인증 비밀번호가 활성화 되었습니다. + 비밀번호 변경 + 비밀번호 끄기 + 복구 이메일 설정 + 복구 이메일 변경 + 비밀번호를 정말로 삭제하시겠습니까? + 비밀번호 힌트 + 비밀번호 힌트를 생성해주세요 + 비밀번호가 정확하지 않습니다. + 2단계 인증 설정 끝내기 + 2단계 인증 설정을 완료하시려면 아래의 절차대로 진행해주세요:\n\n1.이메일 확인(스팸 폴더 확인)\n%1$s\n\n2.인증 링크 클릭 + 힌트는 비밀번호와 다르게 설정해주세요. + 올바르지 않은 이메일 + 죄송합니다. + 비밀번호 복구 이메일을 설정하지 않았기때문에, 비밀번호를 기억해내시거나 계정 초기화를 진행해주셔야합니다. + 다음 복구 이메일 주소로 복구 코드를 전송하였습니다:\n\n%1$s + 이메일을 확인하여 수신받은 6자리 코드를 입력해주세요. + 이메일 %1$s 접근에 문제가 있으신가요? + 이메일 접근을 하실 수 없을 경우, 비밀번호를 기억해내시거나 계정 초기화를 진행해주셔야 합니다. + 계정 초기화 + 계정 초기화 진행시 모든 대화,메시지 및 공유받은 미디어와 파일이 삭제가 됩니다. + 경고 + 진행하실 경우 취소가 불가능합니다.\n\n계정 초기화 진행시 모든 대화 및 메시지가 삭제됩니다. + 초기화 + 비밀번호 + 2단계 인증이 활성화되어 회원님 계정이 개별 비밀번호로 보안됩니다. + 비밀번호를 잊어버리셨나요? + 비밀번호 복구 + 코드 + 비밀번호 비활성화 + 2단계 인증을 활성화 하였습니다.\n설정된 개별 비밀번호를 사용하여 텔레그램 계정에 로그인 할 수 있습니다. + 복구 이메일 %1$s 이 아직 활성화 되지 않았으며 미승인 상태입니다. 개인정보 및 보안 개인정보 @@ -486,6 +529,7 @@ 올바른 전화번호를 입력해 주세요 코드가 만료되었습니다. 다시 로그인하세요 너무 많이 시도하셨습니다. 나중에 다시 시도하세요 + 너무 많이 시도하셨습니다. %1$s 초 후에 다시 시도하세요. 올바른 코드를 입력해 주세요 올바른 이름을 입력해 주세요 올바른 성을 입력해 주세요 diff --git a/TMessagesProj/src/main/res/values-nl/strings.xml b/TMessagesProj/src/main/res/values-nl/strings.xml index 2a05283ae..d652346b1 100644 --- a/TMessagesProj/src/main/res/values-nl/strings.xml +++ b/TMessagesProj/src/main/res/values-nl/strings.xml @@ -85,6 +85,10 @@ aan het typen is aan het typen zijn aan het typen + %1$s neemt geluid op + %1$s verstuurt een foto + %1$s verstuurt een video + %1$s verstuurt een bestand Heb je een vraag\nover Telegram? Foto maken Galerij @@ -117,6 +121,7 @@ Bestandstype niet ondersteund Zelfvernietigingstimer instellen Servicemeldingen + Link-preview ophalen... %1$s heeft de zelfvernietigingstimer ingesteld op %2$s Je hebt de zelfvernietigingstimer ingesteld op %1$s @@ -150,7 +155,7 @@ %1$s heeft je verwijderd uit de groep %2$s %1$s heeft de groep %2$s verlaten %1$s heeft nu Telegram! - %1$s,\nEr is op je account ingelogd vanaf een nieuw apparaat op %2$s\n\nApparaat: %3$s\nLocatie: %4$s\n\nAls jij dit niet was, kun je alle sessies beëindigen via Instellingen - Privacy en veiligheid - Beëindig alle andere sessies.\n\nBedankt,\nHet Telegram-team + %1$s,\nEr is op je account ingelogd vanaf een nieuw apparaat op %2$s\n\nApparaat: %3$s\nLocatie: %4$s\n\nAls jij dit niet was, kun je die sessie beëindigen via Instellingen - Privacy en veiligheid - Sessies.\n\nAls je dat denkt dat iemand anders zonder jouw toestemming is ingelogd kun je twee-staps-verificatie activeren via instellingen - privacy en veiligheid .\n\nBedankt,\nHet Telegram-team %1$s heeft zijn/haar profielfoto gewijzigd Antwoord Antwoord op %1$s @@ -305,14 +310,26 @@ Uitgeschakeld Uit Chatgeluiden + Standaard + + Actieve sessies + Huidige sessie + Geen andere actieve sessies + Je kunt in Telegram inloggen vanaf andere apparaten (mobiel,tablet,desktop) met hetzelfde telefoonnummer. Al je data zal direct worden gesynchroniseerd. + Actieve sessies + Beheer je sessies van andere apparaten. + Tik op een sessie om deze te beëindigen. + Deze sessie beëindigen? + onofficiële app - Toegangscode + Toegangscode-vergrendeling Toegangscode wijzigen Als je een toegangscode instelt verschijnt er een slotje op de chatspagina. Tik erop om Telegram te vergrendelen of te ontgrendelen.\n\nLet op: vergeet je de toegangscode dan zul je de app moeten verwijderen en herinstalleren. Alle geheime chats gaan daarbij verloren. Je zult nu een slotje op de chatspagina zien. Tik erop om Telegram te vergrendelen met je nieuwe toegangscode. PIN Wachtwoord Huidige toegangscode invoeren + Toegangscode invoeren Nieuwe toegangscode invoeren Toegangscode invoeren Toegangscode opnieuw invoeren @@ -372,29 +389,55 @@ Zoekgeschiedenis wissen? Wissen - Password - Change password - Old password - Enter old password - New password - Enter new password - Verify new password - Enter your password - Hint - Enter hint - Important: you will lose all your chats, messages and media in the case of a forgotten password. - Passwords do not match - Incorrect old password - Incorrect password - Incorrect new password - Hint shouldn\'t contain password - Enter password - Important: you will lose all your chats, messages and media. - Delete account - Delete my account - Hint: %1$s - Are you sure you want to delete your account? - We deeply clarify you that you will lose all your chats, messages and media. Are you really sure? + Twee-staps-verificatie + Extra wachtwoord instellen + Naast de code die je per SMS ontvangt kun je een extra wachtwoord instellen voor als je inlogt op een nieuw apparaat. + Je wachtwoord + Wachtwoord invoeren + Wachtwoord invoeren + Nieuw wachtwoord invoeren + Wachtwoord opnieuw invoeren + Herstel-e-mailadres + Je e-mailadres + Voeg je geldige e-mailadres toe. Het is de enige manier om je wachtwoord te herstellen. + Overslaan + Waarschuwing + Let op:\n\nAls je je wachtwoord vergeet verlies je toegang tot je Telegram-account. Er is geen optie om dit te herstellen. + Bijna klaar! + Controleer je e-mail en klik op de bevestigingslink om de twee-staps-verificatie in te schakelen. Kijk voor de zekerheid ook in de ongewenste post. + Gelukt! + Je wachtwoord voor twee-staps-verificatie is nu actief. + Wachtwoord wijzigen + Wachtwoord uitschakelen + Herstel-e-mailadres instellen + Herstel-e-mailadres wijzigen + Weet je zeker dat je je wachtwoord wilt uitschakelen? + Wachtwoordhint + Stel een hint voor je wachtwoord in + Wachtwoorden komen niet overeen + Twee-staps-verificatie annuleren + Volg deze stappen om twee-staps-verificatie in te schakelen:\n\n1.Controleer je e-mail (kijk voor de zekerheid ook in de ongewenste post)\n%1$s\n\n2.n klik op de bevestigingslink. + De hint moet anders zijn dan je wachtwoord + Ongeldig e-mailadres + Sorry + Omdat je geen herstel-e-mailadres hebt opgegeven voor je wachtwoord zul je bij verlies van je wachtwoord je account moeten resetten. + We hebben een herstelcode naar je opgegeven e-mailadres gestuurd:\n\n%1$s + Controleer je e-mail en geef de 6-cijferige code in die we je hebben gestuurd. + Kun je je e-mail niet benaderen %1$s? + Bij verlies van je wachtwoord zul je je account moeten resetten. + ACCOUNT RESETTEN + Al je chats, berichten en alle andere data gaan verloren als je verder gaat met de account-reset. + Waarschuwing + Deze actie kan niet worden hersteld.\n\nAl je chats, berichten en data gaan verloren als je je account reset. + Resetten + Wachtwoord + Twee-staps-verificatie ingeschakeld. Je account is met een extra wachtwoord beveiligd. + Wachtwoord vergeten? + Wachtwoordherstel + Code + Wachtwoord uitgeschakeld + Je hebt twee-staps-verificatie ingeschakeld.\nAls je inlogt op je Telegram-account heb je het ingestelde wachtwoord nodig. + Je herstel-e-mailadres %1$s is nog niet actief en in afwachting van bevestiging. Privacy en veiligheid Privacy @@ -486,12 +529,13 @@ Ongeldig telefoonnummer Code verlopen. Log opnieuw in. Te veel pogingen. Probeer het later opnieuw. + Te veel pogingen, probeer het over %1$s opnieuw Ongeldige code Ongeldige voornaam Ongeldige achternaam Bezig met laden Je hebt geen mediaspeler. Installeer een mediaspeler om door te gaan. - Mail ons op sms@stel.com en vertel ons over je probleem. + E-mail ons op sms@stel.com en vertel ons over je probleem. Je hebt geen apps die bestandstype \'%1$s\' kunnen verwerken, gelieve een compatibele app te installeren Deze gebruiker heeft nog geen Telegram. Wil je een uitnodiging sturen? Weet je het zeker? diff --git a/TMessagesProj/src/main/res/values-pt-rBR/strings.xml b/TMessagesProj/src/main/res/values-pt-rBR/strings.xml index b75938aa3..b0d1b594a 100644 --- a/TMessagesProj/src/main/res/values-pt-rBR/strings.xml +++ b/TMessagesProj/src/main/res/values-pt-rBR/strings.xml @@ -85,6 +85,10 @@ escrevendo... está escrevendo... estão escrevendo... + %1$s está gravando uma mensagem... + %1$s está enviando uma foto... + %1$s está enviando um vídeo... + %1$s está enviando um arquivo... Tem alguma dúvida\nsobre o Telegram? Tirar foto Galeria @@ -117,6 +121,7 @@ Anexo não suportado Definir timer de autodestruição Notificações de serviço + Obtendo informações... %1$s estabeleceu o tempo de autodestruição para %2$s Você estabeleceu o tempo de autodestruição para %1$s @@ -150,7 +155,7 @@ %1$s removeu você do grupo %2$s %1$s saiu do grupo %2$s %1$s entrou para o Telegram! - %1$s,\nDetectamos um acesso à sua conta de um novo dispositivo em %2$s\n\nDispositivo: %3$s\nLocalização: %4$s\n\nCaso não tenha sido você, vá em Configurações – Privacidade e Segurança – Terminar todas as outras sessões.\n\nObrigado,\nEquipe Telegram + %1$s,\nNós detectamos que alguém acessou a sua conta a partir de um novo aparelho em %2$s\n\nAparelho: %3$s\nLocalização: %4$s\n\nSe não foi você, você pode ir em Configurações - Provacidade e Segurança - Sessões, e terminar aquela sessão.\n\nSe você acha que alguém acessou a sua conta contra a sua vontade, você pode habilitar a verificação em duas etapas nas configurações de Privacidade e Segurança.\n\nAtenciosamente,\nEquipe Telegram %1$s atualizou a foto do perfil Responder Responder para %1$s @@ -245,7 +250,7 @@ Sem som Padrão Suporte - Only if silent + Somente no silencioso Papel de Parede Mensagens Enviar usando \'Enter\' @@ -305,14 +310,26 @@ Desativado Desativado Sons no Chat + Padrão + + Sessões Ativas + Sessão atual + Nenhuma outra sessão ativa + Você pode entrar no Telegram a partir de outro celular, tablet ou computador usando o mesmo número de telefone. Todos os seus dados serão sincronizados instantaneamente. + Sessões Ativas + Controle suas sessões em outros aparelho. + Toque em uma sessão para terminá-la. + Encerrar essa sessão? + aplicativo não oficial - Senha + Senha de Bloqueio Alterar Senha Quando você define uma senha adicional, um ícone de cadeado aparece na página de chats. Clique para bloquear e desbloquear o app.\n\nNota: se você esquecer a sua senha, terá de excluir e reinstalar o app. Todos os chats secretos serão perdidos. Você verá o ícone do cadeado na página de chats. Clique para bloquear seu app do Telegram com a sua nova senha. PIN Senha Insira sua senha atual + Insira uma senha Insira sua nova senha Insira sua senha Re-insira sua nova senha @@ -372,29 +389,55 @@ Limpar histórico de busca? Limpar - Password - Change password - Old password - Enter old password - New password - Enter new password - Verify new password - Enter your password - Hint - Enter hint - Important: you will lose all your chats, messages and media in the case of a forgotten password. - Passwords do not match - Incorrect old password - Incorrect password - Incorrect new password - Hint shouldn\'t contain password - Enter password - Important: you will lose all your chats, messages and media. - Delete account - Delete my account - Hint: %1$s - Are you sure you want to delete your account? - We deeply clarify you that you will lose all your chats, messages and media. Are you really sure? + Verificação em duas etapas + Configurar senha adicional + Você pode configurar uma senha que será requisitada quando você entrar em um novo aparelho, além do código que você receberá por SMS. + Sua senha + Por favor, digite a sua senha + Insira uma senha + Por favor, digite a sua nova senha + Por favor, digite sua senha novamente + E-mail de recuperação + Seu e-mail + Por favor, adicione um e-mail válido. Essa é a única forma de recuperar uma senha esquecida. + Pular + Atenção + É sério!\n\nSe você esquecer a sua senha, você perderá o acesso a sua conta do Telegram. Não há nenhuma forma de recuperá-la. + Quase lá! + Por favor, verifique o seu e-mail (não esqueça da pasta spam) para completar a configuração da verificação em duas etapas. + Pronto! + A sua senha para a verificação em duas etapas foi ativada. + Alterar senha + Desabilitar senha + Configurar e-mail de recuperação + Alterar e-mail de recuperação. + Você tem certeza que quer desabilitar a sua senha? + Dica da senha + Por favor, crie uma dica para a sua senha + As senhas não são iguais + Cancelar a configuração da verificação em duas etapas + Por favor, siga os seguintes passos para completar a configuração da autenticação em duas etapas:\n\n1. Verifique seu e-mail ( não esqueça da pasta spam)\n%1$s\n\n2. Clique no link de validação. + A dica deve ser diferente da sua senha + E-mail inválido + Desculpe + Como você não indicou um e-mail de recuperação quando configurou a sua senha, as únicas opções restantes são lembrar a senha ou apagar a sua conta. + O código de recuperação foi enviado para o e-mail fornecido: \n\n%1$s + Por favor, verifique o seu e-mail e digite aqui o código de 6 dígitos recebido. + Está tendo problemas para acessar seu e-mail %1$s? + Se você não puder acessar o seu e-mail, as suas únicas opções são são lembrar a senha ou apagar a sua conta. + APAGAR MINHA CONTA + Se você prosseguir e apagar a sua conta, você perderá todos os seus chats e mensagens, assim como todas as suas mídias e arquivos compartilhados. + Aviso + Essa ação não pode ser revertida ou desfeita.\n\nSe você apagar a sua conta, todas as suas mensagens e chats serão apagados. + Apagar + Senha + Você habilitou a verificação em duas etapas, a sua conta está protegida com uma senha adicional. + Esqueceu a senha? + Recuperação de senha + Código + Senha desativada + Você habilitou a verificação em duas etapas. Toda vez que você entrar na sua conta em um novo aparelho, será preciso digitar a senha que você configurar aqui. + O seu e-mail de recuperação %1$s ainda não está ativo e aguarda confirmação. Privacidade e Segurança Privacidade @@ -486,6 +529,7 @@ Número de telefone inválido O código expirou. Por favor, identifique-se novamente. Muitas tentativas. Por favor, tente novamente mais tarde. + Muitas tentativas, por favor tente novamente em %1$s Código inválido Nome inválido Sobrenome inválido diff --git a/TMessagesProj/src/main/res/values-pt-rPT/strings.xml b/TMessagesProj/src/main/res/values-pt-rPT/strings.xml index 35568de2d..dd6aca2f4 100644 --- a/TMessagesProj/src/main/res/values-pt-rPT/strings.xml +++ b/TMessagesProj/src/main/res/values-pt-rPT/strings.xml @@ -85,6 +85,10 @@ escrevendo... está escrevendo... estão escrevendo... + %1$s está gravando uma mensagem... + %1$s está enviando uma foto... + %1$s está enviando um vídeo... + %1$s está enviando um arquivo... Tem alguma dúvida\nsobre o Telegram? Tirar foto Galeria @@ -117,6 +121,7 @@ Anexo não suportado Definir timer de autodestruição Notificações de serviço + Obtendo informações... %1$s estabeleceu o tempo de autodestruição para %2$s Você estabeleceu o tempo de autodestruição para %1$s @@ -150,7 +155,7 @@ %1$s removeu você do grupo %2$s %1$s saiu do grupo %2$s %1$s entrou para o Telegram! - %1$s,\nDetectamos um acesso à sua conta de um novo dispositivo em %2$s\n\nDispositivo: %3$s\nLocalização: %4$s\n\nCaso não tenha sido você, vá em Configurações – Privacidade e Segurança – Terminar todas as outras sessões.\n\nObrigado,\nEquipe Telegram + %1$s,\nNós detectamos que alguém acessou a sua conta a partir de um novo aparelho em %2$s\n\nAparelho: %3$s\nLocalização: %4$s\n\nSe não foi você, você pode ir em Configurações - Provacidade e Segurança - Sessões, e terminar aquela sessão.\n\nSe você acha que alguém acessou a sua conta contra a sua vontade, você pode habilitar a verificação em duas etapas nas configurações de Privacidade e Segurança.\n\nAtenciosamente,\nEquipe Telegram %1$s atualizou a foto do perfil Responder Responder para %1$s @@ -245,7 +250,7 @@ Sem som Padrão Suporte - Only if silent + Somente no silencioso Papel de Parede Mensagens Enviar usando \'Enter\' @@ -305,14 +310,26 @@ Desativado Desativado Sons no Chat + Padrão + + Sessões Ativas + Sessão atual + Nenhuma outra sessão ativa + Você pode entrar no Telegram a partir de outro celular, tablet ou computador usando o mesmo número de telefone. Todos os seus dados serão sincronizados instantaneamente. + Sessões Ativas + Controle suas sessões em outros aparelho. + Toque em uma sessão para terminá-la. + Encerrar essa sessão? + aplicativo não oficial - Senha + Senha de Bloqueio Alterar Senha Quando você define uma senha adicional, um ícone de cadeado aparece na página de chats. Clique para bloquear e desbloquear o app.\n\nNota: se você esquecer a sua senha, terá de excluir e reinstalar o app. Todos os chats secretos serão perdidos. Você verá o ícone do cadeado na página de chats. Clique para bloquear seu app do Telegram com a sua nova senha. PIN Senha Insira sua senha atual + Insira uma senha Insira sua nova senha Insira sua senha Re-insira sua nova senha @@ -372,29 +389,55 @@ Limpar histórico de busca? Limpar - Password - Change password - Old password - Enter old password - New password - Enter new password - Verify new password - Enter your password - Hint - Enter hint - Important: you will lose all your chats, messages and media in the case of a forgotten password. - Passwords do not match - Incorrect old password - Incorrect password - Incorrect new password - Hint shouldn\'t contain password - Enter password - Important: you will lose all your chats, messages and media. - Delete account - Delete my account - Hint: %1$s - Are you sure you want to delete your account? - We deeply clarify you that you will lose all your chats, messages and media. Are you really sure? + Verificação em duas etapas + Configurar senha adicional + Você pode configurar uma senha que será requisitada quando você entrar em um novo aparelho, além do código que você receberá por SMS. + Sua senha + Por favor, digite a sua senha + Insira uma senha + Por favor, digite a sua nova senha + Por favor, digite sua senha novamente + E-mail de recuperação + Seu e-mail + Por favor, adicione um e-mail válido. Essa é a única forma de recuperar uma senha esquecida. + Pular + Atenção + É sério!\n\nSe você esquecer a sua senha, você perderá o acesso a sua conta do Telegram. Não há nenhuma forma de recuperá-la. + Quase lá! + Por favor, verifique o seu e-mail (não esqueça da pasta spam) para completar a configuração da verificação em duas etapas. + Pronto! + A sua senha para a verificação em duas etapas foi ativada. + Alterar senha + Desabilitar senha + Configurar e-mail de recuperação + Alterar e-mail de recuperação. + Você tem certeza que quer desabilitar a sua senha? + Dica da senha + Por favor, crie uma dica para a sua senha + As senhas não são iguais + Cancelar a configuração da verificação em duas etapas + Por favor, siga os seguintes passos para completar a configuração da autenticação em duas etapas:\n\n1. Verifique seu e-mail ( não esqueça da pasta spam)\n%1$s\n\n2. Clique no link de validação. + A dica deve ser diferente da sua senha + E-mail inválido + Desculpe + Como você não indicou um e-mail de recuperação quando configurou a sua senha, as únicas opções restantes são lembrar a senha ou apagar a sua conta. + O código de recuperação foi enviado para o e-mail fornecido: \n\n%1$s + Por favor, verifique o seu e-mail e digite aqui o código de 6 dígitos recebido. + Está tendo problemas para acessar seu e-mail %1$s? + Se você não puder acessar o seu e-mail, as suas únicas opções são são lembrar a senha ou apagar a sua conta. + APAGAR MINHA CONTA + Se você prosseguir e apagar a sua conta, você perderá todos os seus chats e mensagens, assim como todas as suas mídias e arquivos compartilhados. + Aviso + Essa ação não pode ser revertida ou desfeita.\n\nSe você apagar a sua conta, todas as suas mensagens e chats serão apagados. + Apagar + Senha + Você habilitou a verificação em duas etapas, a sua conta está protegida com uma senha adicional. + Esqueceu a senha? + Recuperação de senha + Código + Senha desativada + Você habilitou a verificação em duas etapas. Toda vez que você entrar na sua conta em um novo aparelho, será preciso digitar a senha que você configurar aqui. + O seu e-mail de recuperação %1$s ainda não está ativo e aguarda confirmação. Privacidade e Segurança Privacidade @@ -486,6 +529,7 @@ Número de telefone inválido O código expirou. Por favor, identifique-se novamente. Muitas tentativas. Por favor, tente novamente mais tarde. + Muitas tentativas, por favor tente novamente em %1$s Código inválido Nome inválido Sobrenome inválido diff --git a/TMessagesProj/src/main/res/values/strings.xml b/TMessagesProj/src/main/res/values/strings.xml index d5e073006..847bff777 100644 --- a/TMessagesProj/src/main/res/values/strings.xml +++ b/TMessagesProj/src/main/res/values/strings.xml @@ -85,6 +85,10 @@ typing... is typing... are typing... + %1$s is recording audio... + %1$s is sending photo... + %1$s is sending video... + %1$s is sending file... Got a question\nabout Telegram? Take photo Gallery @@ -117,6 +121,7 @@ Unsupported attachment Set self-destruct timer Service notifications + Getting Link Info... %1$s set the self-destruct timer to %2$s You set the self-destruct timer to %1$s @@ -150,7 +155,7 @@ %1$s removed you from the group %2$s %1$s has left the group %2$s %1$s joined Telegram! - %1$s,\nWe detected a login into your account from a new device on %2$s\n\nDevice: %3$s\nLocation: %4$s\n\nIf this wasn\'t you, you can go to Settings - Privacy and Security - Terminate all other sessions.\n\nSincerely,\nThe Telegram Team + %1$s,\nWe detected a login into your account from a new device on %2$s\n\nDevice: %3$s\nLocation: %4$s\n\nIf this wasn\'t you, you can go to Settings - Privacy and Security - Sessions and terminate that session.\n\nIf you think that somebody logged in to your account against your will, you can enable two-step verification in Privacy and Security settings.\n\nSincerely,\nThe Telegram Team %1$s updated profile photo Reply Reply to %1$s @@ -305,14 +310,26 @@ Disabled Off In-Chat Sounds + Default + + Active Sessions + Current session + No other active sessions + You can log in to Telegram from other mobile, tablet and desktop devices, using the same phone number. All your data will be instantly synchronized. + Active Sessions + Control your sessions on other devices. + Tap on a session to terminate. + Terminate this session? + unofficial app - Passcode + Passcode Lock Change Passcode When you set up an additional passcode, a lock icon will appear on the chats page. Tap it to lock and unlock your Telegram app.\n\nNote: if you forget the passcode, you\'ll need to delete and reinstall the app. All secret chats will be lost. You will now see a lock icon on the chats page. Tap it to lock your Telegram app with your new passcode. PIN Password Enter your current passcode + Enter a passcode Enter your new passcode Enter your passcode Re-enter your new passcode @@ -372,29 +389,55 @@ Clear search history? Clear - Password - Change password - Old password - Enter old password - New password - Enter new password - Verify new password - Enter your password - Hint - Enter hint - Important: you will lose all your chats, messages and media in the case of a forgotten password. + Two-Step Verification + Set Additional Password + You can set a password that will be required when you log in on a new device in addition to the code you get in the SMS. + Your Password + Please enter your password + Enter a password + Please enter your new password + Please re-enter your password + Recovery E-Mail + Your E-Mail + Please add your valid e-mail. It is the only way to recover a forgotten password. + Skip + Warning + No, seriously.\n\nIf you forget your password, you will lose access to your Telegram account. There will be no way to restore it. + Almost there! + Please check your e-mail (don\'t forget the spam folder) to complete Two-Step Verification setup. + Success! + Your password for Two-Step Verification is now active. + Change Password + Turn Password Off + Set Recovery E-Mail + Change Recovery E-Mail + Are you sure you want to disable your password? + Password Hint + Please create a hint for your password Passwords do not match - Incorrect old password - Incorrect password - Incorrect new password - Hint shouldn\'t contain password - Enter password - Important: you will lose all your chats, messages and media. - Delete account - Delete my account - Hint: %1$s - Are you sure you want to delete your account? - We deeply clarify you that you will lose all your chats, messages and media. Are you really sure? + Abort two-step verification setup + Please follow these steps to complete Two-Step Verification Setup:\n\n1. Check your e-mail (don\'t forget the spam folder)\n%1$s\n\n2. Click on the validation link. + Hint must be different from your password + Invalid e-mail + Sorry + Since you haven\'t provided a recovery e-mail when setting up your password, your remaining options are either to remember your password or to reset your account. + We have sent a recovery code to the e-mail you provided:\n\n%1$s + Please check your e-mail and enter the 6-digit code we have sent here. + Having trouble accessing your e-mail %1$s? + If you can\'t restore access to your e-mail, your remaining options are either to remember your password or to reset your account. + RESET MY ACCOUNT + You will lose all your chats and messages, along with any media and files you shared, if you proceed with resetting your account. + Warning + This action can not be undone.\n\nIf you reset your account, all your messages and chats will be deleted. + Reset + Password + You have enabled Two-Step Verification, so your account is protected with an additional password. + Forgot password? + Password Recovery + Code + Password deactivated + You have enabled Two-Step verification.\nYou\'ll need the password you set up here to log in to your Telegram account. + Your recovery e-mail %1$s is not yet active and pending confirmation. Privacy and Security Privacy @@ -486,6 +529,7 @@ Invalid phone number Code expired, please login again Too many attempts, please try again later + Too many attempts, please try again in %1$s Invalid code Invalid first name Invalid last name