1
0
mirror of https://github.com/MGislv/NekoX.git synced 2024-06-30 22:22:57 +00:00

Update to 2.5.0

Photo editor
Passcode
Sections in shared media\files
This commit is contained in:
DrKLO 2015-02-26 04:32:51 +03:00
parent dff666fca1
commit 93fa5019c3
310 changed files with 10186 additions and 4632 deletions

View File

@ -3,7 +3,7 @@ buildscript {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.0.0'
classpath 'com.android.tools.build:gradle:1.1.0'
}
}
apply plugin: 'com.android.application'
@ -82,7 +82,7 @@ android {
defaultConfig {
minSdkVersion 8
targetSdkVersion 21
versionCode 423
versionName "2.4.0"
versionCode 453
versionName "2.5.0"
}
}

View File

@ -104,7 +104,7 @@ include $(BUILD_STATIC_LIBRARY)
include $(CLEAR_VARS)
LOCAL_PRELINK_MODULE := false
LOCAL_STATIC_LIBRARIES := webp sqlite
LOCAL_MODULE := tmessages.5
LOCAL_MODULE := tmessages.6
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

View File

@ -21,6 +21,9 @@ jmethodID jclass_Bitmap_createBitmap;
jclass jclass_Config;
jfieldID jclass_Config_ARGB_8888;
const uint32_t PGPhotoEnhanceHistogramBins = 256;
const uint32_t PGPhotoEnhanceSegments = 4;
jclass createGlobarRef(JNIEnv *env, jclass class) {
if (class) {
return (*env)->NewGlobalRef(env, class);
@ -312,6 +315,110 @@ JNIEXPORT void Java_org_telegram_messenger_Utilities_blurBitmap(JNIEnv *env, jcl
AndroidBitmap_unlockPixels(env, bitmap);
}
JNIEXPORT void Java_org_telegram_messenger_Utilities_calcCDT(JNIEnv *env, jclass class, jobject hsvBuffer, int width, int height, jobject buffer) {
float imageWidth = width;
float imageHeight = height;
float _clipLimit = 1.25f;
uint32_t totalSegments = PGPhotoEnhanceSegments * PGPhotoEnhanceSegments;
uint32_t tileArea = (uint32_t)(floorf(imageWidth / PGPhotoEnhanceSegments) * floorf(imageHeight / PGPhotoEnhanceSegments));
uint32_t clipLimit = (uint32_t)max(1, _clipLimit * tileArea / (float) PGPhotoEnhanceHistogramBins);
float scale = 255.0f / (float) tileArea;
unsigned char *bytes = (*env)->GetDirectBufferAddress(env, hsvBuffer);
uint32_t **hist = calloc(totalSegments, sizeof(uint32_t *));
uint32_t **cdfs = calloc(totalSegments, sizeof(uint32_t *));
uint32_t *cdfsMin = calloc(totalSegments, sizeof(uint32_t));
uint32_t *cdfsMax = calloc(totalSegments, sizeof(uint32_t));
for (uint32_t a = 0; a < totalSegments; a++) {
hist[a] = calloc(PGPhotoEnhanceHistogramBins, sizeof(uint32_t));
cdfs[a] = calloc(PGPhotoEnhanceHistogramBins, sizeof(uint32_t));
}
float xMul = PGPhotoEnhanceSegments / imageWidth;
float yMul = PGPhotoEnhanceSegments / imageHeight;
for (uint32_t y = 0; y < imageHeight; y++) {
uint32_t yOffset = y * width * 4;
for (uint32_t x = 0; x < imageWidth; x++) {
uint32_t index = x * 4 + yOffset;
uint32_t tx = (uint32_t)(x * xMul);
uint32_t ty = (uint32_t)(y * yMul);
uint32_t t = ty * PGPhotoEnhanceSegments + tx;
hist[t][bytes[index + 2]]++;
}
}
for (uint32_t i = 0; i < totalSegments; i++) {
if (clipLimit > 0) {
uint32_t clipped = 0;
for (uint32_t j = 0; j < PGPhotoEnhanceHistogramBins; ++j) {
if (hist[i][j] > clipLimit) {
clipped += hist[i][j] - clipLimit;
hist[i][j] = clipLimit;
}
}
uint32_t redistBatch = clipped / PGPhotoEnhanceHistogramBins;
uint32_t residual = clipped - redistBatch * PGPhotoEnhanceHistogramBins;
for (uint32_t j = 0; j < PGPhotoEnhanceHistogramBins; ++j) {
hist[i][j] += redistBatch;
}
for (uint32_t j = 0; j < residual; ++j) {
hist[i][j]++;
}
}
memcpy(cdfs[i], hist[i], PGPhotoEnhanceHistogramBins * sizeof(uint32_t));
uint32_t hMin = PGPhotoEnhanceHistogramBins - 1;
for (uint32_t j = 0; j < hMin; ++j) {
if (cdfs[j] != 0) {
hMin = j;
}
}
uint32_t cdf = 0;
for (uint32_t j = hMin; j < PGPhotoEnhanceHistogramBins; ++j) {
cdf += cdfs[i][j];
cdfs[i][j] = (uint8_t) min(255, cdf * scale);
}
cdfsMin[i] = cdfs[i][hMin];
cdfsMax[i] = cdfs[i][PGPhotoEnhanceHistogramBins - 1];
}
uint32_t resultSize = 4 * PGPhotoEnhanceHistogramBins * totalSegments;
uint32_t resultBytesPerRow = 4 * PGPhotoEnhanceHistogramBins;
unsigned char *result = (*env)->GetDirectBufferAddress(env, buffer);
for (uint32_t tile = 0; tile < totalSegments; tile++) {
uint32_t yOffset = tile * resultBytesPerRow;
for (uint32_t i = 0; i < PGPhotoEnhanceHistogramBins; i++) {
uint32_t index = i * 4 + yOffset;
result[index] = (uint8_t)cdfs[tile][i];
result[index + 1] = (uint8_t)cdfsMin[tile];
result[index + 2] = (uint8_t)cdfsMax[tile];
result[index + 3] = 255;
}
}
for (uint32_t a = 0; a < totalSegments; a++) {
free(hist[a]);
free(cdfs[a]);
}
free(hist);
free(cdfs);
free(cdfsMax);
free(cdfsMin);
}
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;

View File

@ -23,6 +23,7 @@ import android.os.Environment;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.util.DisplayMetrics;
import android.util.StateSet;
import android.view.Display;
import android.view.Surface;
@ -33,12 +34,16 @@ import android.widget.AbsListView;
import android.widget.EdgeEffect;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.R;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.UserConfig;
import org.telegram.ui.Components.ForegroundDetector;
import org.telegram.ui.Components.NumberPicker;
import org.telegram.ui.Components.TypefaceSpan;
@ -59,6 +64,7 @@ public class AndroidUtilities {
public static float density = 1;
public static Point displaySize = new Point();
public static Integer photoSize = null;
public static DisplayMetrics displayMetrics = new DisplayMetrics();
private static Boolean isTablet = null;
static {
@ -67,7 +73,7 @@ public class AndroidUtilities {
}
public static void lockOrientation(Activity activity) {
if (activity == null || prevOrientation != -10) {
if (activity == null || prevOrientation != -10 || Build.VERSION.SDK_INT < 9) {
return;
}
try {
@ -115,7 +121,7 @@ public class AndroidUtilities {
}
public static void unlockOrientation(Activity activity) {
if (activity == null) {
if (activity == null || Build.VERSION.SDK_INT < 9) {
return;
}
try {
@ -228,12 +234,13 @@ public class AndroidUtilities {
if (manager != null) {
Display display = manager.getDefaultDisplay();
if (display != null) {
display.getMetrics(displayMetrics);
if(android.os.Build.VERSION.SDK_INT < 13) {
displaySize.set(display.getWidth(), display.getHeight());
} else {
display.getSize(displaySize);
}
FileLog.e("tmessages", "display size = " + displaySize.x + " " + displaySize.y);
FileLog.e("tmessages", "display size = " + displaySize.x + " " + displaySize.y + " " + displayMetrics.xdpi + "x" + displayMetrics.ydpi);
}
}
} catch (Exception e) {
@ -241,6 +248,10 @@ public class AndroidUtilities {
}
}
public static float getPixelsInCM(float cm, boolean isX) {
return (cm / 2.54f) * (isX ? displayMetrics.xdpi : displayMetrics.ydpi);
}
public static long makeBroadcastId(int id) {
return 0x0000000100000000L | ((long)id & 0x00000000FFFFFFFFL);
}
@ -421,6 +432,19 @@ public class AndroidUtilities {
}
}
public static void setProgressBarAnimationDuration(ProgressBar progressBar, int duration) {
if (progressBar == null) {
return;
}
try {
Field mCursorDrawableRes = ProgressBar.class.getDeclaredField("mDuration");
mCursorDrawableRes.setAccessible(true);
mCursorDrawableRes.setInt(progressBar, duration);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
public static int getViewInset(View view) {
if (view == null || Build.VERSION.SDK_INT < 21) {
return 0;
@ -530,4 +554,18 @@ public class AndroidUtilities {
}
return stringBuilder;
}
public static boolean needShowPasscode(boolean reset) {
boolean wasInBackground;
if (Build.VERSION.SDK_INT >= 14) {
wasInBackground = ForegroundDetector.getInstance().isWasInBackground(reset);
if (reset) {
ForegroundDetector.getInstance().resetBackgroundVar();
}
} else {
wasInBackground = UserConfig.lastPauseTime != 0;
}
return UserConfig.passcodeHash.length() > 0 && wasInBackground &&
(UserConfig.appLocked || UserConfig.autoLockIn != 0 && UserConfig.lastPauseTime != 0 && !UserConfig.appLocked && (UserConfig.lastPauseTime + UserConfig.autoLockIn) <= ConnectionsManager.getInstance().getCurrentTime());
}
}

View File

@ -54,6 +54,7 @@ public class ContactsController {
private ArrayList<Integer> delayedContactsUpdate = new ArrayList<>();
private String inviteText;
private boolean updatingInviteText = false;
private HashMap<String, String> sectionsToReplace = new HashMap<>();
private int loadingDeleteInfo = 0;
private int deleteAccountTTL;
@ -114,6 +115,28 @@ public class ContactsController {
if (preferences.getBoolean("needGetStatuses", false)) {
reloadContactsStatuses();
}
sectionsToReplace.put("À", "A");
sectionsToReplace.put("Á", "A");
sectionsToReplace.put("Ä", "A");
sectionsToReplace.put("Ù", "U");
sectionsToReplace.put("Ú", "U");
sectionsToReplace.put("Ü", "U");
sectionsToReplace.put("Ì", "I");
sectionsToReplace.put("Í", "I");
sectionsToReplace.put("Ï", "I");
sectionsToReplace.put("È", "E");
sectionsToReplace.put("É", "E");
sectionsToReplace.put("Ê", "E");
sectionsToReplace.put("Ë", "E");
sectionsToReplace.put("Ò", "O");
sectionsToReplace.put("Ó", "O");
sectionsToReplace.put("Ö", "O");
sectionsToReplace.put("Ç", "C");
sectionsToReplace.put("Ñ", "N");
sectionsToReplace.put("Ÿ", "Y");
sectionsToReplace.put("Ý", "Y");
sectionsToReplace.put("Ţ", "Y");
}
public void cleanup() {
@ -514,10 +537,10 @@ public class ContactsController {
checkContactsInternal();
}
final HashMap<Integer, Contact> contactsMap = readContactsFromPhoneBook();
final HashMap<String, Contact> contactsBookShort = new HashMap<String, Contact>();
final HashMap<String, Contact> contactsBookShort = new HashMap<>();
int oldCount = contactHashMap.size();
ArrayList<TLRPC.TL_inputPhoneContact> toImport = new ArrayList<TLRPC.TL_inputPhoneContact>();
ArrayList<TLRPC.TL_inputPhoneContact> toImport = new ArrayList<>();
if (!contactHashMap.isEmpty()) {
for (HashMap.Entry<Integer, Contact> pair : contactsMap.entrySet()) {
Integer id = pair.getKey();
@ -619,10 +642,10 @@ public class ContactsController {
}
}
final ArrayList<TLRPC.User> toDelete = new ArrayList<TLRPC.User>();
final ArrayList<TLRPC.User> toDelete = new ArrayList<>();
if (contactHashMap != null && !contactHashMap.isEmpty()) {
try {
final HashMap<String, TLRPC.User> contactsPhonesShort = new HashMap<String, TLRPC.User>();
final HashMap<String, TLRPC.User> contactsPhonesShort = new HashMap<>();
for (TLRPC.TL_contact value : contacts) {
TLRPC.User user = MessagesController.getInstance().getUser(value.user_id);
@ -692,7 +715,7 @@ public class ContactsController {
}
final int count = (int)Math.ceil(toImport.size() / 500.0f);
for (int a = 0; a < count; a++) {
ArrayList<TLRPC.TL_inputPhoneContact> finalToImport = new ArrayList<TLRPC.TL_inputPhoneContact>();
ArrayList<TLRPC.TL_inputPhoneContact> finalToImport = new ArrayList<>();
finalToImport.addAll(toImport.subList(a * 500, Math.min((a + 1) * 500, toImport.size())));
TLRPC.TL_contacts_importContacts req = new TLRPC.TL_contacts_importContacts();
req.contacts = finalToImport;
@ -713,7 +736,7 @@ public class ContactsController {
// }
}
MessagesStorage.getInstance().putUsersAndChats(res.users, null, true, true);
ArrayList<TLRPC.TL_contact> cArr = new ArrayList<TLRPC.TL_contact>();
ArrayList<TLRPC.TL_contact> cArr = new ArrayList<>();
for (TLRPC.TL_importedContact c : res.imported) {
TLRPC.TL_contact contact = new TLRPC.TL_contact();
contact.user_id = c.user_id;
@ -848,7 +871,7 @@ public class ContactsController {
public void run() {
MessagesController.getInstance().putUsers(usersArr, from == 1);
final HashMap<Integer, TLRPC.User> usersDict = new HashMap<Integer, TLRPC.User>();
final HashMap<Integer, TLRPC.User> usersDict = new HashMap<>();
final boolean isEmpty = contactsArr.isEmpty();
@ -933,9 +956,9 @@ public class ContactsController {
}
});
final SparseArray<TLRPC.TL_contact> contactsDictionary = new SparseArray<TLRPC.TL_contact>();
final HashMap<String, ArrayList<TLRPC.TL_contact>> sectionsDict = new HashMap<String, ArrayList<TLRPC.TL_contact>>();
final ArrayList<String> sortedSectionsArray = new ArrayList<String>();
final SparseArray<TLRPC.TL_contact> contactsDictionary = new SparseArray<>();
final HashMap<String, ArrayList<TLRPC.TL_contact>> sectionsDict = new HashMap<>();
final ArrayList<String> sortedSectionsArray = new ArrayList<>();
HashMap<String, TLRPC.TL_contact> contactsByPhonesDict = null;
if (!contactsBookLoaded) {
@ -958,13 +981,17 @@ public class ContactsController {
if (key == null || key.length() == 0) {
key = user.last_name;
}
if (key.length() > 1) {
key = key.substring(0, 1);
}
if (key.length() == 0) {
key = "#";
} else {
key = key.toUpperCase();
}
if (key.length() > 1) {
key = key.substring(0, 1);
String replace = sectionsToReplace.get(key);
if (replace != null) {
key = replace;
}
ArrayList<TLRPC.TL_contact> arr = sectionsDict.get(key);
if (arr == null) {
@ -1067,7 +1094,7 @@ public class ContactsController {
}
private void updateUnregisteredContacts(final ArrayList<TLRPC.TL_contact> contactsArr) {
final HashMap<String, TLRPC.TL_contact> contactsPhonesShort = new HashMap<String, TLRPC.TL_contact>();
final HashMap<String, TLRPC.TL_contact> contactsPhonesShort = new HashMap<>();
for (TLRPC.TL_contact value : contactsArr) {
TLRPC.User user = MessagesController.getInstance().getUser(value.user_id);
@ -1077,7 +1104,7 @@ public class ContactsController {
contactsPhonesShort.put(user.phone, value);
}
final ArrayList<Contact> sortedPhoneBookContacts = new ArrayList<Contact>();
final ArrayList<Contact> sortedPhoneBookContacts = new ArrayList<>();
for (HashMap.Entry<Integer, Contact> pair : contactsBook.entrySet()) {
Contact value = pair.getValue();
int id = pair.getKey();
@ -1135,8 +1162,8 @@ public class ContactsController {
}
StringBuilder ids = new StringBuilder();
final HashMap<String, ArrayList<TLRPC.TL_contact>> sectionsDict = new HashMap<String, ArrayList<TLRPC.TL_contact>>();
final ArrayList<String> sortedSectionsArray = new ArrayList<String>();
final HashMap<String, ArrayList<TLRPC.TL_contact>> sectionsDict = new HashMap<>();
final ArrayList<String> sortedSectionsArray = new ArrayList<>();
for (TLRPC.TL_contact value : contacts) {
TLRPC.User user = MessagesController.getInstance().getUser(value.user_id);
@ -1148,17 +1175,21 @@ public class ContactsController {
if (key == null || key.length() == 0) {
key = user.last_name;
}
if (key.length() > 1) {
key = key.substring(0, 1);
}
if (key.length() == 0) {
key = "#";
} else {
key = key.toUpperCase();
}
if (key.length() > 1) {
key = key.substring(0, 1);
String replace = sectionsToReplace.get(key);
if (replace != null) {
key = replace;
}
ArrayList<TLRPC.TL_contact> arr = sectionsDict.get(key);
if (arr == null) {
arr = new ArrayList<TLRPC.TL_contact>();
arr = new ArrayList<>();
sectionsDict.put(key, arr);
sortedSectionsArray.add(key);
}
@ -1193,7 +1224,7 @@ public class ContactsController {
try {
Uri rawContactUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, currentAccount.name).appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, currentAccount.type).build();
Cursor c1 = ApplicationLoader.applicationContext.getContentResolver().query(rawContactUri, new String[]{BaseColumns._ID, ContactsContract.RawContacts.SYNC2}, null, null, null);
HashMap<Integer, Long> bookContacts = new HashMap<Integer, Long>();
HashMap<Integer, Long> bookContacts = new HashMap<>();
if (c1 != null) {
while (c1.moveToNext()) {
bookContacts.put(c1.getInt(1), c1.getLong(0));
@ -1213,7 +1244,7 @@ public class ContactsController {
}
private void performWriteContactsToPhoneBook() {
final ArrayList<TLRPC.TL_contact> contactsArray = new ArrayList<TLRPC.TL_contact>();
final ArrayList<TLRPC.TL_contact> contactsArray = new ArrayList<>();
contactsArray.addAll(contacts);
Utilities.photoBookQueue.postRunnable(new Runnable() {
@Override
@ -1225,8 +1256,8 @@ public class ContactsController {
private void applyContactsUpdates(ArrayList<Integer> ids, ConcurrentHashMap<Integer, TLRPC.User> userDict, ArrayList<TLRPC.TL_contact> newC, ArrayList<Integer> contactsTD) {
if (newC == null || contactsTD == null) {
newC = new ArrayList<TLRPC.TL_contact>();
contactsTD = new ArrayList<Integer>();
newC = new ArrayList<>();
contactsTD = new ArrayList<>();
for (Integer uid : ids) {
if (uid > 0) {
TLRPC.TL_contact contact = new TLRPC.TL_contact();
@ -1351,8 +1382,8 @@ public class ContactsController {
}
public void processContactsUpdates(ArrayList<Integer> ids, ConcurrentHashMap<Integer, TLRPC.User> userDict) {
final ArrayList<TLRPC.TL_contact> newContacts = new ArrayList<TLRPC.TL_contact>();
final ArrayList<Integer> contactsToDelete = new ArrayList<Integer>();
final ArrayList<TLRPC.TL_contact> newContacts = new ArrayList<>();
final ArrayList<Integer> contactsToDelete = new ArrayList<>();
for (Integer uid : ids) {
if (uid > 0) {
TLRPC.TL_contact contact = new TLRPC.TL_contact();
@ -1406,7 +1437,7 @@ public class ContactsController {
}
}
ArrayList<ContentProviderOperation> query = new ArrayList<ContentProviderOperation>();
ArrayList<ContentProviderOperation> query = new ArrayList<>();
ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI);
builder.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, currentAccount.name);
@ -1471,7 +1502,7 @@ public class ContactsController {
}
TLRPC.TL_contacts_importContacts req = new TLRPC.TL_contacts_importContacts();
ArrayList<TLRPC.TL_inputPhoneContact> contactsParams = new ArrayList<TLRPC.TL_inputPhoneContact>();
ArrayList<TLRPC.TL_inputPhoneContact> contactsParams = new ArrayList<>();
TLRPC.TL_inputPhoneContact c = new TLRPC.TL_inputPhoneContact();
c.phone = user.phone;
if (!c.phone.startsWith("+")) {
@ -1510,7 +1541,7 @@ public class ContactsController {
});
TLRPC.TL_contact newContact = new TLRPC.TL_contact();
newContact.user_id = u.id;
ArrayList<TLRPC.TL_contact> arrayList = new ArrayList<TLRPC.TL_contact>();
ArrayList<TLRPC.TL_contact> arrayList = new ArrayList<>();
arrayList.add(newContact);
MessagesStorage.getInstance().putContacts(arrayList, false);
@ -1552,7 +1583,7 @@ public class ContactsController {
return;
}
TLRPC.TL_contacts_deleteContacts req = new TLRPC.TL_contacts_deleteContacts();
final ArrayList<Integer> uids = new ArrayList<Integer>();
final ArrayList<Integer> uids = new ArrayList<>();
for (TLRPC.User user : users) {
TLRPC.InputUser inputUser = MessagesController.getInputUser(user);
if (inputUser == null) {
@ -1631,7 +1662,7 @@ public class ContactsController {
editor.remove("needGetStatuses").commit();
TLRPC.Vector vector = (TLRPC.Vector) response;
if (!vector.objects.isEmpty()) {
ArrayList<TLRPC.User> dbUsersStatus = new ArrayList<TLRPC.User>();
ArrayList<TLRPC.User> dbUsersStatus = new ArrayList<>();
for (Object object : vector.objects) {
TLRPC.User toDbUser = new TLRPC.User();
TLRPC.TL_contactStatus status = (TLRPC.TL_contactStatus) object;

View File

@ -344,7 +344,7 @@ public class ImageLoader {
});
}
});
AndroidUtilities.runOnUIThread(new Runnable() {
imageLoadQueue.postRunnable(new Runnable() {
@Override
public void run() {
runHttpTasks(true);
@ -354,7 +354,7 @@ public class ImageLoader {
@Override
protected void onCancelled() {
AndroidUtilities.runOnUIThread(new Runnable() {
imageLoadQueue.postRunnable(new Runnable() {
@Override
public void run() {
runHttpTasks(true);
@ -633,7 +633,7 @@ public class ImageLoader {
}
}
if (cacheImage.filter == null || blur) {
if (cacheImage.filter == null || blur || cacheImage.httpUrl != null) {
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
} else {
opts.inPreferredConfig = Bitmap.Config.RGB_565;
@ -1057,6 +1057,12 @@ public class ImageLoader {
FileLog.e("tmessages", e);
}
}
try {
new File(cachePath, ".nomedia").createNewFile();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
mediaDirs.put(FileLoader.MEDIA_DIR_CACHE, cachePath);
FileLog.e("tmessages", "cache path = " + cachePath);
@ -1678,42 +1684,47 @@ public class ImageLoader {
runHttpFileLoadTasks(null, 0);
}
private void runHttpFileLoadTasks(HttpFileTask oldTask, int reason) {
if (oldTask != null) {
currentHttpFileLoadTasksCount--;
}
if (oldTask != null) {
if (reason == 1) {
if (oldTask.canRetry) {
final HttpFileTask newTask = new HttpFileTask(oldTask.url, oldTask.tempFile, oldTask.ext);
Runnable runnable = new Runnable() {
@Override
public void run() {
httpFileLoadTasks.add(newTask);
runHttpFileLoadTasks(null, 0);
}
};
retryHttpsTasks.put(oldTask.url, runnable);
AndroidUtilities.runOnUIThread(runnable, 1000);
} else {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.httpFileDidFailedLoad, oldTask.url);
private void runHttpFileLoadTasks(final HttpFileTask oldTask, final int reason) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
if (oldTask != null) {
currentHttpFileLoadTasksCount--;
}
if (oldTask != null) {
if (reason == 1) {
if (oldTask.canRetry) {
final HttpFileTask newTask = new HttpFileTask(oldTask.url, oldTask.tempFile, oldTask.ext);
Runnable runnable = new Runnable() {
@Override
public void run() {
httpFileLoadTasks.add(newTask);
runHttpFileLoadTasks(null, 0);
}
};
retryHttpsTasks.put(oldTask.url, runnable);
AndroidUtilities.runOnUIThread(runnable, 1000);
} else {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.httpFileDidFailedLoad, oldTask.url);
}
} else if (reason == 2) {
httpFileLoadTasksByKeys.remove(oldTask.url);
File file = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), Utilities.MD5(oldTask.url) + "." + oldTask.ext);
String result = oldTask.tempFile.renameTo(file) ? file.toString() : oldTask.tempFile.toString();
NotificationCenter.getInstance().postNotificationName(NotificationCenter.httpFileDidLoaded, oldTask.url, result);
}
}
while (currentHttpFileLoadTasksCount < 2 && !httpFileLoadTasks.isEmpty()) {
HttpFileTask task = httpFileLoadTasks.poll();
if (android.os.Build.VERSION.SDK_INT >= 11) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null, null, null);
} else {
task.execute(null, null, null);
}
currentHttpFileLoadTasksCount++;
}
} else if (reason == 2) {
httpFileLoadTasksByKeys.remove(oldTask.url);
File file = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), Utilities.MD5(oldTask.url) + "." + oldTask.ext);
String result = oldTask.tempFile.renameTo(file) ? file.toString() : oldTask.tempFile.toString();
NotificationCenter.getInstance().postNotificationName(NotificationCenter.httpFileDidLoaded, oldTask.url, result);
}
}
while (currentHttpFileLoadTasksCount < 2 && !httpFileLoadTasks.isEmpty()) {
HttpFileTask task = httpFileLoadTasks.poll();
if (android.os.Build.VERSION.SDK_INT >= 11) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null, null, null);
} else {
task.execute(null, null, null);
}
currentHttpFileLoadTasksCount++;
}
});
}
public static Bitmap loadBitmap(String path, Uri uri, float maxWidth, float maxHeight, boolean useMaxScale) {

View File

@ -69,6 +69,8 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
private int alpha = 255;
private boolean isPressed;
private boolean disableRecycle;
private int orientation;
private boolean centerRotation;
private ImageReceiverDelegate delegate;
public ImageReceiver() {
@ -209,6 +211,15 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
return isPressed;
}
public void setOrientation(int angle, boolean center) {
orientation = angle;
centerRotation = center;
}
public int getOrientation() {
return orientation;
}
public void setImageBitmap(Bitmap bitmap) {
setImageBitmap(bitmap != null ? new BitmapDrawable(null, bitmap) : null);
}
@ -280,8 +291,17 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
canvas.drawRoundRect(roundRect, roundRadius, roundRadius, roundPaint);
}
} else {
int bitmapW = bitmapDrawable.getIntrinsicWidth();
int bitmapH = bitmapDrawable.getIntrinsicHeight();
int bitmapW;
int bitmapH;
int originalW = bitmapDrawable.getIntrinsicWidth();
int originalH = bitmapDrawable.getIntrinsicHeight();
if (orientation == 90 || orientation == 270) {
bitmapW = bitmapDrawable.getIntrinsicHeight();
bitmapH = bitmapDrawable.getIntrinsicWidth();
} else {
bitmapW = bitmapDrawable.getIntrinsicWidth();
bitmapH = bitmapDrawable.getIntrinsicHeight();
}
float scaleW = bitmapW / (float) imageW;
float scaleH = bitmapH / (float) imageH;
@ -312,14 +332,32 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
canvas.save();
canvas.clipRect(imageX, imageY, imageX + imageW, imageY + imageH);
if (orientation != 0) {
if (centerRotation) {
canvas.rotate(orientation, imageW / 2, imageH / 2);
} else {
canvas.rotate(orientation, 0, 0);
}
}
if (bitmapW / scaleH > imageW) {
bitmapW /= scaleH;
originalW /= scaleH;
drawRegion.set(imageX - (bitmapW - imageW) / 2, imageY, imageX + (bitmapW + imageW) / 2, imageY + imageH);
} else {
bitmapH /= scaleW;
originalH /= scaleW;
drawRegion.set(imageX, imageY - (bitmapH - imageH) / 2, imageX + imageW, imageY + (bitmapH + imageH) / 2);
}
bitmapDrawable.setBounds(drawRegion);
if (orientation == 90 || orientation == 270) {
int width = (drawRegion.right - drawRegion.left) / 2;
int height = (drawRegion.bottom - drawRegion.top) / 2;
int centerX = (drawRegion.right + drawRegion.left) / 2;
int centerY = (drawRegion.top + drawRegion.bottom) / 2;
bitmapDrawable.setBounds(centerX - height, centerY - width, centerX + height, centerY + width);
} else {
bitmapDrawable.setBounds(drawRegion);
}
if (isVisible) {
try {
bitmapDrawable.setAlpha(alpha);
@ -339,8 +377,24 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
canvas.restore();
} else {
canvas.save();
if (orientation != 0) {
if (centerRotation) {
canvas.rotate(orientation, imageW / 2, imageH / 2);
} else {
canvas.rotate(orientation, 0, 0);
}
}
drawRegion.set(imageX, imageY, imageX + imageW, imageY + imageH);
bitmapDrawable.setBounds(drawRegion);
if (orientation == 90 || orientation == 270) {
int width = (drawRegion.right - drawRegion.left) / 2;
int height = (drawRegion.bottom - drawRegion.top) / 2;
int centerX = (drawRegion.right + drawRegion.left) / 2;
int centerY = (drawRegion.top + drawRegion.bottom) / 2;
bitmapDrawable.setBounds(centerX - height, centerY - width, centerX + height, centerY + width);
} else {
bitmapDrawable.setBounds(drawRegion);
}
if (isVisible) {
try {
bitmapDrawable.setAlpha(alpha);
@ -357,6 +411,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
FileLog.e("tmessages", e);
}
}
canvas.restore();
}
}
}
@ -391,6 +446,16 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
return null;
}
public int getBitmapWidth() {
Bitmap bitmap = getBitmap();
return orientation == 0 || orientation == 180 ? bitmap.getWidth() : bitmap.getHeight();
}
public int getBitmapHeight() {
Bitmap bitmap = getBitmap();
return orientation == 0 || orientation == 180 ? bitmap.getHeight() : bitmap.getWidth();
}
public void setVisible(boolean value, boolean invalidate) {
if (isVisible == value) {
return;

View File

@ -54,6 +54,7 @@ public class LocaleController {
public static FastDateFormat formatterWeek;
public static FastDateFormat formatterMonth;
public static FastDateFormat formatterYear;
public static FastDateFormat formatterMonthYear;
public static FastDateFormat formatterYearMax;
public static FastDateFormat chatDate;
public static FastDateFormat chatFullDate;
@ -135,7 +136,7 @@ public class LocaleController {
addRules(new String[]{"bem", "brx", "da", "de", "el", "en", "eo", "es", "et", "fi", "fo", "gl", "he", "iw", "it", "nb",
"nl", "nn", "no", "sv", "af", "bg", "bn", "ca", "eu", "fur", "fy", "gu", "ha", "is", "ku",
"lb", "ml", "mr", "nah", "ne", "om", "or", "pa", "pap", "ps", "so", "sq", "sw", "ta", "te",
"tk", "ur", "zu", "mn", "gsw", "chr", "rm", "pt"}, new PluralRules_One());
"tk", "ur", "zu", "mn", "gsw", "chr", "rm", "pt", "an", "ast"}, new PluralRules_One());
addRules(new String[]{"cs", "sk"}, new PluralRules_Czech());
addRules(new String[]{"ff", "fr", "kab"}, new PluralRules_French());
addRules(new String[]{"hr", "ru", "sr", "uk", "be", "bs", "sh"}, new PluralRules_Balkan());
@ -544,6 +545,9 @@ public class LocaleController {
currentLocale = newLocale;
currentLocaleInfo = localeInfo;
currentPluralRules = allRules.get(currentLocale.getLanguage());
if (currentPluralRules == null) {
currentPluralRules = allRules.get("en");
}
changingConfiguration = true;
Locale.setDefault(currentLocale);
android.content.res.Configuration config = new android.content.res.Configuration();
@ -571,6 +575,9 @@ public class LocaleController {
if (value == null) {
value = ApplicationLoader.applicationContext.getString(res);
}
if (value == null) {
value = "LOC_ERR:" + key;
}
return value;
}
@ -638,6 +645,9 @@ public class LocaleController {
}
currentLocale = newLocale;
currentPluralRules = allRules.get(currentLocale.getLanguage());
if (currentPluralRules == null) {
currentPluralRules = allRules.get("en");
}
}
}
}
@ -695,6 +705,20 @@ public class LocaleController {
}
}
private FastDateFormat createFormatter(Locale locale, String format, String defaultFormat) {
if (format == null || format.length() == 0) {
format = defaultFormat;
}
FastDateFormat formatter = null;
try {
formatter = FastDateFormat.getInstance(format, locale);
} catch (Exception e) {
format = defaultFormat;
formatter = FastDateFormat.getInstance(format, locale);
}
return formatter;
}
public void recreateFormatters() {
Locale locale = currentLocale;
if (locale == null) {
@ -706,59 +730,15 @@ public class LocaleController {
}
isRTL = lang.toLowerCase().equals("ar");
nameDisplayOrder = lang.toLowerCase().equals("ko") ? 2 : 1;
String formatString = getStringInternal("formatterMonth", R.string.formatterMonth);
if (formatString == null || formatString.length() == 0) {
formatString = "dd MMM";
}
formatterMonth = FastDateFormat.getInstance(formatString, locale);
formatString = getStringInternal("formatterYear", R.string.formatterYear);
if (formatString == null || formatString.length() == 0) {
formatString = "dd.MM.yy";
}
formatterYear = FastDateFormat.getInstance(formatString, locale);
formatString = getStringInternal("formatterYearMax", R.string.formatterYearMax);
if (formatString == null || formatString.length() == 0) {
formatString = "dd.MM.yyyy";
}
formatterYearMax = FastDateFormat.getInstance(formatString, locale);
formatString = getStringInternal("chatDate", R.string.chatDate);
if (formatString == null || formatString.length() == 0) {
formatString = "d MMMM";
}
chatDate = FastDateFormat.getInstance(formatString, locale);
formatString = getStringInternal("chatFullDate", R.string.chatFullDate);
if (formatString == null || formatString.length() == 0) {
formatString = "d MMMM yyyy";
}
chatFullDate = FastDateFormat.getInstance(formatString, locale);
formatString = getStringInternal("formatterWeek", R.string.formatterWeek);
if (formatString == null || formatString.length() == 0) {
formatString = "EEE";
}
formatterWeek = FastDateFormat.getInstance(formatString, locale);
if (is24HourFormat) {
formatString = getStringInternal("formatterDay24H", R.string.formatterDay24H);
} else {
formatString = getStringInternal("formatterDay12H", R.string.formatterDay12H);
}
if (formatString == null || formatString.length() == 0) {
if (is24HourFormat) {
formatString = "HH:mm";
} else {
formatString = "h:mm a";
}
}
if (lang.toLowerCase().equals("ar") || lang.toLowerCase().equals("ko")) {
formatterDay = FastDateFormat.getInstance(formatString, locale);
} else {
formatterDay = FastDateFormat.getInstance(formatString, Locale.US);
}
formatterMonth = createFormatter(locale, getStringInternal("formatterMonth", R.string.formatterMonth), "dd MMM");
formatterYear = createFormatter(locale, getStringInternal("formatterYear", R.string.formatterYear), "dd.MM.yy");
formatterYearMax = createFormatter(locale, getStringInternal("formatterYearMax", R.string.formatterYearMax), "dd.MM.yyyy");
chatDate = createFormatter(locale, getStringInternal("chatDate", R.string.chatDate), "d MMMM");
chatFullDate = createFormatter(locale, getStringInternal("chatFullDate", R.string.chatFullDate), "d MMMM yyyy");
formatterWeek = createFormatter(locale, getStringInternal("formatterWeek", R.string.formatterWeek), "EEE");
formatterMonthYear = createFormatter(locale, getStringInternal("formatterMonthYear", R.string.formatterMonthYear), "MMMM yyyy");
formatterDay = createFormatter(lang.toLowerCase().equals("ar") || lang.toLowerCase().equals("ko") ? locale : Locale.US, is24HourFormat ? getStringInternal("formatterDay24H", R.string.formatterDay24H) : getStringInternal("formatterDay12H", R.string.formatterDay12H), is24HourFormat ? "HH:mm" : "h:mm a");
}
public static String stringForMessageListDate(long date) {

View File

@ -165,6 +165,8 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
public int size;
public int type;
public int date;
public String thumbPath;
public String imagePath;
}
public final static String MIME_TYPE = "video/avc";

View File

@ -42,6 +42,7 @@ public class MessageObject {
public int type;
public int contentType;
public String dateKey;
public String monthKey;
public boolean deleted = false;
public float audioProgress;
public int audioProgressSec;
@ -199,7 +200,7 @@ public class MessageObject {
}
}
} else if (message.action instanceof TLRPC.TL_messageActionLoginUnknownLocation) {
String date = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.formatterYear.format(((long)message.date) * 1000), LocaleController.formatterDay.format(((long)message.date) * 1000));
String date = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.formatterYear.format(((long) message.date) * 1000), LocaleController.formatterDay.format(((long) message.date) * 1000));
TLRPC.User to_user = UserConfig.getCurrentUser();
if (to_user == null) {
if (users != null) {
@ -346,11 +347,14 @@ public class MessageObject {
}
Calendar rightNow = new GregorianCalendar();
rightNow.setTimeInMillis((long)(messageOwner.date) * 1000);
rightNow.setTimeInMillis((long) (messageOwner.date) * 1000);
int dateDay = rightNow.get(Calendar.DAY_OF_YEAR);
int dateYear = rightNow.get(Calendar.YEAR);
int dateMonth = rightNow.get(Calendar.MONTH);
dateKey = String.format("%d_%02d_%02d", dateYear, dateMonth, dateDay);
if (contentType == 1 || contentType == 2) {
monthKey = String.format("%d_%02d", dateYear, dateMonth);
}
if (generateLayout) {
generateLayout();
@ -556,7 +560,7 @@ public class MessageObject {
textHeight = textLayout.getHeight();
int linesCount = textLayout.getLineCount();
int blocksCount = (int)Math.ceil((float)linesCount / LINES_PER_BLOCK);
int blocksCount = (int) Math.ceil((float) linesCount / LINES_PER_BLOCK);
int linesOffset = 0;
float prevOffset = 0;
@ -581,7 +585,7 @@ public class MessageObject {
block.textLayout = new StaticLayout(str, textPaint, maxWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
block.textYOffset = textLayout.getLineTop(linesOffset);
if (a != 0) {
blockHeight = Math.min(blockHeight, (int)(block.textYOffset - prevOffset));
blockHeight = Math.min(blockHeight, (int) (block.textYOffset - prevOffset));
}
prevOffset = block.textYOffset;
/*if (a != blocksCount - 1) {
@ -613,7 +617,7 @@ public class MessageObject {
FileLog.e("tmessages", e);
}
int linesMaxWidth = (int)Math.ceil(lastLine);
int linesMaxWidth = (int) Math.ceil(lastLine);
int lastLineWidthWithLeft;
int linesMaxWidthWithLeft;
boolean hasNonRTL = false;
@ -622,7 +626,7 @@ public class MessageObject {
lastLineWidth = linesMaxWidth;
}
linesMaxWidthWithLeft = lastLineWidthWithLeft = (int)Math.ceil(lastLine + lastLeft);
linesMaxWidthWithLeft = lastLineWidthWithLeft = (int) Math.ceil(lastLine + lastLeft);
if (lastLeft == 0) {
hasNonRTL = true;
}
@ -655,8 +659,8 @@ public class MessageObject {
}
textRealMaxWidth = Math.max(textRealMaxWidth, lineWidth);
textRealMaxWidthWithLeft = Math.max(textRealMaxWidthWithLeft, lineWidth + lineLeft);
linesMaxWidth = Math.max(linesMaxWidth, (int)Math.ceil(lineWidth));
linesMaxWidthWithLeft = Math.max(linesMaxWidthWithLeft, (int)Math.ceil(lineWidth + lineLeft));
linesMaxWidth = Math.max(linesMaxWidth, (int) Math.ceil(lineWidth));
linesMaxWidthWithLeft = Math.max(linesMaxWidthWithLeft, (int) Math.ceil(lineWidth + lineLeft));
}
if (hasNonRTL) {
textRealMaxWidth = textRealMaxWidthWithLeft;
@ -667,7 +671,7 @@ public class MessageObject {
} else if (a == blocksCount - 1) {
lastLineWidth = linesMaxWidth;
}
textWidth = Math.max(textWidth, (int)Math.ceil(textRealMaxWidth));
textWidth = Math.max(textWidth, (int) Math.ceil(textRealMaxWidth));
} else {
textWidth = Math.max(textWidth, Math.min(maxWidth, linesMaxWidth));
}
@ -696,7 +700,7 @@ public class MessageObject {
}
public void setIsRead() {
messageOwner.flags &=~ TLRPC.MESSAGE_FLAG_UNREAD;
messageOwner.flags &= ~TLRPC.MESSAGE_FLAG_UNREAD;
}
public boolean isSecretPhoto() {
@ -706,15 +710,15 @@ public class MessageObject {
public boolean isSecretMedia() {
return messageOwner instanceof TLRPC.TL_message_secret &&
(messageOwner.media instanceof TLRPC.TL_messageMediaPhoto && messageOwner.ttl != 0 && messageOwner.ttl <= 60 ||
messageOwner.media instanceof TLRPC.TL_messageMediaAudio ||
messageOwner.media instanceof TLRPC.TL_messageMediaVideo);
messageOwner.media instanceof TLRPC.TL_messageMediaAudio ||
messageOwner.media instanceof TLRPC.TL_messageMediaVideo);
}
public static void setIsUnread(TLRPC.Message message, boolean unread) {
if (unread) {
message.flags |= TLRPC.MESSAGE_FLAG_UNREAD;
} else {
message.flags &=~ TLRPC.MESSAGE_FLAG_UNREAD;
message.flags &= ~TLRPC.MESSAGE_FLAG_UNREAD;
}
}

View File

@ -102,6 +102,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
public static final int UPDATE_MASK_READ_DIALOG_MESSAGE = 256;
public static final int UPDATE_MASK_SELECT_DIALOG = 512;
public static final int UPDATE_MASK_PHONE = 1024;
public static final int UPDATE_MASK_NEW_MESSAGE = 2048;
public static final int UPDATE_MASK_SEND_STATE = 4096;
public static final int UPDATE_MASK_ALL = UPDATE_MASK_AVATAR | UPDATE_MASK_STATUS | UPDATE_MASK_NAME | UPDATE_MASK_CHAT_AVATAR | UPDATE_MASK_CHAT_NAME | UPDATE_MASK_CHAT_MEMBERS | UPDATE_MASK_USER_PRINT | UPDATE_MASK_USER_PHONE | UPDATE_MASK_READ_DIALOG_MESSAGE | UPDATE_MASK_PHONE;
public static class PrintingUser {
@ -863,6 +865,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.mainUserInfoChanged);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_ALL);
UserConfig.saveConfig(true);
}
@ -944,10 +947,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
public void deleteDialog(final long did, int offset, final boolean onlyHistory) {
if (offset == 0) {
MessagesStorage.getInstance().deleteDialog(did, onlyHistory);
}
int lower_part = (int)did;
int high_id = (int)(did >> 32);
@ -963,7 +962,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter
dialog.unread_count = 0;
}
dialogMessage.remove(dialog.top_message);
dialog.top_message = 0;
}
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.removeAllMessagesFromDialog, did);
MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
@Override
public void run() {
@ -978,8 +980,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
});
}
});
NotificationCenter.getInstance().postNotificationName(NotificationCenter.removeAllMessagesFromDialog, did);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
MessagesStorage.getInstance().deleteDialog(did, onlyHistory);
}
if (high_id == 1) {
@ -1437,8 +1439,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
currentDialog.unread_count = entry.getValue();
}
}
NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate);
}
});
}
@ -1533,8 +1535,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
dialogsServerOnly.add(d);
}
}
NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate);
}
});
}
@ -1554,8 +1556,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (resetEnd) {
dialogsEndReached = false;
}
loadDialogs(offset, serverOffset, count, false);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
loadDialogs(offset, serverOffset, count, false);
}
});
return;
@ -1713,6 +1715,9 @@ public class MessagesController implements NotificationCenter.NotificationCenter
req.peer.chat_id = -lower_part;
} else {
TLRPC.User user = getUser(lower_part);
if (user == null) {
return;
}
if (user instanceof TLRPC.TL_userForeign || user instanceof TLRPC.TL_userRequest) {
req.peer = new TLRPC.TL_inputPeerForeign();
req.peer.user_id = user.id;
@ -1865,8 +1870,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
arr.add(newMsg);
MessagesStorage.getInstance().putMessages(arr, false, true, false, 0);
updateInterfaceWithMessages(newMsg.dialog_id, objArr);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidCreated, chat.id);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidCreated, chat.id);
return 0;
} else {
@ -1903,8 +1908,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
messagesObj.add(new MessageObject(res.message, users, true));
TLRPC.Chat chat = res.chats.get(0);
updateInterfaceWithMessages(-chat.id, messagesObj);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidCreated, chat.id);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidCreated, chat.id);
if (uploadedAvatar != null) {
changeChatAvatar(chat.id, uploadedAvatar);
}
@ -1950,8 +1955,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
messagesObj.add(new MessageObject(res.message, users, true));
TLRPC.Chat chat = res.chats.get(0);
updateInterfaceWithMessages(-chat.id, messagesObj);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_MEMBERS);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_MEMBERS);
if (info != null) {
for (TLRPC.TL_chatParticipant p : info.participants) {
@ -2032,8 +2037,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
messagesObj.add(new MessageObject(res.message, users, true));
TLRPC.Chat chat = res.chats.get(0);
updateInterfaceWithMessages(-chat.id, messagesObj);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_MEMBERS);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_MEMBERS);
}
boolean changed = false;
if (info != null) {
@ -2851,10 +2856,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
public boolean isDialogMuted(long dialog_id) {
TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id);
/*TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id);
if (dialog != null) {
return isNotifySettingsMuted(dialog.notify_settings);
} else {
} else {*/
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
int mute_type = preferences.getInt("notify2_" + dialog_id, 0);
if (mute_type == 2) {
@ -2865,7 +2870,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
return true;
}
}
}
//}
return false;
}

View File

@ -838,6 +838,59 @@ public class MessagesStorage {
//database.executeFast("DELETE FROM secret_holes WHERE uid = " + high_id).stepThis().dispose();
}
}
if ((int) did == 0) {
SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT data FROM messages WHERE uid = " + did));
ArrayList<File> filesToDelete = new ArrayList<>();
try {
while (cursor.next()) {
ByteBufferDesc data = buffersStorage.getFreeBuffer(cursor.byteArrayLength(0));
if (data != null && cursor.byteBufferValue(0, data.buffer) != 0) {
TLRPC.Message message = (TLRPC.Message) TLClassStore.Instance().TLdeserialize(data, data.readInt32());
if (message == null || message.media == null) {
continue;
}
if (message.media instanceof TLRPC.TL_messageMediaAudio) {
File file = FileLoader.getPathToAttach(message.media.audio);
if (file != null && file.toString().length() > 0) {
filesToDelete.add(file);
}
} else if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
for (TLRPC.PhotoSize photoSize : message.media.photo.sizes) {
File file = FileLoader.getPathToAttach(photoSize);
if (file != null && file.toString().length() > 0) {
filesToDelete.add(file);
}
}
} else if (message.media instanceof TLRPC.TL_messageMediaVideo) {
File file = FileLoader.getPathToAttach(message.media.video);
if (file != null && file.toString().length() > 0) {
filesToDelete.add(file);
}
file = FileLoader.getPathToAttach(message.media.video.thumb);
if (file != null && file.toString().length() > 0) {
filesToDelete.add(file);
}
} else if (message.media instanceof TLRPC.TL_messageMediaDocument) {
File file = FileLoader.getPathToAttach(message.media.document);
if (file != null && file.toString().length() > 0) {
filesToDelete.add(file);
}
file = FileLoader.getPathToAttach(message.media.document.thumb);
if (file != null && file.toString().length() > 0) {
filesToDelete.add(file);
}
}
}
buffersStorage.reuseFreeBuffer(data);
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
cursor.dispose();
FileLoader.getInstance().deleteFiles(filesToDelete);
}
database.executeFast("UPDATE dialogs SET unread_count = 0 WHERE did = " + did).stepThis().dispose();
database.executeFast("DELETE FROM messages WHERE uid = " + did).stepThis().dispose();
database.executeFast("DELETE FROM media_counts_v2 WHERE uid = " + did).stepThis().dispose();
@ -3178,6 +3231,7 @@ public class MessagesStorage {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesDeleted, mids);
}
});
MessagesStorage.getInstance().updateDialogsWithReadedMessagesInternal(mids);
MessagesStorage.getInstance().markMessagesAsDeletedInternal(mids);
MessagesStorage.getInstance().updateDialogsWithDeletedMessagesInternal(mids);
}
@ -3189,9 +3243,6 @@ public class MessagesStorage {
}
private void markMessagesAsDeletedInternal(final ArrayList<Integer> messages) {
if (Thread.currentThread().getId() != storageQueue.getId()) {
throw new RuntimeException("wrong db thread");
}
try {
String ids = TextUtils.join(",", messages);
SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid, data FROM messages WHERE mid IN(%s)", ids));
@ -3287,7 +3338,7 @@ public class MessagesStorage {
ArrayList<Integer> usersToLoad = new ArrayList<>();
ArrayList<Integer> chatsToLoad = new ArrayList<>();
ArrayList<Integer> encryptedToLoad = new ArrayList<>();
cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid WHERE d.did IN(%s)", ids));
cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state, m.date FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid WHERE d.did IN(%s)", ids));
while (cursor.next()) {
TLRPC.TL_dialog dialog = new TLRPC.TL_dialog();
dialog.id = cursor.longValue(0);
@ -3302,6 +3353,10 @@ public class MessagesStorage {
MessageObject.setIsUnread(message, cursor.intValue(5) != 1);
message.id = cursor.intValue(6);
message.send_state = cursor.intValue(7);
int date = cursor.intValue(8);
if (date != 0) {
dialog.last_message_date = date;
}
dialogs.messages.add(message);
if (!usersToLoad.contains(message.from_id)) {
@ -3471,7 +3526,7 @@ public class MessagesStorage {
usersToLoad.add(UserConfig.getClientUserId());
ArrayList<Integer> chatsToLoad = new ArrayList<>();
ArrayList<Integer> encryptedToLoad = new ArrayList<>();
SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state, s.flags FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid LEFT JOIN dialog_settings as s ON d.did = s.did ORDER BY d.date DESC LIMIT %d,%d", offset, count));
SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state, s.flags, m.date FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid LEFT JOIN dialog_settings as s ON d.did = s.did ORDER BY d.date DESC LIMIT %d,%d", offset, count));
while (cursor.next()) {
TLRPC.TL_dialog dialog = new TLRPC.TL_dialog();
dialog.id = cursor.longValue(0);
@ -3495,6 +3550,10 @@ public class MessagesStorage {
if (message != null) {
MessageObject.setIsUnread(message, cursor.intValue(5) != 1);
message.id = cursor.intValue(6);
int date = cursor.intValue(9);
if (date != 0) {
dialog.last_message_date = date;
}
message.send_state = cursor.intValue(7);
dialogs.messages.add(message);

View File

@ -23,7 +23,7 @@ import java.util.zip.ZipFile;
public class NativeLoader {
private final static int LIB_VERSION = 5;
private final static int LIB_VERSION = 6;
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";

View File

@ -48,6 +48,9 @@ public class NotificationCenter {
public static final int updateMessageMedia = totalEvents++;
public static final int recentImagesDidLoaded = totalEvents++;
public static final int replaceMessagesObjects = totalEvents++;
public static final int didSetPasscode = totalEvents++;
public static final int screenStateChanged = totalEvents++;
public static final int appSwitchedToForeground = totalEvents++;
public static final int httpFileDidLoaded = totalEvents++;
public static final int httpFileDidFailedLoad = totalEvents++;

View File

@ -11,6 +11,7 @@ package org.telegram.android;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
@ -29,6 +30,7 @@ import android.support.v4.app.RemoteInput;
import org.json.JSONArray;
import org.json.JSONObject;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.DispatchQueue;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.R;
import org.telegram.messenger.RPCRequest;
@ -48,6 +50,7 @@ public class NotificationsController {
public static final String EXTRA_VOICE_REPLY = "extra_voice_reply";
private DispatchQueue notificationsQueue = new DispatchQueue("notificationsQueue");
private ArrayList<MessageObject> pushMessages = new ArrayList<>();
private HashMap<Integer, MessageObject> pushMessagesDict = new HashMap<>();
private NotificationManagerCompat notificationManager = null;
@ -130,7 +133,9 @@ public class NotificationsController {
}
String msg = null;
if ((int)dialog_id != 0) {
if ((int)dialog_id == 0 || AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) {
msg = LocaleController.getString("YouHaveNewMessage", R.string.YouHaveNewMessage);
} else {
if (chat_id == 0 && user_id != 0) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
if (preferences.getBoolean("EnablePreviewAll", true)) {
@ -237,8 +242,6 @@ public class NotificationsController {
msg = LocaleController.formatString("NotificationMessageGroupNoText", R.string.NotificationMessageGroupNoText, ContactsController.formatName(user.first_name, user.last_name), chat.title);
}
}
} else {
msg = LocaleController.getString("YouHaveNewMessage", R.string.YouHaveNewMessage);
}
return msg;
}
@ -250,7 +253,7 @@ public class NotificationsController {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
int minutes = preferences.getInt("repeat_messages", 60);
if (minutes > 0 && personal_count > 0) {
alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + minutes * 60 * 1000, pintent);
alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + minutes * 60 * 1000, pintent);
} else {
alarm.cancel(pintent);
}
@ -266,9 +269,9 @@ public class NotificationsController {
PendingIntent pintent = PendingIntent.getService(ApplicationLoader.applicationContext, 0, new Intent(ApplicationLoader.applicationContext, NotificationDelay.class), 0);
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
if (onlineReason) {
alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 3 * 1000, pintent);
alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 3 * 1000, pintent);
} else {
alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 500, pintent);
alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 500, pintent);
}
} catch (Exception e) {
FileLog.e("tmessages", e);
@ -416,14 +419,18 @@ public class NotificationsController {
intent.putExtra("userId", user_id);
}
}
if (pushDialogs.size() == 1) {
if (chat != null) {
if (chat.photo != null && chat.photo.photo_small != null && chat.photo.photo_small.volume_id != 0 && chat.photo.photo_small.local_id != 0) {
photoPath = chat.photo.photo_small;
}
} else {
if (user.photo != null && user.photo.photo_small != null && user.photo.photo_small.volume_id != 0 && user.photo.photo_small.local_id != 0) {
photoPath = user.photo.photo_small;
if (AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) {
photoPath = null;
} else {
if (pushDialogs.size() == 1) {
if (chat != null) {
if (chat.photo != null && chat.photo.photo_small != null && chat.photo.photo_small.volume_id != 0 && chat.photo.photo_small.local_id != 0) {
photoPath = chat.photo.photo_small;
}
} else {
if (user.photo != null && user.photo.photo_small != null && user.photo.photo_small.volume_id != 0 && user.photo.photo_small.local_id != 0) {
photoPath = user.photo.photo_small;
}
}
}
}
@ -436,7 +443,7 @@ public class NotificationsController {
String name = null;
boolean replace = true;
if ((int)dialog_id == 0 || pushDialogs.size() > 1) {
if ((int)dialog_id == 0 || pushDialogs.size() > 1 || AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) {
name = LocaleController.getString("AppName", R.string.AppName);
replace = false;
} else {
@ -451,7 +458,7 @@ public class NotificationsController {
if (pushDialogs.size() == 1) {
detailText = LocaleController.formatPluralString("NewMessages", total_unread_count);
} else {
detailText = LocaleController.formatString("NotificationMessagesPeopleDisplayOrder", R.string.NotificationMessagesPeopleDisplayOrder, LocaleController.formatPluralString("NewMessages", total_unread_count), LocaleController.formatPluralString("FromContacts", pushDialogs.size()));
detailText = LocaleController.formatString("NotificationMessagesPeopleDisplayOrder", R.string.NotificationMessagesPeopleDisplayOrder, LocaleController.formatPluralString("NewMessages", total_unread_count), LocaleController.formatPluralString("FromChats", pushDialogs.size()));
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ApplicationLoader.applicationContext)
@ -834,7 +841,7 @@ public class NotificationsController {
notifyCheck = isLast;
}
if (!popupMessages.isEmpty() && oldCount != popupMessages.size()) {
if (!popupMessages.isEmpty() && oldCount != popupMessages.size() && !AndroidUtilities.needShowPasscode(false)) {
if (ApplicationLoader.mainInterfacePaused || !ApplicationLoader.isScreenOn) {
MessageObject messageObject = messageObjects.get(0);
if (popup == 3 || popup == 1 && ApplicationLoader.isScreenOn || popup == 2 && !ApplicationLoader.isScreenOn) {
@ -988,20 +995,33 @@ public class NotificationsController {
setBadge(ApplicationLoader.applicationContext, enabled ? total_unread_count : 0);
}
private void setBadge(Context context, int count) {
try {
String launcherClassName = getLauncherClassName(context);
if (launcherClassName == null) {
return;
private void setBadge(final Context context, final int count) {
notificationsQueue.postRunnable(new Runnable() {
@Override
public void run() {
try {
ContentValues cv = new ContentValues();
cv.put("tag", "org.telegram.messenger/org.telegram.ui.LaunchActivity");
cv.put("count", count);
context.getContentResolver().insert(Uri.parse("content://com.teslacoilsw.notifier/unread_count"), cv);
} catch (Throwable e) {
//ignore
}
try {
String launcherClassName = getLauncherClassName(context);
if (launcherClassName == null) {
return;
}
Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
intent.putExtra("badge_count", count);
intent.putExtra("badge_count_package_name", context.getPackageName());
intent.putExtra("badge_count_class_name", launcherClassName);
context.sendBroadcast(intent);
} catch (Throwable e) {
FileLog.e("tmessages", e);
}
}
Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
intent.putExtra("badge_count", count);
intent.putExtra("badge_count_package_name", context.getPackageName());
intent.putExtra("badge_count_class_name", launcherClassName);
context.sendBroadcast(intent);
} catch (Throwable e) {
FileLog.e("tmessages", e);
}
});
}
public static String getLauncherClassName(Context context) {

View File

@ -28,5 +28,6 @@ public class ScreenReceiver extends BroadcastReceiver {
ConnectionsManager.getInstance().setAppPaused(false, true);
ApplicationLoader.isScreenOn = true;
}
NotificationCenter.getInstance().postNotificationName(NotificationCenter.screenStateChanged);
}
}

View File

@ -1072,8 +1072,8 @@ public class SecretChatHelper {
}
});
MessagesStorage.getInstance().deleteDialog(did, true);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.removeAllMessagesFromDialog, did);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.removeAllMessagesFromDialog, did);
}
});
return null;
@ -1616,7 +1616,7 @@ public class SecretChatHelper {
}
public void startSecretChat(final Context context, final TLRPC.User user) {
if (user == null) {
if (user == null || context == null) {
return;
}
startingSecretChat = true;

View File

@ -481,6 +481,10 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
sendMessage(null, null, null, null, null, null, user, null, null, null, peer, false, null);
}
public void sendMessage(ArrayList<MessageObject> messages) {
}
public void sendMessage(MessageObject message) {
sendMessage(null, null, null, null, null, message, null, null, null, null, message.getDialogId(), true, message.messageOwner.attachPath);
}
@ -1610,6 +1614,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
try {
Bitmap bitmap = ImageLoader.loadBitmap(f.getAbsolutePath(), null, 90, 90, true);
if (bitmap != null) {
fileName.file_name = "animation.gif";
document.thumb = ImageLoader.scaleAndSaveImage(bitmap, 90, 90, 55, isEncrypted);
}
} catch (Exception e) {
@ -1744,7 +1749,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
document.id = 0;
document.date = ConnectionsManager.getInstance().getCurrentTime();
TLRPC.TL_documentAttributeFilename fileName = new TLRPC.TL_documentAttributeFilename();
fileName.file_name = md5;
fileName.file_name = "animation.gif";
document.attributes.add(fileName);
document.size = searchImage.size;
document.dc_id = 0;
@ -1940,112 +1945,116 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
new Thread(new Runnable() {
@Override
public void run() {
boolean isEncrypted = (int)dialog_id == 0;
String path = videoPath;
String originalPath = videoPath;
File temp = new File(originalPath);
originalPath += temp.length() + "_" + temp.lastModified();
if (videoEditedInfo != null) {
originalPath += duration + "_" + videoEditedInfo.startTime + "_" + videoEditedInfo.endTime;
}
TLRPC.TL_video video = null;
if (!isEncrypted) {
video = (TLRPC.TL_video) MessagesStorage.getInstance().getSentFile(originalPath, !isEncrypted ? 2 : 5);
}
if (video == null) {
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Video.Thumbnails.MINI_KIND);
TLRPC.PhotoSize size = ImageLoader.scaleAndSaveImage(thumb, 90, 90, 55, isEncrypted);
video = new TLRPC.TL_video();
video.thumb = size;
if (video.thumb == null) {
video.thumb = new TLRPC.TL_photoSizeEmpty();
video.thumb.type = "s";
} else {
video.thumb.type = "s";
}
video.caption = "";
video.mime_type = "video/mp4";
video.id = 0;
UserConfig.saveConfig(false);
if (videoEditedInfo != null || videoPath.endsWith("mp4")) {
String path = videoPath;
String originalPath = videoPath;
File temp = new File(originalPath);
originalPath += temp.length() + "_" + temp.lastModified();
if (videoEditedInfo != null) {
video.duration = (int)(duration / 1000);
if (videoEditedInfo.rotationValue == 90 || videoEditedInfo.rotationValue == 270) {
video.w = height;
video.h = width;
originalPath += duration + "_" + videoEditedInfo.startTime + "_" + videoEditedInfo.endTime;
}
TLRPC.TL_video video = null;
if (!isEncrypted) {
video = (TLRPC.TL_video) MessagesStorage.getInstance().getSentFile(originalPath, !isEncrypted ? 2 : 5);
}
if (video == null) {
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Video.Thumbnails.MINI_KIND);
TLRPC.PhotoSize size = ImageLoader.scaleAndSaveImage(thumb, 90, 90, 55, isEncrypted);
video = new TLRPC.TL_video();
video.thumb = size;
if (video.thumb == null) {
video.thumb = new TLRPC.TL_photoSizeEmpty();
video.thumb.type = "s";
} else {
video.w = width;
video.h = height;
video.thumb.type = "s";
}
video.size = (int)estimatedSize;
video.videoEditedInfo = videoEditedInfo;
String fileName = Integer.MIN_VALUE + "_" + UserConfig.lastLocalId + ".mp4";
UserConfig.lastLocalId--;
File cacheFile = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), fileName);
video.caption = "";
video.mime_type = "video/mp4";
video.id = 0;
UserConfig.saveConfig(false);
path = cacheFile.getAbsolutePath();
} else {
if (temp != null && temp.exists()) {
video.size = (int) temp.length();
}
boolean infoObtained = false;
if (Build.VERSION.SDK_INT >= 14) {
MediaMetadataRetriever mediaMetadataRetriever = null;
try {
mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(videoPath);
String width = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
if (width != null) {
video.w = Integer.parseInt(width);
}
String height = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
if (height != null) {
video.h = Integer.parseInt(height);
}
String duration = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
if (duration != null) {
video.duration = (int) Math.ceil(Long.parseLong(duration) / 1000.0f);
}
infoObtained = true;
} catch (Exception e) {
FileLog.e("tmessages", e);
} finally {
if (videoEditedInfo != null) {
video.duration = (int) (duration / 1000);
if (videoEditedInfo.rotationValue == 90 || videoEditedInfo.rotationValue == 270) {
video.w = height;
video.h = width;
} else {
video.w = width;
video.h = height;
}
video.size = (int) estimatedSize;
video.videoEditedInfo = videoEditedInfo;
String fileName = Integer.MIN_VALUE + "_" + UserConfig.lastLocalId + ".mp4";
UserConfig.lastLocalId--;
File cacheFile = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), fileName);
UserConfig.saveConfig(false);
path = cacheFile.getAbsolutePath();
} else {
if (temp != null && temp.exists()) {
video.size = (int) temp.length();
}
boolean infoObtained = false;
if (Build.VERSION.SDK_INT >= 14) {
MediaMetadataRetriever mediaMetadataRetriever = null;
try {
if (mediaMetadataRetriever != null) {
mediaMetadataRetriever.release();
mediaMetadataRetriever = null;
mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(videoPath);
String width = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
if (width != null) {
video.w = Integer.parseInt(width);
}
String height = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
if (height != null) {
video.h = Integer.parseInt(height);
}
String duration = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
if (duration != null) {
video.duration = (int) Math.ceil(Long.parseLong(duration) / 1000.0f);
}
infoObtained = true;
} catch (Exception e) {
FileLog.e("tmessages", e);
} finally {
try {
if (mediaMetadataRetriever != null) {
mediaMetadataRetriever.release();
mediaMetadataRetriever = null;
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
}
if (!infoObtained) {
try {
MediaPlayer mp = MediaPlayer.create(ApplicationLoader.applicationContext, Uri.fromFile(new File(videoPath)));
if (mp != null) {
video.duration = (int) Math.ceil(mp.getDuration() / 1000.0f);
video.w = mp.getVideoWidth();
video.h = mp.getVideoHeight();
mp.release();
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
}
if (!infoObtained) {
try {
MediaPlayer mp = MediaPlayer.create(ApplicationLoader.applicationContext, Uri.fromFile(new File(videoPath)));
if (mp != null) {
video.duration = (int) Math.ceil(mp.getDuration() / 1000.0f);
video.w = mp.getVideoWidth();
video.h = mp.getVideoHeight();
mp.release();
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
final TLRPC.TL_video videoFinal = video;
final String originalPathFinal = originalPath;
final String finalPath = path;
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
SendMessagesHelper.getInstance().sendMessage(videoFinal, originalPathFinal, finalPath, dialog_id);
}
}
});
} else {
prepareSendingDocumentInternal(videoPath, videoPath, null, null, dialog_id);
}
final TLRPC.TL_video videoFinal = video;
final String originalPathFinal = originalPath;
final String finalPath = path;
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
SendMessagesHelper.getInstance().sendMessage(videoFinal, originalPathFinal, finalPath, dialog_id);
}
});
}
}).start();
}

View File

@ -59,7 +59,7 @@ public class MP4Builder {
private long dataOffset = 0;
private long writedSinceLastMdat = 0;
private boolean writeNewMdat = true;
private HashMap<Track, long[]> track2SampleSizes = new HashMap<Track, long[]>();
private HashMap<Track, long[]> track2SampleSizes = new HashMap<>();
private ByteBuffer sizeBuffer = null;
public MP4Builder createMovie(Mp4Movie mp4Movie) throws Exception {
@ -158,7 +158,7 @@ public class MP4Builder {
}
protected FileTypeBox createFileTypeBox() {
LinkedList<String> minorBrands = new LinkedList<String>();
LinkedList<String> minorBrands = new LinkedList<>();
minorBrands.add("isom");
minorBrands.add("3gp4");
return new FileTypeBox("isom", 0, minorBrands);
@ -347,7 +347,7 @@ public class MP4Builder {
protected void createStts(Track track, SampleTableBox stbl) {
TimeToSampleBox.Entry lastEntry = null;
List<TimeToSampleBox.Entry> entries = new ArrayList<TimeToSampleBox.Entry>();
List<TimeToSampleBox.Entry> entries = new ArrayList<>();
for (long delta : track.getSampleDurations()) {
if (lastEntry != null && lastEntry.getDelta() == delta) {
@ -418,7 +418,7 @@ public class MP4Builder {
}
protected void createStco(Track track, SampleTableBox stbl) {
ArrayList<Long> chunksOffsets = new ArrayList<Long>();
ArrayList<Long> chunksOffsets = new ArrayList<>();
long lastOffset = -1;
for (Sample sample : track.getSamples()) {
long offset = sample.getOffset();

View File

@ -8,6 +8,7 @@
package org.telegram.messenger;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
@ -19,6 +20,7 @@ import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
@ -38,10 +40,13 @@ import org.telegram.android.LocaleController;
import org.telegram.android.MessagesController;
import org.telegram.android.NativeLoader;
import org.telegram.android.ScreenReceiver;
import org.telegram.ui.Components.ForegroundDetector;
import java.io.File;
import java.util.concurrent.atomic.AtomicInteger;
public class ApplicationLoader extends Application {
private GoogleCloudMessaging gcm;
private AtomicInteger msgId = new AtomicInteger();
private String regid;
@ -49,15 +54,80 @@ public class ApplicationLoader extends Application {
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static Drawable cachedWallpaper = null;
private static Drawable cachedWallpaper;
private static int selectedColor;
private static boolean isCustomTheme;
private static final Object sync = new Object();
public static volatile Context applicationContext = null;
public static volatile Handler applicationHandler = null;
public static volatile Context applicationContext;
public static volatile Handler applicationHandler;
private static volatile boolean applicationInited = false;
public static volatile boolean isScreenOn = false;
public static volatile boolean mainInterfacePaused = true;
public static boolean isCustomTheme() {
return isCustomTheme;
}
public static int getSelectedColor() {
return selectedColor;
}
public static void reloadWallpaper() {
cachedWallpaper = null;
loadWallpaper();
}
public static void loadWallpaper() {
if (cachedWallpaper != null) {
return;
}
Utilities.searchQueue.postRunnable(new Runnable() {
@Override
public void run() {
synchronized (sync) {
int selectedColor = 0;
try {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
int selectedBackground = preferences.getInt("selectedBackground", 1000001);
selectedColor = preferences.getInt("selectedColor", 0);
int cacheColorHint = 0;
if (selectedColor == 0) {
if (selectedBackground == 1000001) {
cachedWallpaper = applicationContext.getResources().getDrawable(R.drawable.background_hd);
isCustomTheme = false;
} else {
File toFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "wallpaper.jpg");
if (toFile.exists()) {
cachedWallpaper = Drawable.createFromPath(toFile.getAbsolutePath());
isCustomTheme = true;
} else {
cachedWallpaper = applicationContext.getResources().getDrawable(R.drawable.background_hd);
isCustomTheme = false;
}
}
}
} catch (Throwable throwable) {
//ignore
}
if (cachedWallpaper == null) {
if (selectedColor == 0) {
selectedColor = -2693905;
}
cachedWallpaper = new ColorDrawable(selectedColor);
}
}
}
});
}
public static Drawable getCachedWallpaper() {
synchronized (sync) {
return cachedWallpaper;
}
}
public static void postInitApplication() {
if (applicationInited) {
return;
@ -117,6 +187,10 @@ public class ApplicationLoader extends Application {
applicationContext = getApplicationContext();
NativeLoader.initNativeLibs(ApplicationLoader.applicationContext);
if (Build.VERSION.SDK_INT >= 14) {
new ForegroundDetector(this);
}
applicationHandler = new Handler(applicationContext.getMainLooper());
startPushService();

View File

@ -452,7 +452,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
datacenter = new Datacenter();
datacenter.datacenterId = 3;
datacenter.addAddressAndPort("174.140.142.6", 443);
datacenter.addAddressAndPort("149.154.175.100", 443);
datacenters.put(datacenter.datacenterId, datacenter);
datacenter = new Datacenter();
@ -488,7 +488,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
datacenter = new Datacenter();
datacenter.datacenterId = 3;
datacenter.addAddressAndPort("174.140.142.6", 443);
datacenter.addAddressAndPort("149.154.175.100", 443);
datacenters.put(datacenter.datacenterId, datacenter);
datacenter = new Datacenter();
@ -1406,6 +1406,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
if (rawRequest != null && (rawRequest instanceof TLRPC.TL_messages_sendMessage ||
rawRequest instanceof TLRPC.TL_messages_sendMedia ||
rawRequest instanceof TLRPC.TL_messages_forwardMessages ||
rawRequest instanceof TLRPC.TL_messages_forwardMessage ||
rawRequest instanceof TLRPC.TL_messages_sendEncrypted ||
rawRequest instanceof TLRPC.TL_messages_sendEncryptedFile ||
rawRequest instanceof TLRPC.TL_messages_sendEncryptedService)) {
@ -1426,6 +1427,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
if (currentRawRequest instanceof TLRPC.TL_messages_sendMessage ||
currentRawRequest instanceof TLRPC.TL_messages_sendMedia ||
currentRawRequest instanceof TLRPC.TL_messages_forwardMessages ||
currentRawRequest instanceof TLRPC.TL_messages_forwardMessage ||
currentRawRequest instanceof TLRPC.TL_messages_sendEncrypted ||
currentRawRequest instanceof TLRPC.TL_messages_sendEncryptedFile ||
currentRawRequest instanceof TLRPC.TL_messages_sendEncryptedService) {
@ -1438,6 +1440,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
if (request.rawRequest instanceof TLRPC.TL_messages_sendMessage ||
request.rawRequest instanceof TLRPC.TL_messages_sendMedia ||
request.rawRequest instanceof TLRPC.TL_messages_forwardMessages ||
request.rawRequest instanceof TLRPC.TL_messages_forwardMessage ||
request.rawRequest instanceof TLRPC.TL_messages_sendEncrypted ||
request.rawRequest instanceof TLRPC.TL_messages_sendEncryptedFile ||
request.rawRequest instanceof TLRPC.TL_messages_sendEncryptedService) {

View File

@ -638,7 +638,7 @@ public class FileLoader {
continue;
}
int currentSide = obj.w >= obj.h ? obj.w : obj.h;
if (closestObject == null || obj instanceof TLRPC.TL_photoCachedSize || currentSide <= side && lastSide < currentSide) {
if (closestObject == null || side > 100 && closestObject.location != null && closestObject.location.dc_id == Integer.MIN_VALUE || obj instanceof TLRPC.TL_photoCachedSize || currentSide <= side && lastSide < currentSide) {
closestObject = obj;
lastSide = currentSide;
}

View File

@ -31,6 +31,12 @@ public class UserConfig {
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;
public static int autoLockIn = 60 * 60;
public static int lastPauseTime = 0;
public static boolean isWaitingForPasscodeEnter = false;
public static int getNewMessageId() {
int id;
@ -62,6 +68,12 @@ public class UserConfig {
editor.putBoolean("registeredForInternalPush", registeredForInternalPush);
editor.putBoolean("blockedUsersLoaded", blockedUsersLoaded);
editor.putBoolean("waitingForPasswordEnter", waitingForPasswordEnter);
editor.putString("passcodeHash1", passcodeHash);
editor.putBoolean("appLocked", appLocked);
editor.putInt("passcodeType", passcodeType);
editor.putInt("autoLockIn", autoLockIn);
editor.putInt("lastPauseTime", lastPauseTime);
if (currentUser != null) {
if (withFile) {
SerializedData data = new SerializedData();
@ -195,6 +207,11 @@ public class UserConfig {
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);
autoLockIn = preferences.getInt("autoLockIn", 60 * 60);
lastPauseTime = preferences.getInt("lastPauseTime", 0);
String user = preferences.getString("user", null);
if (user != null) {
byte[] userBytes = Base64.decode(user, Base64.DEFAULT);
@ -214,12 +231,17 @@ public class UserConfig {
waitingForPasswordEnter = false;
contactsHash = "";
importHash = "";
lastLocalId = -210000;
lastSendMessageId = -210000;
contactsVersion = 1;
lastBroadcastId = -1;
saveIncomingPhotos = false;
blockedUsersLoaded = false;
appLocked = false;
passcodeType = 0;
passcodeHash = "";
autoLockIn = 60 * 60;
lastPauseTime = 0;
isWaitingForPasscodeEnter = false;
saveConfig(true);
}
}

View File

@ -109,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 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);
public native static Bitmap loadBpgImage(ByteBuffer buffer, int len, BitmapFactory.Options options);
public native static int convertVideoFrame(ByteBuffer src, ByteBuffer dest, int destFormat, int width, int height, int padding, int swap);

View File

@ -94,7 +94,7 @@ public class AccountPasswordActivity extends BaseFragment {
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
if (type == 0) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
@ -271,7 +271,7 @@ public class AccountPasswordActivity extends BaseFragment {
listAdapter.notifyDataSetChanged();
}
private void needShowAlert(final String text) {
private void ShowAlert(final String text) {
if (text == null || getParentActivity() == null) {
return;
}
@ -355,20 +355,20 @@ public class AccountPasswordActivity extends BaseFragment {
String hint = hintPasswordCell.getFieldText();
if (hasPassword) {
if (oldPassword.length() == 0) {
needShowAlert(LocaleController.getString("PasswordOldIncorrect", R.string.PasswordOldIncorrect));
ShowAlert(LocaleController.getString("PasswordOldIncorrect", R.string.PasswordOldIncorrect));
return;
}
}
if (newPassword.length() == 0) {
needShowAlert(LocaleController.getString("PasswordNewIncorrect", R.string.PasswordNewIncorrect));
ShowAlert(LocaleController.getString("PasswordNewIncorrect", R.string.PasswordNewIncorrect));
return;
}
if (!newPassword.equals(verifyPasswrod)) {
needShowAlert(LocaleController.getString("PasswordDoNotMatch", R.string.PasswordDoNotMatch));
ShowAlert(LocaleController.getString("PasswordDoNotMatch", R.string.PasswordDoNotMatch));
return;
}
if (hint.toLowerCase().contains(newPassword.toLowerCase())) {
needShowAlert(LocaleController.getString("HintIncorrect", R.string.HintIncorrect));
ShowAlert(LocaleController.getString("HintIncorrect", R.string.HintIncorrect));
return;
}
byte[] oldPasswordBytes = null;
@ -418,13 +418,13 @@ public class AccountPasswordActivity extends BaseFragment {
finishFragment();
} else {
if (error.text.contains("PASSWORD_HASH_INVALID")) {
needShowAlert(LocaleController.getString("PasswordOldIncorrect", R.string.PasswordOldIncorrect));
ShowAlert(LocaleController.getString("PasswordOldIncorrect", R.string.PasswordOldIncorrect));
} else if (error.text.contains("NEW_PASSWORD_BAD")) {
needShowAlert(LocaleController.getString("PasswordNewIncorrect", R.string.PasswordNewIncorrect));
ShowAlert(LocaleController.getString("PasswordNewIncorrect", R.string.PasswordNewIncorrect));
} else if (error.text.startsWith("FLOOD_WAIT")) {
needShowAlert(LocaleController.getString("FloodWait", R.string.FloodWait));
ShowAlert(LocaleController.getString("FloodWait", R.string.FloodWait));
} else {
needShowAlert(error.text);
ShowAlert(error.text);
}
}
}
@ -434,7 +434,7 @@ public class AccountPasswordActivity extends BaseFragment {
} else if (type == 1) {
String oldPassword = oldPasswordCell.getFieldText();
if (oldPassword.length() == 0) {
needShowAlert(LocaleController.getString("PasswordIncorrect", R.string.PasswordIncorrect));
ShowAlert(LocaleController.getString("PasswordIncorrect", R.string.PasswordIncorrect));
return;
}
byte[] oldPasswordBytes = null;
@ -486,11 +486,11 @@ public class AccountPasswordActivity extends BaseFragment {
}
} else {
if (error.text.contains("PASSWORD_HASH_INVALID")) {
needShowAlert(LocaleController.getString("PasswordOldIncorrect", R.string.PasswordOldIncorrect));
ShowAlert(LocaleController.getString("PasswordOldIncorrect", R.string.PasswordOldIncorrect));
} else if (error.text.startsWith("FLOOD_WAIT")) {
needShowAlert(LocaleController.getString("FloodWait", R.string.FloodWait));
ShowAlert(LocaleController.getString("FloodWait", R.string.FloodWait));
} else {
needShowAlert(error.text);
ShowAlert(error.text);
}
}
}

View File

@ -13,6 +13,7 @@ import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
@ -91,9 +92,9 @@ public class ActionBar extends FrameLayout {
if (titleTextView != null && titleTextView.getVisibility() == VISIBLE) {
if (!AndroidUtilities.isTablet() && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
titleTextView.setTextSize(18);
titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
} else {
titleTextView.setTextSize(20);
titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
}
layoutParams = (LayoutParams) titleTextView.getLayoutParams();
@ -106,9 +107,9 @@ public class ActionBar extends FrameLayout {
}
if (subTitleTextView != null && subTitleTextView.getVisibility() == VISIBLE) {
if (!AndroidUtilities.isTablet() && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
subTitleTextView.setTextSize(14);
subTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
} else {
subTitleTextView.setTextSize(16);
subTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
}
layoutParams = (LayoutParams) subTitleTextView.getLayoutParams();
@ -136,7 +137,7 @@ public class ActionBar extends FrameLayout {
}
if (menu != null) {
maxTextWidth = Math.min(maxTextWidth, width - menu.getMeasuredWidth() - AndroidUtilities.dp(16));
maxTextWidth = Math.min(maxTextWidth, width - menu.getMeasuredWidth() - AndroidUtilities.dp(16) - x);
}
if (titleTextView != null && titleTextView.getVisibility() == VISIBLE) {
@ -173,7 +174,7 @@ public class ActionBar extends FrameLayout {
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams)menu.getLayoutParams();
layoutParams.width = isSearchFieldVisible ? LayoutParams.MATCH_PARENT : LayoutParams.WRAP_CONTENT;
layoutParams.height = height;
layoutParams.leftMargin = isSearchFieldVisible ? AndroidUtilities.dp(54) : 0;
layoutParams.leftMargin = isSearchFieldVisible ? AndroidUtilities.dp(AndroidUtilities.isTablet() ? 74 : 66) : 0;
layoutParams.topMargin = occupyStatusBar ? AndroidUtilities.statusBarHeight : 0;
menu.setLayoutParams(layoutParams);
menu.measure(width, height);
@ -366,7 +367,7 @@ public class ActionBar extends FrameLayout {
return;
}
actionMode.setVisibility(VISIBLE);
if (actionModeTop != null) {
if (occupyStatusBar && actionModeTop != null) {
actionModeTop.setVisibility(VISIBLE);
}
if (titleFrameLayout != null) {
@ -382,7 +383,7 @@ public class ActionBar extends FrameLayout {
return;
}
actionMode.setVisibility(GONE);
if (actionModeTop != null) {
if (occupyStatusBar && actionModeTop != null) {
actionModeTop.setVisibility(GONE);
}
if (titleFrameLayout != null) {
@ -473,6 +474,9 @@ public class ActionBar extends FrameLayout {
public void setOccupyStatusBar(boolean value) {
occupyStatusBar = value;
if (actionMode != null) {
actionMode.setPadding(0, occupyStatusBar ? AndroidUtilities.statusBarHeight : 0, 0, 0);
}
}
public boolean getOccupyStatusBar() {

View File

@ -225,7 +225,7 @@ public class ActionBarLayout extends FrameLayout {
@Override
public boolean dispatchKeyEventPreIme(KeyEvent event) {
if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
return delegate != null && delegate.onPreIme() || super.dispatchKeyEventPreIme(event);
}
return super.dispatchKeyEventPreIme(event);
@ -321,7 +321,7 @@ public class ActionBarLayout extends FrameLayout {
beginTrackingSent = false;
BaseFragment lastFragment = fragmentsStack.get(fragmentsStack.size() - 2);
View fragmentView = lastFragment.createView(parentActivity.getLayoutInflater(), null);
View fragmentView = lastFragment.createView(parentActivity.getLayoutInflater());
ViewGroup parent = (ViewGroup) fragmentView.getParent();
if (parent != null) {
parent.removeView(fragmentView);
@ -502,8 +502,7 @@ public class ActionBarLayout extends FrameLayout {
}
public boolean checkTransitionAnimation() {
if (transitionAnimationInProgress && transitionAnimationStartTime < System.currentTimeMillis() - 400) {
transitionAnimationInProgress = false;
if (transitionAnimationInProgress && transitionAnimationStartTime < System.currentTimeMillis() - 1000) {
onAnimationEndCheck(true);
}
return transitionAnimationInProgress;
@ -556,7 +555,7 @@ 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(), null);
View fragmentView = fragment.createView(parentActivity.getLayoutInflater());
if (fragment.needAddActionBar() && fragment.actionBar != null) {
if (removeActionBarExtraHeight) {
fragment.actionBar.setOccupyStatusBar(false);
@ -585,6 +584,7 @@ public class ActionBarLayout extends FrameLayout {
containerView = containerViewBack;
containerViewBack = temp;
containerView.setVisibility(View.VISIBLE);
setInnerTranslationX(0);
bringChildToFront(containerView);
@ -633,6 +633,8 @@ public class ActionBarLayout extends FrameLayout {
ViewProxy.setTranslationX(containerView, 0);
}
};
ViewProxy.setAlpha(containerView, 0.0f);
ViewProxy.setTranslationX(containerView, 48.0f);
currentAnimation = new AnimatorSetProxy();
currentAnimation.playTogether(
ObjectAnimatorProxy.ofFloat(containerView, "alpha", 0.0f, 1.0f),
@ -640,6 +642,11 @@ public class ActionBarLayout extends FrameLayout {
currentAnimation.setInterpolator(new DecelerateInterpolator(1.5f));
currentAnimation.setDuration(200);
currentAnimation.addListener(new AnimatorListenerAdapterProxy() {
@Override
public void onAnimationStart(Object animation) {
transitionAnimationStartTime = System.currentTimeMillis();
}
@Override
public void onAnimationEnd(Object animation) {
onAnimationEndCheck(false);
@ -672,6 +679,22 @@ public class ActionBarLayout extends FrameLayout {
}
fragment.setParentLayout(this);
if (position == -1) {
if (!fragmentsStack.isEmpty()) {
BaseFragment previousFragment = fragmentsStack.get(fragmentsStack.size() - 1);
previousFragment.onPause();
if (previousFragment.actionBar != null) {
ViewGroup parent = (ViewGroup) previousFragment.actionBar.getParent();
if (parent != null) {
parent.removeView(previousFragment.actionBar);
}
}
if (previousFragment.fragmentView != null) {
ViewGroup parent = (ViewGroup) previousFragment.fragmentView.getParent();
if (parent != null) {
parent.removeView(previousFragment.fragmentView);
}
}
}
fragmentsStack.add(fragment);
} else {
fragmentsStack.add(position, fragment);
@ -689,12 +712,13 @@ public class ActionBarLayout extends FrameLayout {
}
public void closeLastFragment(boolean animated) {
if (delegate != null && !delegate.needCloseLastFragment(this) || checkTransitionAnimation()) {
if (delegate != null && !delegate.needCloseLastFragment(this) || checkTransitionAnimation() || fragmentsStack.isEmpty()) {
return;
}
if (parentActivity.getCurrentFocus() != null) {
AndroidUtilities.hideKeyboard(parentActivity.getCurrentFocus());
}
setInnerTranslationX(0);
boolean needAnimation = Build.VERSION.SDK_INT > 10 && animated && parentActivity.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).getBoolean("view_animations", true);
final BaseFragment currentFragment = fragmentsStack.get(fragmentsStack.size() - 1);
BaseFragment previousFragment = null;
@ -709,7 +733,7 @@ public class ActionBarLayout extends FrameLayout {
containerView.setVisibility(View.VISIBLE);
previousFragment.setParentLayout(this);
View fragmentView = previousFragment.createView(parentActivity.getLayoutInflater(), null);
View fragmentView = previousFragment.createView(parentActivity.getLayoutInflater());
if (previousFragment.needAddActionBar() && previousFragment.actionBar != null) {
if (removeActionBarExtraHeight) {
previousFragment.actionBar.setOccupyStatusBar(false);
@ -754,6 +778,11 @@ public class ActionBarLayout extends FrameLayout {
currentAnimation.setInterpolator(new DecelerateInterpolator(1.5f));
currentAnimation.setDuration(200);
currentAnimation.addListener(new AnimatorListenerAdapterProxy() {
@Override
public void onAnimationStart(Object animation) {
transitionAnimationStartTime = System.currentTimeMillis();
}
@Override
public void onAnimationEnd(Object animation) {
onAnimationEndCheck(false);
@ -796,6 +825,11 @@ public class ActionBarLayout extends FrameLayout {
currentAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
currentAnimation.setDuration(200);
currentAnimation.addListener(new AnimatorListenerAdapterProxy() {
@Override
public void onAnimationStart(Object animation) {
transitionAnimationStartTime = System.currentTimeMillis();
}
@Override
public void onAnimationEnd(Object animation) {
onAnimationEndCheck(false);
@ -823,7 +857,7 @@ public class ActionBarLayout extends FrameLayout {
}
BaseFragment previousFragment = fragmentsStack.get(fragmentsStack.size() - 1);
previousFragment.setParentLayout(this);
View fragmentView = previousFragment.createView(parentActivity.getLayoutInflater(), null);
View fragmentView = previousFragment.createView(parentActivity.getLayoutInflater());
if (previousFragment.needAddActionBar() && previousFragment.actionBar != null) {
if (removeActionBarExtraHeight) {
previousFragment.actionBar.setOccupyStatusBar(false);

View File

@ -348,6 +348,10 @@ public class ActionBarMenuItem extends FrameLayoutFixed {
}
}
public void setIcon(int resId) {
iconView.setImageResource(resId);
}
public EditText getSearchField() {
return searchField;
}
@ -399,7 +403,7 @@ public class ActionBarMenuItem extends FrameLayoutFixed {
searchField.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH || event != null && event.getAction() == KeyEvent.ACTION_UP && event.getKeyCode() == KeyEvent.KEYCODE_SEARCH) {
if (actionId == EditorInfo.IME_ACTION_SEARCH || event != null && (event.getAction() == KeyEvent.ACTION_UP && event.getKeyCode() == KeyEvent.KEYCODE_SEARCH || event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
AndroidUtilities.hideKeyboard(searchField);
if (listener != null) {
listener.onSearchPressed(searchField);

View File

@ -41,7 +41,7 @@ public class BaseFragment {
classGuid = ConnectionsManager.getInstance().generateClassGuid();
}
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
return null;
}
@ -76,7 +76,7 @@ public class BaseFragment {
if (parentLayout != null) {
actionBar = new ActionBar(parentLayout.getContext());
actionBar.parentFragment = this;
actionBar.setBackgroundResource(R.color.header);
actionBar.setBackgroundColor(0xff54759e);
actionBar.setItemsBackground(R.drawable.bar_selector);
}
}

View File

@ -165,6 +165,9 @@ public class DrawerLayoutContainer extends FrameLayout {
}
public void openDrawer(boolean fast) {
if (!allowOpenDrawer) {
return;
}
if (AndroidUtilities.isTablet() && parentActionBarLayout != null && parentActionBarLayout.parentActivity != null) {
AndroidUtilities.hideKeyboard(parentActionBarLayout.parentActivity.getCurrentFocus());
}

View File

@ -124,10 +124,14 @@ public class ContactsSearchAdapter extends BaseContactsSearchAdapter {
}
String name = ContactsController.formatName(user.first_name, user.last_name).toLowerCase();
String tName = LocaleController.getInstance().getTranslitString(name);
if (name.equals(tName)) {
tName = null;
}
int found = 0;
for (String q : search) {
if (name.startsWith(q) || name.contains(" " + q)) {
if (name.startsWith(q) || name.contains(" " + q) || tName != null && (tName.startsWith(q) || tName.contains(" " + q))) {
found = 1;
} else if (user.username != null && user.username.startsWith(q)) {
found = 2;

View File

@ -13,7 +13,6 @@ import android.view.View;
import android.view.ViewGroup;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.MessageObject;
import org.telegram.android.MessagesController;
import org.telegram.messenger.TLRPC;
import org.telegram.ui.Cells.DialogCell;
@ -24,6 +23,7 @@ public class DialogsAdapter extends BaseFragmentAdapter {
private Context mContext;
private boolean serverOnly;
private long openedDialogId;
private int currentCount;
public DialogsAdapter(Context context, boolean onlyFromServer) {
mContext = context;
@ -34,6 +34,11 @@ public class DialogsAdapter extends BaseFragmentAdapter {
openedDialogId = id;
}
public boolean isDataSetChanged() {
int current = currentCount;
return current != getCount();
}
@Override
public boolean areAllItemsEnabled() {
return true;
@ -58,6 +63,7 @@ public class DialogsAdapter extends BaseFragmentAdapter {
if (!MessagesController.getInstance().dialogsEndReached) {
count++;
}
currentCount = count;
return count;
}
@ -97,22 +103,23 @@ public class DialogsAdapter extends BaseFragmentAdapter {
if (view == null) {
view = new DialogCell(mContext);
}
((DialogCell) view).useSeparator = (i != getCount() - 1);
TLRPC.TL_dialog dialog = null;
if (serverOnly) {
dialog = MessagesController.getInstance().dialogsServerOnly.get(i);
} else {
dialog = MessagesController.getInstance().dialogs.get(i);
if (AndroidUtilities.isTablet()) {
if (dialog.id == openedDialogId) {
view.setBackgroundColor(0x0f000000);
} else {
view.setBackgroundColor(0);
if (view instanceof DialogCell) { //TODO finally i need to find this crash
((DialogCell) view).useSeparator = (i != getCount() - 1);
TLRPC.TL_dialog dialog = null;
if (serverOnly) {
dialog = MessagesController.getInstance().dialogsServerOnly.get(i);
} else {
dialog = MessagesController.getInstance().dialogs.get(i);
if (AndroidUtilities.isTablet()) {
if (dialog.id == openedDialogId) {
view.setBackgroundColor(0x0f000000);
} else {
view.setBackgroundColor(0);
}
}
}
((DialogCell) view).setDialog(dialog, i, serverOnly);
}
MessageObject message = MessagesController.getInstance().dialogMessage.get(dialog.top_message);
((DialogCell) view).setDialog(dialog.id, message, true, dialog.last_message_date, dialog.unread_count, MessagesController.getInstance().isDialogMuted(dialog.id));
}
return view;
@ -133,9 +140,6 @@ public class DialogsAdapter extends BaseFragmentAdapter {
@Override
public boolean isEmpty() {
if (MessagesController.getInstance().loadingDialogs && MessagesController.getInstance().dialogs.isEmpty()) {
return true;
}
int count;
if (serverOnly) {
count = MessagesController.getInstance().dialogsServerOnly.size();

View File

@ -215,6 +215,10 @@ public class DialogsSearchAdapter extends BaseContactsSearchAdapter {
cursor = MessagesStorage.getInstance().getDatabase().queryFinalized(String.format(Locale.US, "SELECT data, status, name FROM users WHERE uid IN(%s)", TextUtils.join(",", usersToLoad)));
while (cursor.next()) {
String name = cursor.stringValue(2);
String tName = LocaleController.getInstance().getTranslitString(name);
if (name.equals(tName)) {
tName = null;
}
String username = null;
int usernamePos = name.lastIndexOf(";;;");
if (usernamePos != -1) {
@ -222,7 +226,7 @@ public class DialogsSearchAdapter extends BaseContactsSearchAdapter {
}
int found = 0;
for (String q : search) {
if (name.startsWith(q) || name.contains(" " + q)) {
if (name.startsWith(q) || name.contains(" " + q) || tName != null && (tName.startsWith(q) || tName.contains(" " + q))) {
found = 1;
} else if (username != null && username.startsWith(q)) {
found = 2;
@ -257,8 +261,12 @@ public class DialogsSearchAdapter extends BaseContactsSearchAdapter {
cursor = MessagesStorage.getInstance().getDatabase().queryFinalized(String.format(Locale.US, "SELECT data, name FROM chats WHERE uid IN(%s)", TextUtils.join(",", chatsToLoad)));
while (cursor.next()) {
String name = cursor.stringValue(1);
String tName = LocaleController.getInstance().getTranslitString(name);
if (name.equals(tName)) {
tName = null;
}
for (String q : search) {
if (name.startsWith(q) || name.contains(" " + q)) {
if (name.startsWith(q) || name.contains(" " + q) || tName != null && (tName.startsWith(q) || tName.contains(" " + q))) {
ByteBufferDesc data = MessagesStorage.getInstance().getBuffersStorage().getFreeBuffer(cursor.byteArrayLength(0));
if (data != null && cursor.byteBufferValue(0, data.buffer) != 0) {
TLRPC.Chat chat = (TLRPC.Chat) TLClassStore.Instance().TLdeserialize(data, data.readInt32());
@ -285,6 +293,10 @@ public class DialogsSearchAdapter extends BaseContactsSearchAdapter {
cursor = MessagesStorage.getInstance().getDatabase().queryFinalized(String.format(Locale.US, "SELECT q.data, u.name, q.user, q.g, q.authkey, q.ttl, u.data, u.status, q.layer, q.seq_in, q.seq_out, q.use_count, q.exchange_id, q.key_date, q.fprint, q.fauthkey, q.khash FROM enc_chats as q INNER JOIN users as u ON q.user = u.uid WHERE q.uid IN(%s)", TextUtils.join(",", encryptedToLoad)));
while (cursor.next()) {
String name = cursor.stringValue(1);
String tName = LocaleController.getInstance().getTranslitString(name);
if (name.equals(tName)) {
tName = null;
}
String username = null;
int usernamePos = name.lastIndexOf(";;;");
@ -293,7 +305,7 @@ public class DialogsSearchAdapter extends BaseContactsSearchAdapter {
}
int found = 0;
for (String q : search) {
if (name.startsWith(q) || name.contains(" " + q)) {
if (name.startsWith(q) || name.contains(" " + q) || tName != null && (tName.startsWith(q) || tName.contains(" " + q))) {
found = 1;
} else if (username != null && username.startsWith(q)) {
found = 2;
@ -378,6 +390,10 @@ public class DialogsSearchAdapter extends BaseContactsSearchAdapter {
continue;
}
String name = cursor.stringValue(2);
String tName = LocaleController.getInstance().getTranslitString(name);
if (name.equals(tName)) {
tName = null;
}
String username = null;
int usernamePos = name.lastIndexOf(";;;");
if (usernamePos != -1) {
@ -385,7 +401,7 @@ public class DialogsSearchAdapter extends BaseContactsSearchAdapter {
}
int found = 0;
for (String q : search) {
if (name.startsWith(q) || name.contains(" " + q)) {
if (name.startsWith(q) || name.contains(" " + q) || tName != null && (tName.startsWith(q) || tName.contains(" " + q))) {
found = 1;
} else if (username != null && username.startsWith(q)) {
found = 2;
@ -618,7 +634,7 @@ public class DialogsSearchAdapter extends BaseContactsSearchAdapter {
}
((DialogCell) view).useSeparator = (i != getCount() - 1);
MessageObject messageObject = (MessageObject)getItem(i);
((DialogCell) view).setDialog(messageObject.getDialogId(), messageObject, false, messageObject.messageOwner.date, 0, false);
((DialogCell) view).setDialog(messageObject.getDialogId(), messageObject, messageObject.messageOwner.date);
} else if (type == 3) {
if (view == null) {
view = new LoadingCell(mContext);

View File

@ -203,6 +203,9 @@ public class StickersAdapter extends RecyclerView.Adapter implements Notificatio
}
HashMap<Long, TLRPC.Document> documents = new HashMap<>();
for (TLRPC.Document document : res.documents) {
if (document == null) {
continue;
}
documents.put(document.id, document);
if (document.thumb != null && document.thumb.location != null) {
document.thumb.location.ext = "webp";

View File

@ -25,10 +25,10 @@ import java.util.List;
public final class AnimatorSet10 extends Animator10 {
private ArrayList<Animator10> mPlayingSet = new ArrayList<Animator10>();
private HashMap<Animator10, Node> mNodeMap = new HashMap<Animator10, Node>();
private ArrayList<Node> mNodes = new ArrayList<Node>();
private ArrayList<Node> mSortedNodes = new ArrayList<Node>();
private ArrayList<Animator10> mPlayingSet = new ArrayList<>();
private HashMap<Animator10, Node> mNodeMap = new HashMap<>();
private ArrayList<Node> mNodes = new ArrayList<>();
private ArrayList<Node> mSortedNodes = new ArrayList<>();
private boolean mNeedsSort = true;
private AnimatorSetListener mSetListener = null;
boolean mTerminated = false;
@ -89,7 +89,7 @@ public final class AnimatorSet10 extends Animator10 {
}
public ArrayList<Animator10> getChildAnimations() {
ArrayList<Animator10> childList = new ArrayList<Animator10>();
ArrayList<Animator10> childList = new ArrayList<>();
for (Node node : mNodes) {
childList.add(node.animation);
}
@ -295,7 +295,7 @@ public final class AnimatorSet10 extends Animator10 {
ArrayList<AnimatorListener> oldListeners = node.animation.getListeners();
if (oldListeners != null && oldListeners.size() > 0) {
final ArrayList<AnimatorListener> clonedListeners = new
ArrayList<AnimatorListener>(oldListeners);
ArrayList<>(oldListeners);
for (AnimatorListener listener : clonedListeners) {
if (listener instanceof DependencyListener ||
@ -306,7 +306,7 @@ public final class AnimatorSet10 extends Animator10 {
}
}
final ArrayList<Node> nodesToStart = new ArrayList<Node>();
final ArrayList<Node> nodesToStart = new ArrayList<>();
for (Node node : mSortedNodes) {
if (mSetListener == null) {
mSetListener = new AnimatorSetListener(this);
@ -379,12 +379,12 @@ public final class AnimatorSet10 extends Animator10 {
anim.mNeedsSort = true;
anim.mTerminated = false;
anim.mStarted = false;
anim.mPlayingSet = new ArrayList<Animator10>();
anim.mNodeMap = new HashMap<Animator10, Node>();
anim.mNodes = new ArrayList<Node>();
anim.mSortedNodes = new ArrayList<Node>();
anim.mPlayingSet = new ArrayList<>();
anim.mNodeMap = new HashMap<>();
anim.mNodes = new ArrayList<>();
anim.mSortedNodes = new ArrayList<>();
HashMap<Node, Node> nodeCloneMap = new HashMap<Node, Node>();
HashMap<Node, Node> nodeCloneMap = new HashMap<>();
for (Node node : mNodes) {
Node nodeClone = node.clone();
nodeCloneMap.put(node, nodeClone);
@ -400,7 +400,7 @@ public final class AnimatorSet10 extends Animator10 {
for (AnimatorListener listener : cloneListeners) {
if (listener instanceof AnimatorSetListener) {
if (listenersToRemove == null) {
listenersToRemove = new ArrayList<AnimatorListener>();
listenersToRemove = new ArrayList<>();
}
listenersToRemove.add(listener);
}
@ -543,14 +543,14 @@ public final class AnimatorSet10 extends Animator10 {
private void sortNodes() {
if (mNeedsSort) {
mSortedNodes.clear();
ArrayList<Node> roots = new ArrayList<Node>();
ArrayList<Node> roots = new ArrayList<>();
int numNodes = mNodes.size();
for (Node node : mNodes) {
if (node.dependencies == null || node.dependencies.size() == 0) {
roots.add(node);
}
}
ArrayList<Node> tmpRoots = new ArrayList<Node>();
ArrayList<Node> tmpRoots = new ArrayList<>();
while (roots.size() > 0) {
int numRoots = roots.size();
for (Node root : roots) {
@ -582,7 +582,7 @@ public final class AnimatorSet10 extends Animator10 {
for (int j = 0; j < numDependencies; ++j) {
Dependency dependency = node.dependencies.get(j);
if (node.nodeDependencies == null) {
node.nodeDependencies = new ArrayList<Node>();
node.nodeDependencies = new ArrayList<>();
}
if (!node.nodeDependencies.contains(dependency.node)) {
node.nodeDependencies.add(dependency.node);
@ -620,8 +620,8 @@ public final class AnimatorSet10 extends Animator10 {
public void addDependency(Dependency dependency) {
if (dependencies == null) {
dependencies = new ArrayList<Dependency>();
nodeDependencies = new ArrayList<Node>();
dependencies = new ArrayList<>();
nodeDependencies = new ArrayList<>();
}
dependencies.add(dependency);
if (!nodeDependencies.contains(dependency.node)) {
@ -629,7 +629,7 @@ public final class AnimatorSet10 extends Animator10 {
}
Node dependencyNode = dependency.node;
if (dependencyNode.nodeDependents == null) {
dependencyNode.nodeDependents = new ArrayList<Node>();
dependencyNode.nodeDependents = new ArrayList<>();
}
dependencyNode.nodeDependents.add(this);
}

View File

@ -31,7 +31,7 @@ public class View10 extends Animation {
public static boolean NEED_PROXY = Build.VERSION.SDK_INT < 11;
private static final WeakHashMap<View, View10> PROXIES = new WeakHashMap<View, View10>();
private static final WeakHashMap<View, View10> PROXIES = new WeakHashMap<>();
public static View10 wrap(View view) {
View10 proxy = PROXIES.get(view);
@ -68,7 +68,7 @@ public class View10 extends Animation {
setDuration(0);
setFillAfter(true);
view.setAnimation(this);
mView = new WeakReference<View>(view);
mView = new WeakReference<>(view);
}
public float getAlpha() {

View File

@ -64,7 +64,7 @@ public class BlockedUsersActivity extends BaseFragment implements NotificationCe
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);

View File

@ -574,9 +574,9 @@ public class ChatBaseCell extends BaseCell {
if (drawCheck2) {
if (!media) {
if (drawCheck1) {
setDrawableBounds(checkDrawable, layoutWidth - AndroidUtilities.dp(22.5f) - checkDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dp(8.5f) - checkDrawable.getIntrinsicHeight());
setDrawableBounds(checkDrawable, layoutWidth - AndroidUtilities.dp(22.5f) - checkDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dp(8.0f) - checkDrawable.getIntrinsicHeight());
} else {
setDrawableBounds(checkDrawable, layoutWidth - AndroidUtilities.dp(18.5f) - checkDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dp(8.5f) - checkDrawable.getIntrinsicHeight());
setDrawableBounds(checkDrawable, layoutWidth - AndroidUtilities.dp(18.5f) - checkDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dp(8.0f) - checkDrawable.getIntrinsicHeight());
}
checkDrawable.draw(canvas);
} else {
@ -590,7 +590,7 @@ public class ChatBaseCell extends BaseCell {
}
if (drawCheck1) {
if (!media) {
setDrawableBounds(halfCheckDrawable, layoutWidth - AndroidUtilities.dp(18) - halfCheckDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dp(8.5f) - halfCheckDrawable.getIntrinsicHeight());
setDrawableBounds(halfCheckDrawable, layoutWidth - AndroidUtilities.dp(18) - halfCheckDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dp(8.0f) - halfCheckDrawable.getIntrinsicHeight());
halfCheckDrawable.draw(canvas);
} else {
setDrawableBounds(halfCheckMediaDrawable, layoutWidth - AndroidUtilities.dp(20.5f) - halfCheckMediaDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dp(13.0f) - halfCheckMediaDrawable.getIntrinsicHeight());

View File

@ -530,19 +530,14 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
break;
}
}
float maxWidth;
if (AndroidUtilities.isTablet()) {
maxWidth = (int) (AndroidUtilities.getMinTabletSide() * 0.5f);
} else {
maxWidth = (int) (Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) * 0.5f);
}
float maxHeight = AndroidUtilities.displaySize.y * 0.4f;
if (photoWidth == 0) {
photoWidth = (int)maxWidth;
photoHeight = photoWidth + AndroidUtilities.dp(100);
photoHeight = (int) maxHeight;
photoWidth = photoHeight + AndroidUtilities.dp(100);
}
if (photoWidth > maxWidth) {
photoHeight *= maxWidth / photoWidth;
photoWidth = (int)maxWidth;
if (photoHeight > maxHeight) {
photoWidth *= maxHeight / photoHeight;
photoHeight = (int)maxHeight;
}
backgroundWidth = photoWidth + AndroidUtilities.dp(12);
currentPhotoObjectThumb = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, 80);
@ -870,8 +865,8 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
if (currentMessageObject.type == 9) {
Drawable menuDrawable = null;
if (currentMessageObject.isOut()) {
infoPaint.setColor(0xff75b166);
docBackPaint.setColor(0xffd0f3b3);
infoPaint.setColor(0xff70b15c);
docBackPaint.setColor(0xffdaf5c3);
menuDrawable = docMenuOutDrawable;
} else {
infoPaint.setColor(0xffa1adbb);

View File

@ -55,12 +55,15 @@ public class DialogCell extends BaseCell {
private static Paint linePaint;
private long currentDialogId;
private boolean allowPrintStrings;
private boolean isDialogCell;
private int lastMessageDate;
private int unreadCount;
private boolean lastUnreadState;
private int lastSendState;
private boolean dialogMuted;
private MessageObject message;
private int index;
private boolean isServerOnly;
private ImageReceiver avatarImage;
private AvatarDrawable avatarDrawable;
@ -166,14 +169,24 @@ public class DialogCell extends BaseCell {
avatarDrawable = new AvatarDrawable();
}
public void setDialog(long dialog_id, MessageObject messageObject, boolean usePrintStrings, int date, int unread, boolean muted) {
public void setDialog(TLRPC.TL_dialog dialog, int i, boolean server) {
currentDialogId = dialog.id;
isDialogCell = true;
index = i;
isServerOnly = server;
update(0);
}
public void setDialog(long dialog_id, MessageObject messageObject, int date) {
currentDialogId = dialog_id;
message = messageObject;
allowPrintStrings = usePrintStrings;
isDialogCell = false;
lastMessageDate = date;
unreadCount = unread;
dialogMuted = muted;
unreadCount = 0;
lastUnreadState = messageObject != null && messageObject.isUnread();
if (message != null) {
lastSendState = message.messageOwner.send_state;
}
update(0);
}
@ -211,7 +224,7 @@ public class DialogCell extends BaseCell {
String countString = null;
CharSequence messageString = "";
CharSequence printingString = null;
if (allowPrintStrings) {
if (isDialogCell) {
printingString = MessagesController.getInstance().printingStrings.get(currentDialogId);
}
TextPaint currentNamePaint = namePaint;
@ -543,15 +556,15 @@ public class DialogCell extends BaseCell {
if (LocaleController.isRTL) {
if (nameLayout != null && nameLayout.getLineCount() > 0) {
left = nameLayout.getLineLeft(0);
widthpx = Math.ceil(nameLayout.getLineWidth(0));
if (dialogMuted) {
nameMuteLeft = (int) (nameLeft + (nameWidth - widthpx) - AndroidUtilities.dp(6) - muteDrawable.getIntrinsicWidth());
}
if (left == 0) {
widthpx = Math.ceil(nameLayout.getLineWidth(0));
if (widthpx < nameWidth) {
nameLeft += (nameWidth - widthpx);
}
}
if (dialogMuted) {
nameMuteLeft = (nameLeft - AndroidUtilities.dp(6) - muteDrawable.getIntrinsicWidth());
}
}
if (messageLayout != null && messageLayout.getLineCount() > 0) {
left = messageLayout.getLineLeft(0);
@ -587,10 +600,37 @@ public class DialogCell extends BaseCell {
}
}
public void checkCurrentDialogIndex() {
TLRPC.TL_dialog dialog = null;
if (isServerOnly) {
dialog = MessagesController.getInstance().dialogsServerOnly.get(index);
} else {
dialog = MessagesController.getInstance().dialogs.get(index);
}
boolean update = true;
if (currentDialogId != dialog.id || message != null && message.messageOwner.id != dialog.top_message || unreadCount != dialog.unread_count) {
currentDialogId = dialog.id;
update(0);
}
}
public void update(int mask) {
if (isDialogCell) {
TLRPC.TL_dialog dialog = MessagesController.getInstance().dialogs_dict.get(currentDialogId);
if (dialog != null && mask == 0) {
message = MessagesController.getInstance().dialogMessage.get(dialog.top_message);
lastUnreadState = message != null && message.isUnread();
unreadCount = dialog.unread_count;
lastMessageDate = dialog.last_message_date;
if (message != null) {
lastSendState = message.messageOwner.send_state;
}
}
}
if (mask != 0) {
boolean continueUpdate = false;
if (allowPrintStrings && (mask & MessagesController.UPDATE_MASK_USER_PRINT) != 0) {
if (isDialogCell && (mask & MessagesController.UPDATE_MASK_USER_PRINT) != 0) {
CharSequence printString = MessagesController.getInstance().printingStrings.get(currentDialogId);
if (lastPrintString != null && printString == null || lastPrintString == null && printString != null || lastPrintString != null && printString != null && !lastPrintString.equals(printString)) {
continueUpdate = true;
@ -618,8 +658,9 @@ public class DialogCell extends BaseCell {
}
if (!continueUpdate && (mask & MessagesController.UPDATE_MASK_READ_DIALOG_MESSAGE) != 0) {
if (message != null && lastUnreadState != message.isUnread()) {
lastUnreadState = message.isUnread();
continueUpdate = true;
} else if (allowPrintStrings) {
} else if (isDialogCell) {
TLRPC.TL_dialog dialog = MessagesController.getInstance().dialogs_dict.get(currentDialogId);
if (dialog != null && unreadCount != dialog.unread_count) {
unreadCount = dialog.unread_count;
@ -627,11 +668,19 @@ public class DialogCell extends BaseCell {
}
}
}
if (!continueUpdate && (mask & MessagesController.UPDATE_MASK_SEND_STATE) != 0) {
if (message != null && lastSendState != message.messageOwner.send_state) {
lastSendState = message.messageOwner.send_state;
continueUpdate = true;
}
}
if (!continueUpdate) {
return;
}
}
dialogMuted = isDialogCell && MessagesController.getInstance().isDialogMuted(currentDialogId);
user = null;
chat = null;
encryptedChat = null;

View File

@ -9,7 +9,6 @@
package org.telegram.ui.Cells;
import android.content.Context;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.FrameLayout;
@ -21,7 +20,9 @@ import org.telegram.android.LocaleController;
public class GreySectionCell extends FrameLayout {
private TextView textView;
private void init() {
public GreySectionCell(Context context) {
super(context);
setBackgroundColor(0xfff2f2f2);
textView = new TextView(getContext());
@ -39,26 +40,6 @@ public class GreySectionCell extends FrameLayout {
textView.setLayoutParams(layoutParams);
}
public GreySectionCell(Context context) {
super(context);
init();
}
public GreySectionCell(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public GreySectionCell(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public GreySectionCell(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(36), MeasureSpec.EXACTLY));

View File

@ -9,6 +9,7 @@
package org.telegram.ui.Cells;
import android.content.Context;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.ImageView;
@ -32,28 +33,54 @@ public class PhotoEditToolCell extends FrameLayoutFixed {
LayoutParams layoutParams = (LayoutParams) iconImage.getLayoutParams();
layoutParams.width = LayoutParams.MATCH_PARENT;
layoutParams.height = LayoutParams.MATCH_PARENT;
layoutParams.bottomMargin = AndroidUtilities.dp(20);
layoutParams.bottomMargin = AndroidUtilities.dp(12);
iconImage.setLayoutParams(layoutParams);
nameTextView = new TextView(context);
nameTextView.setGravity(Gravity.CENTER);
nameTextView.setTextColor(0xffffffff);
nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10);
nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
nameTextView.setMaxLines(1);
nameTextView.setSingleLine(true);
nameTextView.setEllipsize(TextUtils.TruncateAt.END);
addView(nameTextView);
layoutParams = (LayoutParams) nameTextView.getLayoutParams();
layoutParams.width = LayoutParams.MATCH_PARENT;
layoutParams.height = AndroidUtilities.dp(20);
layoutParams.height = LayoutParams.WRAP_CONTENT;
layoutParams.gravity = Gravity.LEFT | Gravity.BOTTOM;
layoutParams.leftMargin = AndroidUtilities.dp(4);
layoutParams.rightMargin = AndroidUtilities.dp(4);
nameTextView.setLayoutParams(layoutParams);
valueTextView = new TextView(context);
valueTextView.setTextColor(0xff6cc3ff);
valueTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 11);
valueTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
addView(valueTextView);
layoutParams = (LayoutParams) valueTextView.getLayoutParams();
layoutParams.width = LayoutParams.WRAP_CONTENT;
layoutParams.height = LayoutParams.WRAP_CONTENT;
layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
layoutParams.leftMargin = AndroidUtilities.dp(57);
layoutParams.topMargin = AndroidUtilities.dp(3);
valueTextView.setLayoutParams(layoutParams);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(80), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(60), MeasureSpec.EXACTLY));
super.onMeasure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(86), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(60), MeasureSpec.EXACTLY));
}
public void setIconAndText(int resId, String text) {
public void setIconAndTextAndValue(int resId, String text, float value) {
iconImage.setImageResource(resId);
nameTextView.setText(text);
nameTextView.setText(text.toUpperCase());
if (value == 0) {
valueTextView.setText("");
} else if (value > 0) {
valueTextView.setText("+" + (int) value);
} else {
valueTextView.setText("" + (int) value);
}
}
}

View File

@ -15,7 +15,7 @@ import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
@ -23,8 +23,9 @@ import org.telegram.android.AndroidUtilities;
import org.telegram.android.MediaController;
import org.telegram.messenger.R;
import org.telegram.ui.Components.BackupImageView;
import org.telegram.ui.Components.FrameLayoutFixed;
public class PhotoPickerAlbumsCell extends FrameLayout {
public class PhotoPickerAlbumsCell extends FrameLayoutFixed {
public static interface PhotoPickerAlbumsCellDelegate {
public abstract void didSelectAlbum(MediaController.AlbumEntry albumEntry);
@ -35,7 +36,7 @@ public class PhotoPickerAlbumsCell extends FrameLayout {
private int albumsCount;
private PhotoPickerAlbumsCellDelegate delegate;
private class AlbumView extends FrameLayout {
private class AlbumView extends FrameLayoutFixed {
private BackupImageView imageView;
private TextView nameTextView;
@ -146,7 +147,9 @@ public class PhotoPickerAlbumsCell extends FrameLayout {
if (albumEntry != null) {
AlbumView albumView = albumViews[a];
albumView.imageView.setOrientation(0, true);
if (albumEntry.coverPhoto != null && albumEntry.coverPhoto.path != null) {
albumView.imageView.setOrientation(albumEntry.coverPhoto.orientation, true);
albumView.imageView.setImage("thumb://" + albumEntry.coverPhoto.imageId + ":" + albumEntry.coverPhoto.path, null, getContext().getResources().getDrawable(R.drawable.nophotos));
} else {
albumView.imageView.setImageResource(R.drawable.nophotos);
@ -167,16 +170,21 @@ public class PhotoPickerAlbumsCell extends FrameLayout {
itemWidth = (AndroidUtilities.displaySize.x - ((albumsCount + 1) * AndroidUtilities.dp(4))) / albumsCount;
}
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(4) + itemWidth, MeasureSpec.EXACTLY));
for (int a = 0; a < albumsCount; a++) {
LayoutParams layoutParams = (LayoutParams) albumViews[a].getLayoutParams();
layoutParams.topMargin = AndroidUtilities.dp(4);
layoutParams.leftMargin = (itemWidth + AndroidUtilities.dp(4)) * a;
layoutParams.width = itemWidth;
layoutParams.height = itemWidth;
layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
albumViews[a].setLayoutParams(layoutParams);
albumViews[a].measure(MeasureSpec.makeMeasureSpec(itemWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(itemWidth, MeasureSpec.EXACTLY));
}
ViewGroup.LayoutParams layoutParams = getLayoutParams();
if (layoutParams != null) {
layoutParams.height = AndroidUtilities.dp(4) + itemWidth;
setLayoutParams(layoutParams);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}

View File

@ -11,7 +11,6 @@ package org.telegram.ui.Cells;
import android.content.Context;
import android.view.Gravity;
import android.widget.FrameLayout;
import android.widget.ImageView;
import org.telegram.android.AndroidUtilities;
import org.telegram.messenger.R;
@ -23,7 +22,6 @@ public class PhotoPickerPhotoCell extends FrameLayout {
public BackupImageView photoImage;
public FrameLayout checkFrame;
public CheckBox checkBox;
public ImageView editedImage;
public int itemWidth;
public PhotoPickerPhotoCell(Context context) {
@ -57,16 +55,6 @@ public class PhotoPickerPhotoCell extends FrameLayout {
layoutParams.topMargin = AndroidUtilities.dp(6);
layoutParams.rightMargin = AndroidUtilities.dp(6);
checkBox.setLayoutParams(layoutParams);
editedImage = new ImageView(context);
editedImage.setImageResource(R.drawable.photo_edit);
editedImage.setScaleType(ImageView.ScaleType.CENTER);
addView(editedImage);
layoutParams = (LayoutParams) editedImage.getLayoutParams();
layoutParams.width = AndroidUtilities.dp(42);
layoutParams.height = AndroidUtilities.dp(42);
layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
editedImage.setLayoutParams(layoutParams);
}
@Override

View File

@ -10,6 +10,7 @@ package org.telegram.ui.Cells;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
@ -39,62 +40,57 @@ public class PhotoPickerSearchCell extends LinearLayout {
public SearchButton(Context context) {
super(context);
setBackgroundColor(0xff292929);
setBackgroundColor(0xff1a1a1a);
selector = new View(context);
selector.setBackgroundResource(R.drawable.list_selector);
addView(selector);
FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) selector.getLayoutParams();
layoutParams1.width = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams1.height = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams1.width = LayoutParams.MATCH_PARENT;
layoutParams1.height = LayoutParams.MATCH_PARENT;
selector.setLayoutParams(layoutParams1);
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setOrientation(HORIZONTAL);
addView(linearLayout);
layoutParams1 = (FrameLayout.LayoutParams) linearLayout.getLayoutParams();
layoutParams1.width = FrameLayout.LayoutParams.WRAP_CONTENT;
layoutParams1.height = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams1.gravity = Gravity.CENTER;
linearLayout.setLayoutParams(layoutParams1);
imageView = new ImageView(context);
linearLayout.addView(imageView);
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) imageView.getLayoutParams();
layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
imageView.setScaleType(ImageView.ScaleType.CENTER);
addView(imageView);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) imageView.getLayoutParams();
layoutParams.height = AndroidUtilities.dp(48);
layoutParams.width = AndroidUtilities.dp(48);
layoutParams1.gravity = Gravity.LEFT | Gravity.TOP;
imageView.setLayoutParams(layoutParams);
FrameLayout frameLayout = new FrameLayout(context);
frameLayout.setPadding(AndroidUtilities.dp(4), 0, 0, 0);
linearLayout.addView(frameLayout);
layoutParams = (LinearLayout.LayoutParams) frameLayout.getLayoutParams();
layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT;
layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
frameLayout.setLayoutParams(layoutParams);
textView1 = new TextView(context);
textView1.setGravity(Gravity.CENTER_VERTICAL);
textView1.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
textView1.setPadding(0, 0, AndroidUtilities.dp(8), 0);
textView1.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView1.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
textView1.setTextColor(0xffffffff);
frameLayout.addView(textView1);
textView1.setSingleLine(true);
textView1.setEllipsize(TextUtils.TruncateAt.END);
addView(textView1);
layoutParams1 = (FrameLayout.LayoutParams) textView1.getLayoutParams();
layoutParams1.width = FrameLayout.LayoutParams.WRAP_CONTENT;
layoutParams1.height = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams1.width = LayoutParams.MATCH_PARENT;
layoutParams1.height = LayoutParams.WRAP_CONTENT;
layoutParams1.gravity = Gravity.TOP | Gravity.LEFT;
layoutParams1.rightMargin = AndroidUtilities.dp(4);
layoutParams1.leftMargin = AndroidUtilities.dp(51);
layoutParams1.topMargin = AndroidUtilities.dp(8);
textView1.setLayoutParams(layoutParams1);
textView2 = new TextView(context);
textView2.setGravity(Gravity.CENTER_VERTICAL);
textView2.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 9);
textView2.setPadding(0, AndroidUtilities.dp(24), AndroidUtilities.dp(8), 0);
textView2.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10);
textView2.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
textView2.setTextColor(0xff464646);
frameLayout.addView(textView2);
textView2.setTextColor(0xff666666);
textView2.setSingleLine(true);
textView2.setEllipsize(TextUtils.TruncateAt.END);
addView(textView2);
layoutParams1 = (FrameLayout.LayoutParams) textView2.getLayoutParams();
layoutParams1.width = FrameLayout.LayoutParams.WRAP_CONTENT;
layoutParams1.height = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams1.width = LayoutParams.MATCH_PARENT;
layoutParams1.height = LayoutParams.WRAP_CONTENT;
layoutParams1.gravity = Gravity.TOP | Gravity.LEFT;
layoutParams1.leftMargin = AndroidUtilities.dp(51);
layoutParams1.rightMargin = AndroidUtilities.dp(4);
layoutParams1.topMargin = AndroidUtilities.dp(26);
textView2.setLayoutParams(layoutParams1);
}
@ -115,7 +111,8 @@ public class PhotoPickerSearchCell extends LinearLayout {
SearchButton searchButton = new SearchButton(context);
searchButton.textView1.setText(LocaleController.getString("SearchImages", R.string.SearchImages));
searchButton.imageView.setImageResource(R.drawable.web_search);
searchButton.textView2.setText(LocaleController.getString("SearchImagesInfo", R.string.SearchImagesInfo));
searchButton.imageView.setImageResource(R.drawable.search_web);
addView(searchButton);
LayoutParams layoutParams = (LayoutParams) searchButton.getLayoutParams();
layoutParams.weight = 0.5f;
@ -144,7 +141,7 @@ public class PhotoPickerSearchCell extends LinearLayout {
searchButton = new SearchButton(context);
searchButton.textView1.setText(LocaleController.getString("SearchGifs", R.string.SearchGifs));
searchButton.textView2.setText("GIPHY");
searchButton.imageView.setImageResource(R.drawable.gif_search);
searchButton.imageView.setImageResource(R.drawable.search_gif);
addView(searchButton);
layoutParams = (LayoutParams) searchButton.getLayoutParams();
layoutParams.weight = 0.5f;

View File

@ -249,6 +249,12 @@ public class SharedDocumentCell extends FrameLayout implements MediaController.
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
MediaController.getInstance().removeLoadingFileObserver(this);
}
public void setChecked(boolean checked, boolean animated) {
if (checkBox.getVisibility() != VISIBLE) {
checkBox.setVisibility(VISIBLE);
@ -262,30 +268,40 @@ public class SharedDocumentCell extends FrameLayout implements MediaController.
loaded = false;
loading = false;
int idx = -1;
String name = FileLoader.getDocumentFileName(document.messageOwner.media.document);
placeholderImabeView.setVisibility(VISIBLE);
extTextView.setVisibility(VISIBLE);
placeholderImabeView.setImageResource(getThumbForNameOrMime(name, document.messageOwner.media.document.mime_type));
nameTextView.setText(name);
extTextView.setText((idx = name.lastIndexOf(".")) == -1 ? "" : name.substring(idx + 1).toLowerCase());
if (document.messageOwner.media.document.thumb instanceof TLRPC.TL_photoSizeEmpty) {
if (document != null && document.messageOwner.media != null) {
int idx = -1;
String name = FileLoader.getDocumentFileName(document.messageOwner.media.document);
placeholderImabeView.setVisibility(VISIBLE);
extTextView.setVisibility(VISIBLE);
placeholderImabeView.setImageResource(getThumbForNameOrMime(name, document.messageOwner.media.document.mime_type));
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.setImageBitmap(null);
} else {
thumbImageView.setVisibility(VISIBLE);
thumbImageView.setImage(document.messageOwner.media.document.thumb.location, "40_40", (Drawable) null);
}
long date = (long) document.messageOwner.date * 1000;
dateTextView.setText(String.format("%s, %s", Utilities.formatFileSize(document.messageOwner.media.document.size), LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.formatterYear.format(new Date(date)), LocaleController.formatterDay.format(new Date(date)))));
} else {
nameTextView.setText("");
extTextView.setText("");
dateTextView.setText("");
placeholderImabeView.setVisibility(VISIBLE);
extTextView.setVisibility(VISIBLE);
thumbImageView.setVisibility(GONE);
thumbImageView.setImageBitmap(null);
} else {
thumbImageView.setVisibility(VISIBLE);
thumbImageView.setImage(document.messageOwner.media.document.thumb.location, "40_40", (Drawable) null);
}
long date = (long) document.messageOwner.date * 1000;
dateTextView.setText(String.format("%s, %s", Utilities.formatFileSize(document.messageOwner.media.document.size), LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.formatterYear.format(new Date(date)), LocaleController.formatterDay.format(new Date(date)))));
setWillNotDraw(!needDivider);
progressView.setProgress(0, false);
updateFileExistIcon();
}
public void updateFileExistIcon() {
if (message != null) {
if (message != null && message.messageOwner.media != null) {
String fileName = null;
File cacheFile = null;
if (message.messageOwner.attachPath == null || message.messageOwner.attachPath.length() == 0 || !(new File(message.messageOwner.attachPath).exists())) {

View File

@ -0,0 +1,50 @@
/*
* 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.util.TypedValue;
import android.view.Gravity;
import android.widget.FrameLayout;
import android.widget.TextView;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.LocaleController;
public class SharedMediaSectionCell extends FrameLayout {
private TextView textView;
public SharedMediaSectionCell(Context context) {
super(context);
textView = new TextView(getContext());
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
textView.setTextColor(0xff222222);
textView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL);
addView(textView);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams)textView.getLayoutParams();
layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams.leftMargin = AndroidUtilities.dp(13);
layoutParams.rightMargin = AndroidUtilities.dp(13);
layoutParams.gravity = LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT;
textView.setLayoutParams(layoutParams);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(40), MeasureSpec.EXACTLY));
}
public void setText(String text) {
textView.setText(text);
}
}

View File

@ -0,0 +1,255 @@
/*
* 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.os.Build;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.MessageObject;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.R;
import org.telegram.messenger.TLRPC;
import org.telegram.ui.Components.BackupImageView;
import org.telegram.ui.Components.CheckBox;
import org.telegram.ui.Components.FrameLayoutFixed;
import org.telegram.ui.PhotoViewer;
public class SharedPhotoVideoCell extends FrameLayoutFixed {
private PhotoVideoView[] photoVideoViews;
private MessageObject[] messageObjects;
private int[] indeces;
private SharedPhotoVideoCellDelegate delegate;
private int itemsCount;
private boolean isFirst;
public static interface SharedPhotoVideoCellDelegate {
public abstract void didClickItem(SharedPhotoVideoCell cell, int index, MessageObject messageObject, int a);
public abstract boolean didLongClickItem(SharedPhotoVideoCell cell, int index, MessageObject messageObject, int a);
}
private class PhotoVideoView extends FrameLayoutFixed {
private BackupImageView imageView;
private TextView videoTextView;
private LinearLayout videoInfoContainer;
private View selector;
private CheckBox checkBox;
public PhotoVideoView(Context context) {
super(context);
imageView = new BackupImageView(context);
imageView.imageReceiver.setNeedsQualityThumb(true);
imageView.imageReceiver.setShouldGenerateQualityThumb(true);
addView(imageView);
LayoutParams layoutParams = (LayoutParams) imageView.getLayoutParams();
layoutParams.width = LayoutParams.MATCH_PARENT;
layoutParams.height = LayoutParams.MATCH_PARENT;
imageView.setLayoutParams(layoutParams);
videoInfoContainer = new LinearLayout(context);
videoInfoContainer.setOrientation(LinearLayout.HORIZONTAL);
videoInfoContainer.setBackgroundResource(R.drawable.phototime);
videoInfoContainer.setPadding(AndroidUtilities.dp(3), 0, AndroidUtilities.dp(3), 0);
videoInfoContainer.setGravity(Gravity.CENTER_VERTICAL);
addView(videoInfoContainer);
layoutParams = (LayoutParams) videoInfoContainer.getLayoutParams();
layoutParams.width = LayoutParams.MATCH_PARENT;
layoutParams.height = AndroidUtilities.dp(16);
layoutParams.gravity = Gravity.BOTTOM | Gravity.LEFT;
videoInfoContainer.setLayoutParams(layoutParams);
ImageView imageView1 = new ImageView(context);
imageView1.setImageResource(R.drawable.ic_video);
videoInfoContainer.addView(imageView1);
LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) imageView1.getLayoutParams();
layoutParams1.width = LinearLayout.LayoutParams.WRAP_CONTENT;
layoutParams1.height = LinearLayout.LayoutParams.WRAP_CONTENT;
imageView1.setLayoutParams(layoutParams1);
videoTextView = new TextView(context);
videoTextView.setTextColor(0xffffffff);
videoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
videoTextView.setGravity(Gravity.CENTER_VERTICAL);
videoInfoContainer.addView(videoTextView);
layoutParams1 = (LinearLayout.LayoutParams) videoTextView.getLayoutParams();
layoutParams1.width = LinearLayout.LayoutParams.WRAP_CONTENT;
layoutParams1.height = LinearLayout.LayoutParams.WRAP_CONTENT;
layoutParams1.leftMargin = AndroidUtilities.dp(4);
layoutParams1.gravity = Gravity.CENTER_VERTICAL;
layoutParams1.bottomMargin = AndroidUtilities.dp(1);
videoTextView.setLayoutParams(layoutParams1);
selector = new View(context);
selector.setBackgroundResource(R.drawable.list_selector);
addView(selector);
layoutParams = (LayoutParams) selector.getLayoutParams();
layoutParams.width = LayoutParams.MATCH_PARENT;
layoutParams.height = LayoutParams.MATCH_PARENT;
selector.setLayoutParams(layoutParams);
checkBox = new CheckBox(context, R.drawable.round_check2);
checkBox.setVisibility(GONE);
addView(checkBox);
layoutParams = (LayoutParams) checkBox.getLayoutParams();
layoutParams.width = AndroidUtilities.dp(22);
layoutParams.height = AndroidUtilities.dp(22);
layoutParams.gravity = Gravity.RIGHT | Gravity.TOP;
layoutParams.topMargin = AndroidUtilities.dp(6);
layoutParams.rightMargin = AndroidUtilities.dp(6);
checkBox.setLayoutParams(layoutParams);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (Build.VERSION.SDK_INT >= 21) {
selector.drawableHotspotChanged(event.getX(), event.getY());
}
return super.onTouchEvent(event);
}
}
public SharedPhotoVideoCell(Context context) {
super(context);
messageObjects = new MessageObject[6];
photoVideoViews = new PhotoVideoView[6];
indeces = new int[6];
for (int a = 0; a < 6; a++) {
photoVideoViews[a] = new PhotoVideoView(context);
addView(photoVideoViews[a]);
photoVideoViews[a].setVisibility(GONE);
photoVideoViews[a].setTag(a);
photoVideoViews[a].setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (delegate != null) {
int a = (Integer) v.getTag();
delegate.didClickItem(SharedPhotoVideoCell.this, indeces[a], messageObjects[a], a);
}
}
});
photoVideoViews[a].setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if (delegate != null) {
int a = (Integer) v.getTag();
return delegate.didLongClickItem(SharedPhotoVideoCell.this, indeces[a], messageObjects[a], a);
}
return false;
}
});
}
}
public void setDelegate(SharedPhotoVideoCellDelegate delegate) {
this.delegate = delegate;
}
public void setItemsCount(int count) {
for (int a = 0; a < photoVideoViews.length; a++) {
photoVideoViews[a].setVisibility(a < count ? VISIBLE : GONE);
}
itemsCount = count;
}
public BackupImageView getImageView(int a) {
if (a >= itemsCount) {
return null;
}
return photoVideoViews[a].imageView;
}
public MessageObject getMessageObject(int a) {
if (a >= itemsCount) {
return null;
}
return messageObjects[a];
}
public void setIsFirst(boolean first) {
isFirst = first;
}
public void setChecked(int a, boolean checked, boolean animated) {
if (photoVideoViews[a].checkBox.getVisibility() != VISIBLE) {
photoVideoViews[a].checkBox.setVisibility(VISIBLE);
}
photoVideoViews[a].checkBox.setChecked(checked, animated);
}
public void setItem(int a, int index, MessageObject messageObject) {
messageObjects[a] = messageObject;
indeces[a] = index;
if (messageObject != null) {
photoVideoViews[a].setVisibility(VISIBLE);
PhotoVideoView photoVideoView = photoVideoViews[a];
photoVideoView.imageView.imageReceiver.setParentMessageObject(messageObject);
photoVideoView.imageView.imageReceiver.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;
int minutes = duration / 60;
int seconds = duration - minutes * 60;
photoVideoView.videoTextView.setText(String.format("%d:%02d", minutes, seconds));
if (messageObject.messageOwner.media.video.thumb != null) {
TLRPC.FileLocation location = messageObject.messageOwner.media.video.thumb.location;
photoVideoView.imageView.setImage(null, null, null, ApplicationLoader.applicationContext.getResources().getDrawable(R.drawable.photo_placeholder_in), null, location, "b", 0);
} else {
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);
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.imageView.setImageResource(R.drawable.photo_placeholder_in);
}
} else {
photoVideoViews[a].setVisibility(GONE);
messageObjects[a] = null;
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int itemWidth;
if (AndroidUtilities.isTablet()) {
itemWidth = (AndroidUtilities.dp(490) - ((itemsCount + 1) * AndroidUtilities.dp(4))) / itemsCount;
} else {
itemWidth = (AndroidUtilities.displaySize.x - ((itemsCount + 1) * AndroidUtilities.dp(4))) / itemsCount;
}
for (int a = 0; a < itemsCount; a++) {
LayoutParams layoutParams = (LayoutParams) photoVideoViews[a].getLayoutParams();
layoutParams.topMargin = isFirst ? 0 : AndroidUtilities.dp(4);
layoutParams.leftMargin = (itemWidth + AndroidUtilities.dp(4)) * a + AndroidUtilities.dp(4);
layoutParams.width = itemWidth;
layoutParams.height = itemWidth;
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
photoVideoViews[a].setLayoutParams(layoutParams);
}
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec((isFirst ? 0 : AndroidUtilities.dp(4)) + itemWidth, MeasureSpec.EXACTLY));
}
}

View File

@ -55,7 +55,7 @@ public class ChangeChatNameActivity extends BaseFragment {
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);

View File

@ -48,7 +48,7 @@ public class ChangeNameActivity extends BaseFragment {
private final static int done_button = 1;
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);

View File

@ -101,7 +101,7 @@ public class ChangePhoneActivity extends BaseFragment {
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setTitle(LocaleController.getString("AppName", R.string.AppName));
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
@ -289,9 +289,9 @@ public class ChangePhoneActivity extends BaseFragment {
private int countryState = 0;
private ArrayList<String> countriesArray = new ArrayList<String>();
private HashMap<String, String> countriesMap = new HashMap<String, String>();
private HashMap<String, String> codesMap = new HashMap<String, String>();
private ArrayList<String> countriesArray = new ArrayList<>();
private HashMap<String, String> countriesMap = new HashMap<>();
private HashMap<String, String> codesMap = new HashMap<>();
private boolean ignoreSelection = false;
private boolean ignoreOnTextChange = false;
@ -533,7 +533,7 @@ public class ChangePhoneActivity extends BaseFragment {
layoutParams.gravity = Gravity.LEFT;
textView.setLayoutParams(layoutParams);
HashMap<String, String> languageMap = new HashMap<String, String>();
HashMap<String, String> languageMap = new HashMap<>();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(getResources().getAssets().open("countries.txt")));
String line;
@ -1013,7 +1013,7 @@ public class ChangePhoneActivity extends BaseFragment {
destroyCodeTimer();
UserConfig.setCurrentUser(user);
UserConfig.saveConfig(true);
ArrayList<TLRPC.User> users = new ArrayList<TLRPC.User>();
ArrayList<TLRPC.User> users = new ArrayList<>();
users.add(user);
MessagesStorage.getInstance().putUsersAndChats(users, null, true, true);
MessagesController.getInstance().putUser(user, false);

View File

@ -35,7 +35,7 @@ import org.telegram.ui.ActionBar.BaseFragment;
public class ChangePhoneHelpActivity extends BaseFragment {
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);

View File

@ -61,7 +61,7 @@ public class ChangeUsernameActivity extends BaseFragment {
private final static int done_button = 1;
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);
@ -205,14 +205,19 @@ public class ChangeUsernameActivity extends BaseFragment {
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
if (error.equals("USERNAME_INVALID")) {
builder.setMessage(LocaleController.getString("UsernameInvalid", R.string.UsernameInvalid));
} else if (error.equals("USERNAME_OCCUPIED")) {
builder.setMessage(LocaleController.getString("UsernameInUse", R.string.UsernameInUse));
} else if (error.equals("USERNAMES_UNAVAILABLE")) {
builder.setMessage(LocaleController.getString("FeatureUnavailable", R.string.FeatureUnavailable));
} else {
builder.setMessage(LocaleController.getString("ErrorOccurred", R.string.ErrorOccurred));
switch (error) {
case "USERNAME_INVALID":
builder.setMessage(LocaleController.getString("UsernameInvalid", R.string.UsernameInvalid));
break;
case "USERNAME_OCCUPIED":
builder.setMessage(LocaleController.getString("UsernameInUse", R.string.UsernameInUse));
break;
case "USERNAMES_UNAVAILABLE":
builder.setMessage(LocaleController.getString("FeatureUnavailable", R.string.FeatureUnavailable));
break;
default:
builder.setMessage(LocaleController.getString("ErrorOccurred", R.string.ErrorOccurred));
break;
}
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
showAlertDialog(builder);

File diff suppressed because it is too large Load Diff

View File

@ -13,6 +13,7 @@ import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
@ -164,6 +165,11 @@ public class AvatarDrawable extends Drawable {
drawBrodcast = isBroadcast;
if (firstName == null || firstName.length() == 0) {
firstName = lastName;
lastName = null;
}
String text = "";
if (firstName != null && firstName.length() > 0) {
text += firstName.substring(0, 1);
@ -176,8 +182,26 @@ public class AvatarDrawable extends Drawable {
}
lastch = lastName.substring(a, a + 1);
}
text += lastch;
if (Build.VERSION.SDK_INT >= 14) {
text += "\u200C" + lastch;
} else {
text += lastch;
}
} else if (firstName != null && firstName.length() > 0) {
for (int a = firstName.length() - 1; a >= 0; a--) {
if (firstName.charAt(a) == ' ') {
if (a != firstName.length() - 1 && firstName.charAt(a + 1) != ' ') {
if (Build.VERSION.SDK_INT >= 14) {
text += "\u200C" + firstName.substring(a + 1, a + 2);
} else {
text += firstName.substring(a + 1, a + 2);
}
break;
}
}
}
}
if (text.length() > 0) {
text = text.toUpperCase();
try {

View File

@ -11,12 +11,14 @@ package org.telegram.ui.Components;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.ImageLoader;
import org.telegram.android.MediaController;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
@ -24,10 +26,13 @@ import org.telegram.android.NotificationCenter;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
import org.telegram.ui.LaunchActivity;
import org.telegram.ui.PhotoAlbumPickerActivity;
import org.telegram.ui.PhotoCropActivity;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.PhotoViewer;
import java.io.File;
import java.util.ArrayList;
public class AvatarUpdater implements NotificationCenter.NotificationCenterDelegate, PhotoCropActivity.PhotoEditActivityDelegate {
public String currentPicturePath;
@ -68,13 +73,33 @@ public class AvatarUpdater implements NotificationCenter.NotificationCenterDeleg
}
public void openGallery() {
try {
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
parentFragment.startActivityForResult(photoPickerIntent, 14);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
PhotoAlbumPickerActivity fragment = new PhotoAlbumPickerActivity(true);
fragment.setDelegate(new PhotoAlbumPickerActivity.PhotoAlbumPickerActivityDelegate() {
@Override
public void didSelectPhotos(ArrayList<String> photos) {
if (!photos.isEmpty()) {
Bitmap bitmap = ImageLoader.loadBitmap(photos.get(0), null, 800, 800, true);
processBitmap(bitmap);
}
}
@Override
public void didSelectWebPhotos(ArrayList<MediaController.SearchImage> photos) {
}
@Override
public void startPhotoSelectActivity() {
try {
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
parentFragment.startActivityForResult(photoPickerIntent, 14);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
parentFragment.presentFragment(fragment);
}
private void startCrop(String path, Uri uri) {
@ -102,9 +127,42 @@ public class AvatarUpdater implements NotificationCenter.NotificationCenterDeleg
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 13) {
PhotoViewer.getInstance().setParentActivity(parentFragment.getParentActivity());
int orientation = 0;
try {
ExifInterface ei = new ExifInterface(currentPicturePath);
int exif = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch(exif) {
case ExifInterface.ORIENTATION_ROTATE_90:
orientation = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
orientation = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
orientation = 270;
break;
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
final ArrayList<Object> arrayList = new ArrayList<>();
arrayList.add(new MediaController.PhotoEntry(0, 0, 0, currentPicturePath, orientation));
PhotoViewer.getInstance().openPhotoForSelect(arrayList, 0, 1, new PhotoViewer.EmptyPhotoViewerProvider() {
@Override
public void sendButtonPressed(int index) {
String path = null;
MediaController.PhotoEntry photoEntry = (MediaController.PhotoEntry) arrayList.get(0);
if (photoEntry.imagePath != null) {
path = photoEntry.imagePath;
} else if (photoEntry.path != null) {
path = photoEntry.path;
}
Bitmap bitmap = ImageLoader.loadBitmap(path, null, 800, 800, true);
processBitmap(bitmap);
}
});
Utilities.addMediaToGallery(currentPicturePath);
startCrop(currentPicturePath, null);
currentPicturePath = null;
} else if (requestCode == 14) {
if (data == null || data.getData() == null) {

View File

@ -68,6 +68,10 @@ public class BackupImageView extends View {
setImage(null, path, filter, thumb, null, null, null, 0);
}
public void setOrientation(int angle, boolean center) {
imageReceiver.setOrientation(angle, center);
}
public void setImage(TLObject path, String httpUrl, String filter, Drawable thumb, Bitmap thumbBitmap, TLRPC.FileLocation thumbLocation, String thumbFilter, int size) {
if (thumbBitmap != null) {
thumb = new BitmapDrawable(null, thumbBitmap);

View File

@ -18,6 +18,7 @@ import android.os.PowerManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
@ -29,8 +30,8 @@ import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
@ -54,7 +55,7 @@ import org.telegram.messenger.ApplicationLoader;
import java.lang.reflect.Field;
public class ChatActivityEnterView implements NotificationCenter.NotificationCenterDelegate, SizeNotifierRelativeLayout.SizeNotifierRelativeLayoutDelegate {
public class ChatActivityEnterView extends LinearLayout implements NotificationCenter.NotificationCenterDelegate, SizeNotifierRelativeLayout.SizeNotifierRelativeLayoutDelegate {
public static interface ChatActivityEnterViewDelegate {
public abstract void onMessageSend();
@ -66,17 +67,18 @@ public class ChatActivityEnterView implements NotificationCenter.NotificationCen
}
private EditText messsageEditText;
private ImageButton sendButton;
private ImageView sendButton;
private PopupWindow emojiPopup;
private ImageView emojiButton;
private EmojiView emojiView;
private TextView recordTimeText;
private ImageButton audioSendButton;
private View recordPanel;
private View slideText;
private PowerManager.WakeLock mWakeLock;
private ImageView audioSendButton;
private FrameLayout recordPanel;
private LinearLayout slideText;
private SizeNotifierRelativeLayout sizeNotifierRelativeLayout;
private FrameLayout attachButton;
private PowerManager.WakeLock mWakeLock;
private AnimatorSetProxy runningAnimation;
private AnimatorSetProxy runningAnimation2;
private ObjectAnimatorProxy runningAnimationAudio;
@ -98,7 +100,13 @@ public class ChatActivityEnterView implements NotificationCenter.NotificationCen
private boolean ignoreTextChange;
private ChatActivityEnterViewDelegate delegate;
public ChatActivityEnterView() {
public ChatActivityEnterView(Activity context, SizeNotifierRelativeLayout parent, boolean isChat) {
super(context);
setOrientation(HORIZONTAL);
setBackgroundResource(R.drawable.compose_panel);
setFocusable(true);
setFocusableInTouchMode(true);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.recordStarted);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.recordStartError);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.recordStopped);
@ -108,64 +116,31 @@ public class ChatActivityEnterView implements NotificationCenter.NotificationCen
NotificationCenter.getInstance().addObserver(this, NotificationCenter.emojiDidLoaded);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.hideEmojiKeyboard);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioRouteChanged);
parentActivity = context;
sizeNotifierRelativeLayout = parent;
sizeNotifierRelativeLayout.setDelegate(this);
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
sendByEnter = preferences.getBoolean("send_by_enter", false);
}
public void onDestroy() {
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.recordStarted);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.recordStartError);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.recordStopped);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.recordProgressChanged);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.closeChats);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.audioDidSent);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.emojiDidLoaded);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.hideEmojiKeyboard);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.audioRouteChanged);
if (mWakeLock != null) {
try {
mWakeLock.release();
mWakeLock = null;
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
if (sizeNotifierRelativeLayout != null) {
sizeNotifierRelativeLayout.delegate = null;
}
}
public void setContainerView(Activity activity, View containerView) {
parentActivity = activity;
sizeNotifierRelativeLayout = (SizeNotifierRelativeLayout) containerView.findViewById(R.id.chat_layout);
sizeNotifierRelativeLayout.delegate = this;
messsageEditText = (EditText) containerView.findViewById(R.id.chat_text_edit);
messsageEditText.setHint(LocaleController.getString("TypeMessage", R.string.TypeMessage));
attachButton = (FrameLayout) containerView.findViewById(R.id.chat_attach_button);
if (attachButton != null) {
ViewProxy.setPivotX(attachButton, AndroidUtilities.dp(48));
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) messsageEditText.getLayoutParams();
layoutParams.rightMargin = AndroidUtilities.dp(50);
messsageEditText.setLayoutParams(layoutParams);
}
sendButton = (ImageButton) containerView.findViewById(R.id.chat_send_button);
sendButton.setVisibility(View.INVISIBLE);
ViewProxy.setScaleX(sendButton, 0.1f);
ViewProxy.setScaleY(sendButton, 0.1f);
ViewProxy.setAlpha(sendButton, 0.0f);
sendButton.clearAnimation();
emojiButton = (ImageView) containerView.findViewById(R.id.chat_smile_button);
audioSendButton = (ImageButton) containerView.findViewById(R.id.chat_audio_send_button);
recordPanel = containerView.findViewById(R.id.record_panel);
recordTimeText = (TextView) containerView.findViewById(R.id.recording_time_text);
slideText = containerView.findViewById(R.id.slideText);
TextView textView = (TextView) containerView.findViewById(R.id.slideToCancelTextView);
textView.setText(LocaleController.getString("SlideToCancel", R.string.SlideToCancel));
FrameLayoutFixed frameLayout = new FrameLayoutFixed(context);
addView(frameLayout);
LayoutParams layoutParams = (LayoutParams) frameLayout.getLayoutParams();
layoutParams.width = 0;
layoutParams.height = LayoutParams.WRAP_CONTENT;
layoutParams.weight = 1;
frameLayout.setLayoutParams(layoutParams);
emojiButton = new ImageView(context);
emojiButton.setImageResource(R.drawable.ic_msg_panel_smiles);
emojiButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
emojiButton.setPadding(AndroidUtilities.dp(4), AndroidUtilities.dp(1), 0, 0);
frameLayout.addView(emojiButton);
FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) emojiButton.getLayoutParams();
layoutParams1.width = AndroidUtilities.dp(48);
layoutParams1.height = AndroidUtilities.dp(48);
layoutParams1.gravity = Gravity.BOTTOM;
layoutParams1.topMargin = AndroidUtilities.dp(2);
emojiButton.setLayoutParams(layoutParams1);
emojiButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
@ -173,6 +148,41 @@ public class ChatActivityEnterView implements NotificationCenter.NotificationCen
}
});
/*
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:id="@+id/chat_text_edit"
android:maxLines="4"
android:textSize="18dp"
android:textColorHint="#b2b2b2"
android:imeOptions="flagNoExtractUi"
android:inputType="textCapSentences|textMultiLine"
/>
*/
messsageEditText = new EditText(context);
messsageEditText.setHint(LocaleController.getString("TypeMessage", R.string.TypeMessage));
messsageEditText.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
messsageEditText.setInputType(messsageEditText.getInputType() | EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE);
messsageEditText.setSingleLine(false);
messsageEditText.setMaxLines(4);
messsageEditText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
messsageEditText.setGravity(Gravity.BOTTOM);
messsageEditText.setPadding(0, AndroidUtilities.dp(11), 0, AndroidUtilities.dp(12));
messsageEditText.setBackgroundDrawable(null);
AndroidUtilities.clearCursorDrawable(messsageEditText);
messsageEditText.setTextColor(0xff000000);
messsageEditText.setHintTextColor(0xffb2b2b2);
frameLayout.addView(messsageEditText);
layoutParams1 = (FrameLayout.LayoutParams) messsageEditText.getLayoutParams();
layoutParams1.width = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams1.height = FrameLayout.LayoutParams.WRAP_CONTENT;
layoutParams1.gravity = Gravity.BOTTOM;
layoutParams1.leftMargin = AndroidUtilities.dp(52);
layoutParams1.rightMargin = AndroidUtilities.dp(isChat ? 50 : 2);
messsageEditText.setLayoutParams(layoutParams1);
messsageEditText.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
@ -188,7 +198,6 @@ public class ChatActivityEnterView implements NotificationCenter.NotificationCen
return false;
}
});
messsageEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
@ -197,7 +206,6 @@ public class ChatActivityEnterView implements NotificationCenter.NotificationCen
}
}
});
messsageEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
@ -213,14 +221,164 @@ public class ChatActivityEnterView implements NotificationCenter.NotificationCen
return false;
}
});
sendButton.setOnClickListener(new View.OnClickListener() {
messsageEditText.addTextChangedListener(new TextWatcher() {
@Override
public void onClick(View view) {
sendMessage();
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
String message = getTrimmedString(charSequence.toString());
checkSendButton(true);
if (delegate != null) {
delegate.onTextChanged(charSequence);
}
if (message.length() != 0 && lastTypingTimeSend < System.currentTimeMillis() - 5000 && !ignoreTextChange) {
int currentTime = ConnectionsManager.getInstance().getCurrentTime();
TLRPC.User currentUser = null;
if ((int) dialog_id > 0) {
currentUser = MessagesController.getInstance().getUser((int) dialog_id);
}
if (currentUser != null && (currentUser.id == UserConfig.getClientUserId() || currentUser.status != null && currentUser.status.expires < currentTime)) {
return;
}
lastTypingTimeSend = System.currentTimeMillis();
if (delegate != null) {
delegate.needSendTyping();
}
}
}
@Override
public void afterTextChanged(Editable editable) {
if (sendByEnter && editable.length() > 0 && editable.charAt(editable.length() - 1) == '\n') {
sendMessage();
}
int i = 0;
ImageSpan[] arrayOfImageSpan = editable.getSpans(0, editable.length(), ImageSpan.class);
int j = arrayOfImageSpan.length;
while (true) {
if (i >= j) {
Emoji.replaceEmoji(editable, messsageEditText.getPaint().getFontMetricsInt(), AndroidUtilities.dp(20));
return;
}
editable.removeSpan(arrayOfImageSpan[i]);
i++;
}
}
});
if (isChat) {
attachButton = new FrameLayout(context);
attachButton.setEnabled(false);
ViewProxy.setPivotX(attachButton, AndroidUtilities.dp(48));
frameLayout.addView(attachButton);
layoutParams1 = (FrameLayout.LayoutParams) attachButton.getLayoutParams();
layoutParams1.width = AndroidUtilities.dp(48);
layoutParams1.height = AndroidUtilities.dp(48);
layoutParams1.gravity = Gravity.BOTTOM | Gravity.RIGHT;
layoutParams1.topMargin = AndroidUtilities.dp(2);
attachButton.setLayoutParams(layoutParams1);
}
recordPanel = new FrameLayoutFixed(context);
recordPanel.setVisibility(GONE);
recordPanel.setBackgroundColor(0xffffffff);
frameLayout.addView(recordPanel);
layoutParams1 = (FrameLayout.LayoutParams) recordPanel.getLayoutParams();
layoutParams1.width = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams1.height = AndroidUtilities.dp(48);
layoutParams1.gravity = Gravity.BOTTOM;
layoutParams1.topMargin = AndroidUtilities.dp(2);
recordPanel.setLayoutParams(layoutParams1);
slideText = new LinearLayout(context);
slideText.setOrientation(HORIZONTAL);
recordPanel.addView(slideText);
layoutParams1 = (FrameLayout.LayoutParams) slideText.getLayoutParams();
layoutParams1.width = FrameLayout.LayoutParams.WRAP_CONTENT;
layoutParams1.height = FrameLayout.LayoutParams.WRAP_CONTENT;
layoutParams1.gravity = Gravity.CENTER;
layoutParams1.leftMargin = AndroidUtilities.dp(30);
slideText.setLayoutParams(layoutParams1);
ImageView imageView = new ImageView(context);
imageView.setImageResource(R.drawable.slidearrow);
slideText.addView(imageView);
layoutParams = (LayoutParams) imageView.getLayoutParams();
layoutParams.width = LayoutParams.WRAP_CONTENT;
layoutParams.height = LayoutParams.WRAP_CONTENT;
layoutParams.gravity = Gravity.CENTER_VERTICAL;
layoutParams.topMargin = AndroidUtilities.dp(1);
imageView.setLayoutParams(layoutParams);
TextView textView = new TextView(context);
textView.setText(LocaleController.getString("SlideToCancel", R.string.SlideToCancel));
textView.setTextColor(0xff999999);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
slideText.addView(textView);
layoutParams = (LayoutParams) textView.getLayoutParams();
layoutParams.width = LayoutParams.WRAP_CONTENT;
layoutParams.height = LayoutParams.WRAP_CONTENT;
layoutParams.gravity = Gravity.CENTER_VERTICAL;
layoutParams.leftMargin = AndroidUtilities.dp(6);
textView.setLayoutParams(layoutParams);
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setOrientation(HORIZONTAL);
linearLayout.setPadding(AndroidUtilities.dp(13), 0, 0, 0);
linearLayout.setBackgroundColor(0xffffffff);
recordPanel.addView(linearLayout);
layoutParams1 = (FrameLayout.LayoutParams) linearLayout.getLayoutParams();
layoutParams1.width = FrameLayout.LayoutParams.WRAP_CONTENT;
layoutParams1.height = FrameLayout.LayoutParams.WRAP_CONTENT;
layoutParams1.gravity = Gravity.CENTER_VERTICAL;
linearLayout.setLayoutParams(layoutParams1);
imageView = new ImageView(context);
imageView.setImageResource(R.drawable.rec);
linearLayout.addView(imageView);
layoutParams = (LayoutParams) imageView.getLayoutParams();
layoutParams.width = LayoutParams.WRAP_CONTENT;
layoutParams.height = LayoutParams.WRAP_CONTENT;
layoutParams.gravity = Gravity.CENTER_VERTICAL;
layoutParams.topMargin = AndroidUtilities.dp(1);
imageView.setLayoutParams(layoutParams);
recordTimeText = new TextView(context);
recordTimeText.setText("00:00");
recordTimeText.setTextColor(0xff4d4c4b);
recordTimeText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
linearLayout.addView(recordTimeText);
layoutParams = (LayoutParams) recordTimeText.getLayoutParams();
layoutParams.width = LayoutParams.WRAP_CONTENT;
layoutParams.height = LayoutParams.WRAP_CONTENT;
layoutParams.gravity = Gravity.CENTER_VERTICAL;
layoutParams.leftMargin = AndroidUtilities.dp(6);
recordTimeText.setLayoutParams(layoutParams);
FrameLayout frameLayout1 = new FrameLayout(context);
addView(frameLayout1);
layoutParams = (LayoutParams) frameLayout1.getLayoutParams();
layoutParams.width = AndroidUtilities.dp(48);
layoutParams.height = AndroidUtilities.dp(48);
layoutParams.gravity = Gravity.BOTTOM;
layoutParams.topMargin = AndroidUtilities.dp(2);
frameLayout1.setLayoutParams(layoutParams);
audioSendButton = new ImageView(context);
audioSendButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
audioSendButton.setImageResource(R.drawable.mic_button_states);
audioSendButton.setBackgroundColor(0xffffffff);
audioSendButton.setPadding(0, 0, AndroidUtilities.dp(4), 0);
frameLayout1.addView(audioSendButton);
layoutParams1 = (FrameLayout.LayoutParams) audioSendButton.getLayoutParams();
layoutParams1.width = AndroidUtilities.dp(48);
layoutParams1.height = AndroidUtilities.dp(48);
audioSendButton.setLayoutParams(layoutParams1);
audioSendButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
@ -279,59 +437,56 @@ public class ChatActivityEnterView implements NotificationCenter.NotificationCen
}
});
messsageEditText.addTextChangedListener(new TextWatcher() {
sendButton = new ImageView(context);
sendButton.setVisibility(View.INVISIBLE);
sendButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
sendButton.setImageResource(R.drawable.ic_send);
ViewProxy.setScaleX(sendButton, 0.1f);
ViewProxy.setScaleY(sendButton, 0.1f);
ViewProxy.setAlpha(sendButton, 0.0f);
sendButton.clearAnimation();
frameLayout1.addView(sendButton);
layoutParams1 = (FrameLayout.LayoutParams) sendButton.getLayoutParams();
layoutParams1.width = AndroidUtilities.dp(48);
layoutParams1.height = AndroidUtilities.dp(48);
sendButton.setLayoutParams(layoutParams1);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
String message = getTrimmedString(charSequence.toString());
checkSendButton(true);
if (delegate != null) {
delegate.onTextChanged(charSequence);
}
if (message.length() != 0 && lastTypingTimeSend < System.currentTimeMillis() - 5000 && !ignoreTextChange) {
int currentTime = ConnectionsManager.getInstance().getCurrentTime();
TLRPC.User currentUser = null;
if ((int) dialog_id > 0) {
currentUser = MessagesController.getInstance().getUser((int) dialog_id);
}
if (currentUser != null && (currentUser.id == UserConfig.getClientUserId() || currentUser.status != null && currentUser.status.expires < currentTime)) {
return;
}
lastTypingTimeSend = System.currentTimeMillis();
if (delegate != null) {
delegate.needSendTyping();
}
}
}
@Override
public void afterTextChanged(Editable editable) {
if (sendByEnter && editable.length() > 0 && editable.charAt(editable.length() - 1) == '\n') {
sendMessage();
}
int i = 0;
ImageSpan[] arrayOfImageSpan = editable.getSpans(0, editable.length(), ImageSpan.class);
int j = arrayOfImageSpan.length;
while (true) {
if (i >= j) {
Emoji.replaceEmoji(editable, messsageEditText.getPaint().getFontMetricsInt(), AndroidUtilities.dp(20));
return;
}
editable.removeSpan(arrayOfImageSpan[i]);
i++;
}
public void onClick(View view) {
sendMessage();
}
});
checkSendButton(false);
}
public void onDestroy() {
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.recordStarted);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.recordStartError);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.recordStopped);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.recordProgressChanged);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.closeChats);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.audioDidSent);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.emojiDidLoaded);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.hideEmojiKeyboard);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.audioRouteChanged);
if (mWakeLock != null) {
try {
mWakeLock.release();
mWakeLock = null;
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
if (sizeNotifierRelativeLayout != null) {
sizeNotifierRelativeLayout.setDelegate(null);
}
}
public void setDialogId(long id) {
dialog_id = id;
}
private void sendMessage() {
if (processSendingText(messsageEditText.getText().toString())) {
messsageEditText.setText("");
@ -725,10 +880,6 @@ public class ChatActivityEnterView implements NotificationCenter.NotificationCen
this.delegate = delegate;
}
public void setDialogId(long id) {
dialog_id = id;
}
public void setFieldText(String text) {
if (messsageEditText == null) {
return;

View File

@ -14,7 +14,6 @@ import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.view.View;
@ -27,9 +26,11 @@ public class ClippingImageView extends View {
private int clipLeft;
private int clipRight;
private int clipTop;
private Rect drawRect;
private int orientation;
private RectF drawRect;
private Paint paint;
private Bitmap bmp;
private Matrix matrix;
private onDrawListener drawListener;
private boolean needRadius;
@ -48,7 +49,9 @@ public class ClippingImageView extends View {
super(context);
paint = new Paint();
paint.setFilterBitmap(true);
drawRect = new Rect();
matrix = new Matrix();
drawRect = new RectF();
bitmapRect = new RectF();
}
public int getClipBottom() {
@ -85,6 +88,7 @@ public class ClippingImageView extends View {
drawListener.onDraw();
}
canvas.save();
if (needRadius) {
roundRect.set(0, 0, getWidth(), getHeight());
shaderMatrix.reset();
@ -92,10 +96,24 @@ public class ClippingImageView extends View {
bitmapShader.setLocalMatrix(shaderMatrix);
canvas.drawRoundRect(roundRect, radius, radius, roundPaint);
} else {
if (orientation == 90 || orientation == 270) {
drawRect.set(-getHeight() / 2, -getWidth() / 2, getHeight() / 2, getWidth() / 2);
matrix.setRectToRect(bitmapRect, drawRect, Matrix.ScaleToFit.FILL);
matrix.postRotate(orientation, 0, 0);
matrix.postTranslate(getWidth() / 2, getHeight() / 2);
} else if (orientation == 180) {
drawRect.set(-getWidth() / 2, -getHeight() / 2, getWidth() / 2, getHeight() / 2);
matrix.setRectToRect(bitmapRect, drawRect, Matrix.ScaleToFit.FILL);
matrix.postRotate(orientation, 0, 0);
matrix.postTranslate(getWidth() / 2, getHeight() / 2);
} else {
drawRect.set(0, 0, getWidth(), getHeight());
matrix.setRectToRect(bitmapRect, drawRect, Matrix.ScaleToFit.FILL);
}
canvas.clipRect(clipLeft / scaleY, clipTop / scaleY, getWidth() - clipRight / scaleY, getHeight() - clipBottom / scaleY);
drawRect.set(0, 0, getWidth(), getHeight());
try {
canvas.drawBitmap(bmp, null, drawRect, paint);
canvas.drawBitmap(bmp, matrix, paint);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
@ -136,16 +154,21 @@ public class ClippingImageView extends View {
invalidate();
}
public void setOrientation(int angle) {
orientation = angle;
}
public void setImageBitmap(Bitmap bitmap) {
bmp = bitmap;
if (bitmap != null && needRadius) {
roundRect = new RectF();
shaderMatrix = new Matrix();
bitmapRect = new RectF();
if (bitmap != null) {
bitmapRect.set(0, 0, bitmap.getWidth(), bitmap.getHeight());
bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
roundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
roundPaint.setShader(bitmapShader);
if (needRadius) {
roundRect = new RectF();
shaderMatrix = new Matrix();
bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
roundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
roundPaint.setShader(bitmapShader);
}
}
invalidate();
}

View File

@ -0,0 +1,121 @@
/*
* 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.app.Activity;
import android.app.Application;
import android.os.Build;
import android.os.Bundle;
import org.telegram.messenger.FileLog;
import java.util.concurrent.CopyOnWriteArrayList;
public class ForegroundDetector implements Application.ActivityLifecycleCallbacks {
public interface Listener {
public void onBecameForeground();
public void onBecameBackground();
}
private int refs;
private boolean wasInBackground = true;
private long enterBackgroundTime = 0;
private CopyOnWriteArrayList<Listener> listeners = new CopyOnWriteArrayList<>();
private static ForegroundDetector Instance = null;
public static ForegroundDetector getInstance() {
return Instance;
}
public ForegroundDetector(Application application) {
Instance = this;
application.registerActivityLifecycleCallbacks(this);
}
public boolean isForeground() {
return refs > 0;
}
public boolean isBackground() {
return refs == 0;
}
public void addListener(Listener listener) {
listeners.add(listener);
}
public void removeListener(Listener listener) {
listeners.remove(listener);
}
@Override
public void onActivityStarted(Activity activity) {
if (++refs == 1) {
if (System.currentTimeMillis() - enterBackgroundTime < 200) {
wasInBackground = false;
}
FileLog.e("tmessages", "switch to foreground");
for (Listener listener : listeners) {
try {
listener.onBecameForeground();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
}
}
public boolean isWasInBackground(boolean reset) {
if (reset && Build.VERSION.SDK_INT >= 21 && (System.currentTimeMillis() - enterBackgroundTime < 200)) {
wasInBackground = false;
}
return wasInBackground;
}
public void resetBackgroundVar() {
wasInBackground = false;
}
@Override
public void onActivityStopped(Activity activity) {
if (--refs == 0) {
enterBackgroundTime = System.currentTimeMillis();
wasInBackground = true;
FileLog.e("tmessages", "switch to background");
for (Listener listener : listeners) {
try {
listener.onBecameBackground();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
}
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
}

View File

@ -0,0 +1,211 @@
/*
* This is the source code of Telegram for Android v. 1.7.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2014.
*/
package org.telegram.ui.Components;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListAdapter;
import android.widget.ListView;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.LocaleController;
import org.telegram.messenger.FileLog;
import org.telegram.ui.Adapters.BaseSectionsAdapter;
import java.util.ArrayList;
public class LetterSectionsListView extends ListView implements AbsListView.OnScrollListener {
private ArrayList<View> headers = new ArrayList<>();
private ArrayList<View> headersCache = new ArrayList<>();
private OnScrollListener mOnScrollListener;
private BaseSectionsAdapter mAdapter;
private int currentFirst = -1;
private int currentVisible = -1;
private int startSection;
private int sectionsCount;
public LetterSectionsListView(Context context) {
super(context);
super.setOnScrollListener(this);
}
public LetterSectionsListView(Context context, AttributeSet attrs) {
super(context, attrs);
super.setOnScrollListener(this);
}
public LetterSectionsListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
super.setOnScrollListener(this);
}
@Override
public void setAdapter(ListAdapter adapter) {
if (mAdapter == adapter) {
return;
}
headers.clear();
headersCache.clear();
if (adapter instanceof BaseSectionsAdapter) {
mAdapter = (BaseSectionsAdapter) adapter;
} else {
mAdapter = null;
}
super.setAdapter(adapter);
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (mOnScrollListener != null) {
mOnScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
}
if (mAdapter == null) {
return;
}
headersCache.addAll(headers);
headers.clear();
if (mAdapter.getCount() == 0) {
return;
}
if (currentFirst != firstVisibleItem || currentVisible != visibleItemCount) {
currentFirst = firstVisibleItem;
currentVisible = visibleItemCount;
sectionsCount = 1;
startSection = mAdapter.getSectionForPosition(firstVisibleItem);
int itemNum = firstVisibleItem + mAdapter.getCountForSection(startSection) - mAdapter.getPositionInSectionForPosition(firstVisibleItem);
while (true) {
if (itemNum >= firstVisibleItem + visibleItemCount) {
break;
}
itemNum += mAdapter.getCountForSection(startSection + sectionsCount);
sectionsCount++;
}
}
int itemNum = firstVisibleItem;
for (int a = startSection; a < startSection + sectionsCount; a++) {
View header = null;
if (!headersCache.isEmpty()) {
header = headersCache.get(0);
headersCache.remove(0);
}
header = getSectionHeaderView(a, header);
headers.add(header);
int count = mAdapter.getCountForSection(a);
if (a == startSection) {
int pos = mAdapter.getPositionInSectionForPosition(itemNum);
if (pos == count - 1) {
header.setTag(-header.getHeight());
} else if (pos == count - 2) {
View child = getChildAt(itemNum - firstVisibleItem);
int headerTop = 0;
if (child != null) {
headerTop = child.getTop();
} else {
headerTop = -AndroidUtilities.dp(100);
}
if (headerTop < 0) {
header.setTag(headerTop);
} else {
header.setTag(0);
}
} else {
header.setTag(0);
}
itemNum += count - mAdapter.getPositionInSectionForPosition(firstVisibleItem);
} else {
View child = getChildAt(itemNum - firstVisibleItem);
if (child != null) {
header.setTag(child.getTop());
} else {
header.setTag(-AndroidUtilities.dp(100));
}
itemNum += count;
}
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (mOnScrollListener != null) {
mOnScrollListener.onScrollStateChanged(view, scrollState);
}
}
private View getSectionHeaderView(int section, View oldView) {
boolean shouldLayout = oldView == null;
View view = mAdapter.getSectionHeaderView(section, oldView, this);
if (shouldLayout) {
ensurePinnedHeaderLayout(view, false);
}
return view;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mAdapter == null || headers.isEmpty()) {
return;
}
for (View header : headers) {
ensurePinnedHeaderLayout(header, true);
}
}
private void ensurePinnedHeaderLayout(View header, boolean forceLayout) {
if (header.isLayoutRequested() || forceLayout) {
ViewGroup.LayoutParams layoutParams = header.getLayoutParams();
int heightSpec = MeasureSpec.makeMeasureSpec(layoutParams.height, MeasureSpec.EXACTLY);
int widthSpec = MeasureSpec.makeMeasureSpec(layoutParams.width, MeasureSpec.EXACTLY);
try {
header.measure(widthSpec, heightSpec);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
header.layout(0, 0, header.getMeasuredWidth(), header.getMeasuredHeight());
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
if (mAdapter == null || headers.isEmpty()) {
return;
}
for (View header : headers) {
int saveCount = canvas.save();
int top = (Integer)header.getTag();
canvas.translate(LocaleController.isRTL ? getWidth() - header.getWidth() : 0, top);
canvas.clipRect(0, 0, getWidth(), header.getMeasuredHeight());
if (top < 0) {
canvas.saveLayerAlpha(0, top, header.getWidth(), top + canvas.getHeight(), (int)(255 * (1.0f + (float)top / (float)header.getMeasuredHeight())), Canvas.HAS_ALPHA_LAYER_SAVE_FLAG);
}
header.draw(canvas);
canvas.restoreToCount(saveCount);
}
}
@Override
public void setOnScrollListener(OnScrollListener l) {
mOnScrollListener = l;
}
public void setOnItemClickListener(LetterSectionsListView.OnItemClickListener listener) {
super.setOnItemClickListener(listener);
}
}

View File

@ -73,7 +73,7 @@ public class NumberPicker extends LinearLayout {
private OnScrollListener mOnScrollListener;
private Formatter mFormatter;
private long mLongPressUpdateInterval = DEFAULT_LONG_PRESS_UPDATE_INTERVAL;
private final SparseArray<String> mSelectorIndexToStringCache = new SparseArray<String>();
private final SparseArray<String> mSelectorIndexToStringCache = new SparseArray<>();
private final int[] mSelectorIndices = new int[SELECTOR_WHEEL_ITEM_COUNT];
private Paint mSelectorWheelPaint;
private Drawable mVirtualButtonPressedDrawable;

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,598 @@
/*
* 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.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.MotionEvent;
import android.widget.FrameLayout;
import org.telegram.android.AndroidUtilities;
import org.telegram.messenger.FileLog;
public class PhotoCropView extends FrameLayout {
public static interface PhotoCropViewDelegate {
public abstract void needMoveImageTo(float x, float y, float s, boolean animated);
}
private boolean freeformCrop = true;
private Paint rectPaint;
private Paint circlePaint;
private Paint halfPaint;
private Paint shadowPaint;
private float rectSizeX = 600;
private float rectSizeY = 600;
private int draggingState = 0;
private int orientation;
private float oldX = 0, oldY = 0;
private int bitmapWidth = 1, bitmapHeight = 1, bitmapX, bitmapY;
private float rectX = -1, rectY = -1;
private Bitmap bitmapToEdit;
private float bitmapGlobalScale = 1;
private float bitmapGlobalX = 0;
private float bitmapGlobalY = 0;
private PhotoCropViewDelegate delegate;
private RectF animationStartValues;
private RectF animationEndValues;
private Runnable animationRunnable;
public PhotoCropView(Context context) {
super(context);
rectPaint = new Paint();
rectPaint.setColor(0xb2ffffff);
rectPaint.setStrokeWidth(AndroidUtilities.dp(2));
rectPaint.setStyle(Paint.Style.STROKE);
circlePaint = new Paint();
circlePaint.setColor(0xffffffff);
halfPaint = new Paint();
halfPaint.setColor(0x7f000000);
shadowPaint = new Paint();
shadowPaint.setColor(0x1a000000);
setWillNotDraw(false);
}
public void setBitmap(Bitmap bitmap, int rotation, boolean freeform) {
bitmapToEdit = bitmap;
rectSizeX = 600;
rectSizeY = 600;
draggingState = 0;
oldX = 0;
oldY = 0;
bitmapWidth = 1;
bitmapHeight = 1;
rectX = -1;
rectY = -1;
freeformCrop = freeform;
orientation = rotation;
requestLayout();
}
public boolean onTouch(MotionEvent motionEvent) {
if (motionEvent == null) {
draggingState = 0;
return false;
}
float x = motionEvent.getX();
float y = motionEvent.getY();
int cornerSide = AndroidUtilities.dp(20);
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
if (rectX - cornerSide < x && rectX + cornerSide > x && rectY - cornerSide < y && rectY + cornerSide > y) {
draggingState = 1;
} else if (rectX - cornerSide + rectSizeX < x && rectX + cornerSide + rectSizeX > x && rectY - cornerSide < y && rectY + cornerSide > y) {
draggingState = 2;
} else if (rectX - cornerSide < x && rectX + cornerSide > x && rectY - cornerSide + rectSizeY < y && rectY + cornerSide + rectSizeY > y) {
draggingState = 3;
} else if (rectX - cornerSide + rectSizeX < x && rectX + cornerSide + rectSizeX > x && rectY - cornerSide + rectSizeY < y && rectY + cornerSide + rectSizeY > y) {
draggingState = 4;
} else {
if (freeformCrop) {
if (rectX + cornerSide < x && rectX - cornerSide + rectSizeX > x && rectY - cornerSide < y && rectY + cornerSide > y) {
draggingState = 5;
} else if (rectY + cornerSide < y && rectY - cornerSide + rectSizeY > y && rectX - cornerSide + rectSizeX < x && rectX + cornerSide + rectSizeX > x) {
draggingState = 6;
} else if (rectY + cornerSide < y && rectY - cornerSide + rectSizeY > y && rectX - cornerSide < x && rectX + cornerSide > x) {
draggingState = 7;
} else if (rectX + cornerSide < x && rectX - cornerSide + rectSizeX > x && rectY - cornerSide + rectSizeY < y && rectY + cornerSide + rectSizeY > y) {
draggingState = 8;
}
} else {
draggingState = 0;
}
}
if (draggingState != 0) {
cancelAnimationRunnable();
PhotoCropView.this.requestDisallowInterceptTouchEvent(true);
}
oldX = x;
oldY = y;
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
if (draggingState != 0) {
draggingState = 0;
startAnimationRunnable();
return true;
}
} else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE && draggingState != 0) {
float diffX = x - oldX;
float diffY = y - oldY;
float bitmapScaledWidth = bitmapWidth * bitmapGlobalScale;
float bitmapScaledHeight = bitmapHeight * bitmapGlobalScale;
float bitmapStartX = (getWidth() - AndroidUtilities.dp(28) - bitmapScaledWidth) / 2 + bitmapGlobalX + AndroidUtilities.dp(14);
float bitmapStartY = (getHeight() - AndroidUtilities.dp(28) - bitmapScaledHeight) / 2 + bitmapGlobalY + AndroidUtilities.dp(14);
float bitmapEndX = bitmapStartX + bitmapScaledWidth;
float bitmapEndY = bitmapStartY + bitmapScaledHeight;
float minSide = AndroidUtilities.getPixelsInCM(0.9f, true);
if (draggingState == 1 || draggingState == 5) {
if (draggingState != 5) {
if (rectSizeX - diffX < minSide) {
diffX = rectSizeX - minSide;
}
if (rectX + diffX < bitmapX) {
diffX = bitmapX - rectX;
}
if (rectX + diffX < bitmapStartX) {
bitmapGlobalX -= bitmapStartX - rectX - diffX;
delegate.needMoveImageTo(bitmapGlobalX, bitmapGlobalY, bitmapGlobalScale, false);
}
}
if (!freeformCrop) {
if (rectY + diffX < bitmapY) {
diffX = bitmapY - rectY;
}
if (rectY + diffX < bitmapStartY) {
bitmapGlobalY -= bitmapStartY - rectY - diffX;
delegate.needMoveImageTo(bitmapGlobalX, bitmapGlobalY, bitmapGlobalScale, false);
}
rectX += diffX;
rectY += diffX;
rectSizeX -= diffX;
rectSizeY -= diffX;
} else {
if (rectSizeY - diffY < minSide) {
diffY = rectSizeY - minSide;
}
if (rectY + diffY < bitmapY) {
diffY = bitmapY - rectY;
}
if (rectY + diffY < bitmapStartY) {
bitmapGlobalY -= bitmapStartY - rectY - diffY;
delegate.needMoveImageTo(bitmapGlobalX, bitmapGlobalY, bitmapGlobalScale, false);
}
if (draggingState != 5) {
rectX += diffX;
rectSizeX -= diffX;
}
rectY += diffY;
rectSizeY -= diffY;
}
} else if (draggingState == 2 || draggingState == 6) {
if (rectSizeX + diffX < minSide) {
diffX = -(rectSizeX - minSide);
}
if (rectX + rectSizeX + diffX > bitmapX + bitmapWidth) {
diffX = bitmapX + bitmapWidth - rectX - rectSizeX;
}
if (rectX + rectSizeX + diffX > bitmapEndX) {
bitmapGlobalX -= bitmapEndX - rectX - rectSizeX - diffX;
delegate.needMoveImageTo(bitmapGlobalX, bitmapGlobalY, bitmapGlobalScale, false);
}
if (!freeformCrop) {
if (rectY - diffX < bitmapY) {
diffX = rectY - bitmapY;
}
if (rectY - diffX < bitmapStartY) {
bitmapGlobalY -= bitmapStartY - rectY + diffX;
delegate.needMoveImageTo(bitmapGlobalX, bitmapGlobalY, bitmapGlobalScale, false);
}
rectY -= diffX;
rectSizeX += diffX;
rectSizeY += diffX;
} else {
if (draggingState != 6) {
if (rectSizeY - diffY < minSide) {
diffY = rectSizeY - minSide;
}
if (rectY + diffY < bitmapY) {
diffY = bitmapY - rectY;
}
if (rectY + diffY < bitmapStartY) {
bitmapGlobalY -= bitmapStartY - rectY - diffY;
delegate.needMoveImageTo(bitmapGlobalX, bitmapGlobalY, bitmapGlobalScale, false);
}
rectY += diffY;
rectSizeY -= diffY;
}
rectSizeX += diffX;
}
} else if (draggingState == 3 || draggingState == 7) {
if (rectSizeX - diffX < minSide) {
diffX = rectSizeX - minSide;
}
if (rectX + diffX < bitmapX) {
diffX = bitmapX - rectX;
}
if (rectX + diffX < bitmapStartX) {
bitmapGlobalX -= bitmapStartX - rectX - diffX;
delegate.needMoveImageTo(bitmapGlobalX, bitmapGlobalY, bitmapGlobalScale, false);
}
if (!freeformCrop) {
if (rectY + rectSizeX - diffX > bitmapY + bitmapHeight) {
diffX = rectY + rectSizeX - bitmapY - bitmapHeight;
}
if (rectY + rectSizeX - diffX > bitmapEndY) {
bitmapGlobalY -= bitmapEndY - rectY - rectSizeX + diffX;
delegate.needMoveImageTo(bitmapGlobalX, bitmapGlobalY, bitmapGlobalScale, false);
}
rectX += diffX;
rectSizeX -= diffX;
rectSizeY -= diffX;
} else {
if (draggingState != 7) {
if (rectY + rectSizeY + diffY > bitmapY + bitmapHeight) {
diffY = bitmapY + bitmapHeight - rectY - rectSizeY;
}
if (rectY + rectSizeY + diffY > bitmapEndY) {
bitmapGlobalY -= bitmapEndY - rectY - rectSizeY - diffY;
delegate.needMoveImageTo(bitmapGlobalX, bitmapGlobalY, bitmapGlobalScale, false);
}
rectSizeY += diffY;
if (rectSizeY < minSide) {
rectSizeY = minSide;
}
}
rectX += diffX;
rectSizeX -= diffX;
}
} else if (draggingState == 4 || draggingState == 8) {
if (draggingState != 8) {
if (rectX + rectSizeX + diffX > bitmapX + bitmapWidth) {
diffX = bitmapX + bitmapWidth - rectX - rectSizeX;
}
if (rectX + rectSizeX + diffX > bitmapEndX) {
bitmapGlobalX -= bitmapEndX - rectX - rectSizeX - diffX;
delegate.needMoveImageTo(bitmapGlobalX, bitmapGlobalY, bitmapGlobalScale, false);
}
}
if (!freeformCrop) {
if (rectY + rectSizeX + diffX > bitmapY + bitmapHeight) {
diffX = bitmapY + bitmapHeight - rectY - rectSizeX;
}
if (rectY + rectSizeX + diffX > bitmapEndY) {
bitmapGlobalY -= bitmapEndY - rectY - rectSizeX - diffX;
delegate.needMoveImageTo(bitmapGlobalX, bitmapGlobalY, bitmapGlobalScale, false);
}
rectSizeX += diffX;
rectSizeY += diffX;
} else {
if (rectY + rectSizeY + diffY > bitmapY + bitmapHeight) {
diffY = bitmapY + bitmapHeight - rectY - rectSizeY;
}
if (rectY + rectSizeY + diffY > bitmapEndY) {
bitmapGlobalY -= bitmapEndY - rectY - rectSizeY - diffY;
delegate.needMoveImageTo(bitmapGlobalX, bitmapGlobalY, bitmapGlobalScale, false);
}
if (draggingState != 8) {
rectSizeX += diffX;
}
rectSizeY += diffY;
}
if (rectSizeX < minSide) {
rectSizeX = minSide;
}
if (rectSizeY < minSide) {
rectSizeY = minSide;
}
}
oldX = x;
oldY = y;
invalidate();
}
return draggingState != 0;
}
public float getRectX() {
return rectX - AndroidUtilities.dp(14);
}
public float getRectY() {
return rectY - AndroidUtilities.dp(14);
}
public float getRectSizeX() {
return rectSizeX;
}
public float getRectSizeY() {
return rectSizeY;
}
public float getBitmapX() {
return bitmapX - AndroidUtilities.dp(14);
}
public float getBitmapY() {
return bitmapY - AndroidUtilities.dp(14);
}
public float getLimitX() {
return rectX - ((int) Math.max(0, Math.ceil((getWidth() - AndroidUtilities.dp(28) - bitmapWidth * bitmapGlobalScale) / 2)) + AndroidUtilities.dp(14));
}
public float getLimitY() {
return rectY - ((int) Math.max(0, Math.ceil((getHeight() - AndroidUtilities.dp(28) - bitmapHeight * bitmapGlobalScale) / 2)) + AndroidUtilities.dp(14));
}
public float getLimitWidth() {
return getWidth() - AndroidUtilities.dp(14) - rectX - (int) Math.max(0, Math.ceil((getWidth() - AndroidUtilities.dp(28) - bitmapWidth * bitmapGlobalScale) / 2)) - rectSizeX;
}
public float getLimitHeight() {
return getHeight() - AndroidUtilities.dp(14) - rectY - (int) Math.max(0, Math.ceil((getHeight() - AndroidUtilities.dp(28) - bitmapHeight * bitmapGlobalScale) / 2)) - rectSizeY;
}
private Bitmap createBitmap(int x, int y, int w, int h) {
Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setFilterBitmap(true);
Matrix matrix = new Matrix();
matrix.setTranslate(-bitmapToEdit.getWidth() / 2, -bitmapToEdit.getHeight() / 2);
matrix.postRotate(orientation);
if (orientation == 90 || orientation == 270) {
matrix.postTranslate(bitmapToEdit.getHeight() / 2 - x, bitmapToEdit.getWidth() / 2 - y);
} else {
matrix.postTranslate(bitmapToEdit.getWidth() / 2 - x, bitmapToEdit.getHeight() / 2 - y);
}
canvas.drawBitmap(bitmapToEdit, matrix, paint);
try {
canvas.setBitmap(null);
} catch (Exception e) {
//don't promt, this will crash on 2.x
}
return bitmap;
}
public Bitmap getBitmap() {
float bitmapScaledWidth = bitmapWidth * bitmapGlobalScale;
float bitmapScaledHeight = bitmapHeight * bitmapGlobalScale;
float bitmapStartX = (getWidth() - AndroidUtilities.dp(28) - bitmapScaledWidth) / 2 + bitmapGlobalX + AndroidUtilities.dp(14);
float bitmapStartY = (getHeight() - AndroidUtilities.dp(28) - bitmapScaledHeight) / 2 + bitmapGlobalY + AndroidUtilities.dp(14);
float percX = (rectX - bitmapStartX) / bitmapScaledWidth;
float percY = (rectY - bitmapStartY) / bitmapScaledHeight;
float percSizeX = rectSizeX / bitmapScaledWidth;
float percSizeY = rectSizeY / bitmapScaledHeight;
int width;
int height;
if (orientation == 90 || orientation == 270) {
width = bitmapToEdit.getHeight();
height = bitmapToEdit.getWidth();
} else {
width = bitmapToEdit.getWidth();
height = bitmapToEdit.getHeight();
}
int x = (int) (percX * width);
int y = (int) (percY * height);
int sizeX = (int) (percSizeX * width);
int sizeY = (int) (percSizeY * height);
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
if (x + sizeX > width) {
sizeX = width - x;
}
if (y + sizeY > height) {
sizeY = height - y;
}
try {
return createBitmap(x, y, sizeX, sizeY);
} catch (Throwable e) {
FileLog.e("tmessags", e);
System.gc();
try {
return createBitmap(x, y, sizeX, sizeY);
} catch (Throwable e2) {
FileLog.e("tmessages", e2);
}
}
return null;
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawRect(0, 0, getWidth(), rectY, halfPaint);
canvas.drawRect(0, rectY, rectX, rectY + rectSizeY, halfPaint);
canvas.drawRect(rectX + rectSizeX, rectY, getWidth(), rectY + rectSizeY, halfPaint);
canvas.drawRect(0, rectY + rectSizeY, getWidth(), getHeight(), halfPaint);
int side = AndroidUtilities.dp(1);
canvas.drawRect(rectX - side * 2, rectY - side * 2, rectX - side * 2 + AndroidUtilities.dp(20), rectY, circlePaint);
canvas.drawRect(rectX - side * 2, rectY - side * 2, rectX, rectY - side * 2 + AndroidUtilities.dp(20), circlePaint);
canvas.drawRect(rectX + rectSizeX + side * 2 - AndroidUtilities.dp(20), rectY - side * 2, rectX + rectSizeX + side * 2, rectY, circlePaint);
canvas.drawRect(rectX + rectSizeX, rectY - side * 2, rectX + rectSizeX + side * 2, rectY - side * 2 + AndroidUtilities.dp(20), circlePaint);
canvas.drawRect(rectX - side * 2, rectY + rectSizeY + side * 2 - AndroidUtilities.dp(20), rectX, rectY + rectSizeY + side * 2, circlePaint);
canvas.drawRect(rectX - side * 2, rectY + rectSizeY, rectX - side * 2 + AndroidUtilities.dp(20), rectY + rectSizeY + side * 2, circlePaint);
canvas.drawRect(rectX + rectSizeX + side * 2 - AndroidUtilities.dp(20), rectY + rectSizeY, rectX + rectSizeX + side * 2, rectY + rectSizeY + side * 2, circlePaint);
canvas.drawRect(rectX + rectSizeX, rectY + rectSizeY + side * 2 - AndroidUtilities.dp(20), rectX + rectSizeX + side * 2, rectY + rectSizeY + side * 2, circlePaint);
for (int a = 1; a < 3; a++) {
canvas.drawRect(rectX + rectSizeX / 3 * a - side, rectY, rectX + side * 2 + rectSizeX / 3 * a, rectY + rectSizeY, shadowPaint);
canvas.drawRect(rectX, rectY + rectSizeY / 3 * a - side, rectX + rectSizeX, rectY + rectSizeY / 3 * a + side * 2, shadowPaint);
}
for (int a = 1; a < 3; a++) {
canvas.drawRect(rectX + rectSizeX / 3 * a, rectY, rectX + side + rectSizeX / 3 * a, rectY + rectSizeY, circlePaint);
canvas.drawRect(rectX, rectY + rectSizeY / 3 * a, rectX + rectSizeX, rectY + rectSizeY / 3 * a + side, circlePaint);
}
canvas.drawRect(rectX, rectY, rectX + rectSizeX, rectY + rectSizeY, rectPaint);
}
public void setBitmapParams(float scale, float x, float y) {
bitmapGlobalScale = scale;
bitmapGlobalX = x;
bitmapGlobalY = y;
}
public void startAnimationRunnable() {
if (animationRunnable != null) {
return;
}
animationRunnable = new Runnable() {
@Override
public void run() {
if (animationRunnable == this) {
animationRunnable = null;
animateToFill();
}
}
};
AndroidUtilities.runOnUIThread(animationRunnable, 1500);
}
public void cancelAnimationRunnable() {
if (animationRunnable != null) {
AndroidUtilities.cancelRunOnUIThread(animationRunnable);
animationRunnable = null;
animationStartValues = null;
animationEndValues = null;
}
}
public void setAnimationProgress(float animationProgress) {
if (animationStartValues != null) {
if (animationProgress == 1) {
rectX = animationEndValues.left;
rectY = animationEndValues.top;
rectSizeX = animationEndValues.right;
rectSizeY = animationEndValues.bottom;
animationStartValues = null;
animationEndValues = null;
} else {
rectX = animationStartValues.left + (animationEndValues.left - animationStartValues.left) * animationProgress;
rectY = animationStartValues.top + (animationEndValues.top - animationStartValues.top) * animationProgress;
rectSizeX = animationStartValues.right + (animationEndValues.right - animationStartValues.right) * animationProgress;
rectSizeY = animationStartValues.bottom + (animationEndValues.bottom - animationStartValues.bottom) * animationProgress;
}
invalidate();
}
}
public void animateToFill() {
float scaleToX = bitmapWidth / rectSizeX;
float scaleToY = bitmapHeight / rectSizeY;
float scaleTo = scaleToX > scaleToY ? scaleToY : scaleToX;
if (scaleTo > 1 && scaleTo * bitmapGlobalScale > 3) {
scaleTo = 3 / bitmapGlobalScale;
} else if (scaleTo < 1 && scaleTo * bitmapGlobalScale < 1) {
scaleTo = 1 / bitmapGlobalScale;
}
float newSizeX = rectSizeX * scaleTo;
float newSizeY = rectSizeY * scaleTo;
float newX = (getWidth() - AndroidUtilities.dp(28) - newSizeX) / 2 + AndroidUtilities.dp(14);
float newY = (getHeight() - AndroidUtilities.dp(28) - newSizeY) / 2 + AndroidUtilities.dp(14);
animationStartValues = new RectF(rectX, rectY, rectSizeX, rectSizeY);
animationEndValues = new RectF(newX, newY, newSizeX, newSizeY);
float newBitmapGlobalX = newX + getWidth() / 2 * (scaleTo - 1) + (bitmapGlobalX - rectX) * scaleTo;
float newBitmapGlobalY = newY + getHeight() / 2 * (scaleTo - 1) + (bitmapGlobalY - rectY) * scaleTo;
delegate.needMoveImageTo(newBitmapGlobalX, newBitmapGlobalY, bitmapGlobalScale * scaleTo, true);
}
public void setDelegate(PhotoCropViewDelegate delegate) {
this.delegate = delegate;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (bitmapToEdit == null) {
return;
}
int viewWidth = getWidth() - AndroidUtilities.dp(28);
int viewHeight = getHeight() - AndroidUtilities.dp(28);
float bitmapW;
float bitmapH;
if (orientation == 90 || orientation == 270) {
bitmapW = bitmapToEdit.getHeight();
bitmapH = bitmapToEdit.getWidth();
} else {
bitmapW = bitmapToEdit.getWidth();
bitmapH = bitmapToEdit.getHeight();
}
float scaleX = viewWidth / bitmapW;
float scaleY = viewHeight / bitmapH;
if (scaleX > scaleY) {
bitmapH = viewHeight;
bitmapW = (int) Math.ceil(bitmapW * scaleY);
} else {
bitmapW = viewWidth;
bitmapH = (int) Math.ceil(bitmapH * scaleX);
}
float percX = (rectX - bitmapX) / bitmapWidth;
float percY = (rectY - bitmapY) / bitmapHeight;
float percSizeX = rectSizeX / bitmapWidth;
float percSizeY = rectSizeY / bitmapHeight;
bitmapWidth = (int) bitmapW;
bitmapHeight = (int) bitmapH;
bitmapX = (int) Math.ceil((viewWidth - bitmapWidth) / 2 + AndroidUtilities.dp(14));
bitmapY = (int) Math.ceil((viewHeight - bitmapHeight) / 2 + AndroidUtilities.dp(14));
if (rectX == -1 && rectY == -1) {
if (freeformCrop) {
rectY = bitmapY;
rectX = bitmapX;
rectSizeX = bitmapWidth;
rectSizeY = bitmapHeight;
} else {
if (bitmapWidth > bitmapHeight) {
rectY = bitmapY;
rectX = (viewWidth - bitmapHeight) / 2 + AndroidUtilities.dp(14);
rectSizeX = bitmapHeight;
rectSizeY = bitmapHeight;
} else {
rectX = bitmapX;
rectY = (viewHeight - bitmapWidth) / 2 + AndroidUtilities.dp(14);
rectSizeX = bitmapWidth;
rectSizeY = bitmapWidth;
}
}
} else {
rectX = percX * bitmapWidth + bitmapX;
rectY = percY * bitmapHeight + bitmapY;
rectSizeX = percSizeX * bitmapWidth;
rectSizeY = percSizeY * bitmapHeight;
}
}
}

View File

@ -0,0 +1,132 @@
/*
* 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.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;
import org.telegram.android.AndroidUtilities;
public class PhotoEditorSeekBar extends View {
private Paint innerPaint = new Paint();
private Paint outerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private int thumbSize = AndroidUtilities.dp(16);
private int thumbDX = 0;
private float progress = 0;
private boolean pressed = false;
private int minValue;
private int maxValue;
private PhotoEditorSeekBarDelegate delegate;
public abstract interface PhotoEditorSeekBarDelegate {
public void onProgressChanged();
}
public PhotoEditorSeekBar(Context context) {
super(context);
innerPaint.setColor(0x99383838);
outerPaint.setColor(0xff53aeef);
}
public void setDelegate(PhotoEditorSeekBarDelegate delegate) {
this.delegate = delegate;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event == null) {
return false;
}
float x = event.getX();
float y = event.getY();
float thumbX = (int)((getMeasuredWidth() - thumbSize) * progress);
if (event.getAction() == MotionEvent.ACTION_DOWN) {
int additionWidth = (getMeasuredHeight() - thumbSize) / 2;
if (thumbX - additionWidth <= x && x <= thumbX + thumbSize + additionWidth && y >= 0 && y <= getMeasuredHeight()) {
pressed = true;
thumbDX = (int)(x - thumbX);
getParent().requestDisallowInterceptTouchEvent(true);
invalidate();
return true;
}
} else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
if (pressed) {
pressed = false;
invalidate();
return true;
}
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (pressed) {
thumbX = (int)(x - thumbDX);
if (thumbX < 0) {
thumbX = 0;
} else if (thumbX > getMeasuredWidth() - thumbSize) {
thumbX = getMeasuredWidth() - thumbSize;
}
progress = thumbX / (getMeasuredWidth() - thumbSize);
if (delegate != null) {
delegate.onProgressChanged();
}
invalidate();
return true;
}
}
return false;
}
public void setProgress(int progress) {
setProgress(progress, true);
}
public void setProgress(int progress, boolean notify) {
if (progress < minValue) {
progress = minValue;
} else if (progress > maxValue) {
progress = maxValue;
}
this.progress = (progress - minValue) / (float) (maxValue - minValue);
invalidate();
if (notify && delegate != null) {
delegate.onProgressChanged();
}
}
public int getProgress() {
return (int) (minValue + progress * (maxValue - minValue));
}
public void setMinMax(int min, int max) {
minValue = min;
maxValue = max;
}
@Override
protected void onDraw(Canvas canvas) {
int y = (getMeasuredHeight() - thumbSize) / 2;
int thumbX = (int)((getMeasuredWidth() - thumbSize) * progress);
canvas.drawRect(thumbSize / 2, getMeasuredHeight() / 2 - AndroidUtilities.dp(1), getMeasuredWidth() - thumbSize / 2, getMeasuredHeight() / 2 + AndroidUtilities.dp(1), innerPaint);
if (minValue == 0) {
canvas.drawRect(thumbSize / 2, getMeasuredHeight() / 2 - AndroidUtilities.dp(1), thumbX, getMeasuredHeight() / 2 + AndroidUtilities.dp(1), outerPaint);
} else {
if (progress > 0.5f) {
canvas.drawRect(getMeasuredWidth() / 2 - AndroidUtilities.dp(1), (getMeasuredHeight() - thumbSize) / 2, getMeasuredWidth() / 2, (getMeasuredHeight() + thumbSize) / 2, outerPaint);
canvas.drawRect(getMeasuredWidth() / 2, getMeasuredHeight() / 2 - AndroidUtilities.dp(1), thumbX, getMeasuredHeight() / 2 + AndroidUtilities.dp(1), outerPaint);
} else {
canvas.drawRect(getMeasuredWidth() / 2, (getMeasuredHeight() - thumbSize) / 2, getMeasuredWidth() / 2 + AndroidUtilities.dp(1), (getMeasuredHeight() + thumbSize) / 2, outerPaint);
canvas.drawRect(thumbX, getMeasuredHeight() / 2 - AndroidUtilities.dp(1), getMeasuredWidth() / 2, getMeasuredHeight() / 2 + AndroidUtilities.dp(1), outerPaint);
}
}
canvas.drawCircle(thumbX + thumbSize / 2, y + thumbSize / 2, thumbSize / 2, outerPaint);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -20,52 +20,43 @@ import org.telegram.android.AndroidUtilities;
import org.telegram.android.LocaleController;
import org.telegram.messenger.R;
public class PhotoPickerBottomLayout extends LinearLayout {
public class PhotoPickerBottomLayout extends FrameLayout {
public FrameLayout doneButton;
public LinearLayout doneButton;
public TextView cancelButton;
public TextView doneButtonTextView;
public TextView doneButtonBadgeTextView;
public PhotoPickerBottomLayout(Context context) {
super(context);
setBackgroundColor(0xff333333);
setOrientation(HORIZONTAL);
setBackgroundColor(0xff1a1a1a);
cancelButton = new TextView(context);
cancelButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
cancelButton.setTextColor(0xffffffff);
cancelButton.setGravity(Gravity.CENTER);
cancelButton.setBackgroundResource(R.drawable.bar_selector_picker);
cancelButton.setPadding(AndroidUtilities.dp(3), 0, 0, 0);
cancelButton.setPadding(AndroidUtilities.dp(29), 0, AndroidUtilities.dp(29), 0);
cancelButton.setText(LocaleController.getString("Cancel", R.string.Cancel).toUpperCase());
cancelButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
addView(cancelButton);
LayoutParams layoutParams = (LayoutParams) cancelButton.getLayoutParams();
layoutParams.width = 0;
layoutParams.width = LayoutParams.WRAP_CONTENT;
layoutParams.height = LayoutParams.MATCH_PARENT;
layoutParams.weight = 1;
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
cancelButton.setLayoutParams(layoutParams);
doneButton = new FrameLayout(context);
doneButton = new LinearLayout(context);
doneButton.setOrientation(LinearLayout.HORIZONTAL);
doneButton.setBackgroundResource(R.drawable.bar_selector_picker);
doneButton.setPadding(0, 0, AndroidUtilities.dp(3), 0);
doneButton.setPadding(AndroidUtilities.dp(29), 0, AndroidUtilities.dp(29), 0);
addView(doneButton);
layoutParams = (LayoutParams) doneButton.getLayoutParams();
layoutParams.width = 0;
layoutParams.width = LayoutParams.WRAP_CONTENT;
layoutParams.height = LayoutParams.MATCH_PARENT;
layoutParams.weight = 1;
layoutParams.gravity = Gravity.TOP | Gravity.RIGHT;
doneButton.setLayoutParams(layoutParams);
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setOrientation(HORIZONTAL);
doneButton.addView(linearLayout);
FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) linearLayout.getLayoutParams();
layoutParams1.width = FrameLayout.LayoutParams.WRAP_CONTENT;
layoutParams1.height = FrameLayout.LayoutParams.WRAP_CONTENT;
layoutParams1.gravity = Gravity.CENTER;
linearLayout.setLayoutParams(layoutParams1);
doneButtonBadgeTextView = new TextView(context);
doneButtonBadgeTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
doneButtonBadgeTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
@ -74,28 +65,27 @@ public class PhotoPickerBottomLayout extends LinearLayout {
doneButtonBadgeTextView.setBackgroundResource(R.drawable.photobadge);
doneButtonBadgeTextView.setMinWidth(AndroidUtilities.dp(23));
doneButtonBadgeTextView.setPadding(AndroidUtilities.dp(8), 0, AndroidUtilities.dp(8), AndroidUtilities.dp(1));
linearLayout.addView(doneButtonBadgeTextView);
layoutParams = (LayoutParams) doneButtonBadgeTextView.getLayoutParams();
layoutParams.width = LayoutParams.WRAP_CONTENT;
layoutParams.height = AndroidUtilities.dp(23);
layoutParams.rightMargin = AndroidUtilities.dp(10);
doneButtonBadgeTextView.setLayoutParams(layoutParams);
doneButton.addView(doneButtonBadgeTextView);
LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) doneButtonBadgeTextView.getLayoutParams();
layoutParams1.width = LayoutParams.WRAP_CONTENT;
layoutParams1.height = AndroidUtilities.dp(23);
layoutParams1.rightMargin = AndroidUtilities.dp(10);
layoutParams1.gravity = Gravity.CENTER_VERTICAL;
doneButtonBadgeTextView.setLayoutParams(layoutParams1);
doneButtonTextView = new TextView(context);
doneButtonTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
doneButtonTextView.setTextColor(0xffffffff);
doneButtonTextView.setGravity(Gravity.CENTER);
doneButtonTextView.setCompoundDrawablePadding(AndroidUtilities.dp(8));
doneButtonTextView.setBackgroundResource(R.drawable.bar_selector_picker);
doneButtonTextView.setPadding(AndroidUtilities.dp(3), 0, 0, 0);
doneButtonTextView.setText(LocaleController.getString("Send", R.string.Send).toUpperCase());
doneButtonTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
linearLayout.addView(doneButtonTextView);
layoutParams = (LayoutParams) doneButtonTextView.getLayoutParams();
layoutParams.width = LayoutParams.WRAP_CONTENT;
layoutParams.gravity = Gravity.CENTER_VERTICAL;
layoutParams.height = LayoutParams.WRAP_CONTENT;
doneButtonTextView.setLayoutParams(layoutParams);
doneButton.addView(doneButtonTextView);
layoutParams1 = (LinearLayout.LayoutParams) doneButtonTextView.getLayoutParams();
layoutParams1.width = LayoutParams.WRAP_CONTENT;
layoutParams1.gravity = Gravity.CENTER_VERTICAL;
layoutParams1.height = LayoutParams.WRAP_CONTENT;
doneButtonTextView.setLayoutParams(layoutParams1);
}
public void updateSelectedCount(int count, boolean disable) {
@ -103,12 +93,10 @@ public class PhotoPickerBottomLayout extends LinearLayout {
doneButtonBadgeTextView.setVisibility(View.GONE);
if (disable) {
doneButtonTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.selectphoto_small_grey, 0, 0, 0);
doneButtonTextView.setTextColor(0xff999999);
doneButton.setEnabled(false);
} else {
doneButtonTextView.setTextColor(0xffffffff);
doneButtonTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.selectphoto_small_active, 0, 0, 0);
}
} else {
doneButtonTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);

View File

@ -1,9 +1,9 @@
/*
* This is the source code of Telegram for Android v. 1.7.x.
* 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-2014.
* Copyright Nikolai Kudashov, 2013-2015.
*/
package org.telegram.ui.Components;
@ -12,7 +12,6 @@ import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListAdapter;
import android.widget.ListView;
@ -22,18 +21,12 @@ import org.telegram.android.LocaleController;
import org.telegram.messenger.FileLog;
import org.telegram.ui.Adapters.BaseSectionsAdapter;
import java.util.ArrayList;
public class SectionsListView extends ListView implements AbsListView.OnScrollListener {
private ArrayList<View> headers = new ArrayList<View>();
private ArrayList<View> headersCache = new ArrayList<View>();
private View pinnedHeader;
private OnScrollListener mOnScrollListener;
private BaseSectionsAdapter mAdapter;
private int currentFirst = -1;
private int currentVisible = -1;
private int startSection;
private int sectionsCount;
private int currentStartSection = -1;
public SectionsListView(Context context) {
super(context);
@ -55,8 +48,7 @@ public class SectionsListView extends ListView implements AbsListView.OnScrollLi
if (mAdapter == adapter) {
return;
}
headers.clear();
headersCache.clear();
pinnedHeader = null;
if (adapter instanceof BaseSectionsAdapter) {
mAdapter = (BaseSectionsAdapter) adapter;
} else {
@ -74,69 +66,38 @@ public class SectionsListView extends ListView implements AbsListView.OnScrollLi
return;
}
headersCache.addAll(headers);
headers.clear();
if (mAdapter.getCount() == 0) {
return;
}
if (currentFirst != firstVisibleItem || currentVisible != visibleItemCount) {
currentFirst = firstVisibleItem;
currentVisible = visibleItemCount;
sectionsCount = 1;
startSection = mAdapter.getSectionForPosition(firstVisibleItem);
int itemNum = firstVisibleItem + mAdapter.getCountForSection(startSection) - mAdapter.getPositionInSectionForPosition(firstVisibleItem);
while (true) {
if (itemNum >= firstVisibleItem + visibleItemCount) {
break;
}
itemNum += mAdapter.getCountForSection(startSection + sectionsCount);
sectionsCount++;
}
int startSection = mAdapter.getSectionForPosition(firstVisibleItem);
if (currentStartSection != startSection || pinnedHeader == null) {
pinnedHeader = getSectionHeaderView(startSection, pinnedHeader);
currentStartSection = startSection;
}
int itemNum = firstVisibleItem;
for (int a = startSection; a < startSection + sectionsCount; a++) {
View header = null;
if (!headersCache.isEmpty()) {
header = headersCache.get(0);
headersCache.remove(0);
}
header = getSectionHeaderView(a, header);
headers.add(header);
int count = mAdapter.getCountForSection(a);
if (a == startSection) {
int pos = mAdapter.getPositionInSectionForPosition(itemNum);
if (pos == count - 1) {
header.setTag(-header.getHeight());
} else if (pos == count - 2) {
View child = getChildAt(itemNum - firstVisibleItem);
int headerTop = 0;
if (child != null) {
headerTop = child.getTop();
} else {
headerTop = -AndroidUtilities.dp(100);
}
if (headerTop < 0) {
header.setTag(headerTop);
} else {
header.setTag(0);
}
} else {
header.setTag(0);
int count = mAdapter.getCountForSection(startSection);
int pos = mAdapter.getPositionInSectionForPosition(firstVisibleItem);
if (pos == count - 1) {
View child = getChildAt(0);
int headerHeight = pinnedHeader.getHeight();
int headerTop = 0;
if (child != null) {
int available = child.getTop() + child.getHeight();
if (available < headerHeight) {
headerTop = available - headerHeight;
}
itemNum += count - mAdapter.getPositionInSectionForPosition(firstVisibleItem);
} else {
View child = getChildAt(itemNum - firstVisibleItem);
if (child != null) {
header.setTag(child.getTop());
} else {
header.setTag(-AndroidUtilities.dp(100));
}
itemNum += count;
headerTop = -AndroidUtilities.dp(100);
}
if (headerTop < 0) {
pinnedHeader.setTag(headerTop);
} else {
pinnedHeader.setTag(0);
}
} else {
pinnedHeader.setTag(0);
}
invalidate();
@ -161,19 +122,16 @@ public class SectionsListView extends ListView implements AbsListView.OnScrollLi
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mAdapter == null || headers.isEmpty()) {
if (mAdapter == null || pinnedHeader == null) {
return;
}
for (View header : headers) {
ensurePinnedHeaderLayout(header, true);
}
ensurePinnedHeaderLayout(pinnedHeader, true);
}
private void ensurePinnedHeaderLayout(View header, boolean forceLayout) {
if (header.isLayoutRequested() || forceLayout) {
ViewGroup.LayoutParams layoutParams = header.getLayoutParams();
int heightSpec = MeasureSpec.makeMeasureSpec(layoutParams.height, MeasureSpec.EXACTLY);
int widthSpec = MeasureSpec.makeMeasureSpec(layoutParams.width, MeasureSpec.EXACTLY);
int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY);
int heightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
try {
header.measure(widthSpec, heightSpec);
} catch (Exception e) {
@ -186,20 +144,15 @@ public class SectionsListView extends ListView implements AbsListView.OnScrollLi
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
if (mAdapter == null || headers.isEmpty()) {
if (mAdapter == null || pinnedHeader == null) {
return;
}
for (View header : headers) {
int saveCount = canvas.save();
int top = (Integer)header.getTag();
canvas.translate(LocaleController.isRTL ? getWidth() - header.getWidth() : 0, top);
canvas.clipRect(0, 0, getWidth(), header.getMeasuredHeight());
if (top < 0) {
canvas.saveLayerAlpha(0, top, header.getWidth(), top + canvas.getHeight(), (int)(255 * (1.0f + (float)top / (float)header.getMeasuredHeight())), Canvas.HAS_ALPHA_LAYER_SAVE_FLAG);
}
header.draw(canvas);
canvas.restoreToCount(saveCount);
}
int saveCount = canvas.save();
int top = (Integer)pinnedHeader.getTag();
canvas.translate(LocaleController.isRTL ? getWidth() - pinnedHeader.getWidth() : 0, top);
canvas.clipRect(0, 0, getWidth(), pinnedHeader.getMeasuredHeight());
pinnedHeader.draw(canvas);
canvas.restoreToCount(saveCount);
}
@Override
@ -207,7 +160,7 @@ public class SectionsListView extends ListView implements AbsListView.OnScrollLi
mOnScrollListener = l;
}
public void setOnItemClickListener(SectionsListView.OnItemClickListener listener) {
public void setOnItemClickListener(OnItemClickListener listener) {
super.setOnItemClickListener(listener);
}
}

View File

@ -11,6 +11,7 @@ package org.telegram.ui.Components;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.RelativeLayout;
@ -22,7 +23,8 @@ public class SizeNotifierRelativeLayout extends RelativeLayout {
private Rect rect = new Rect();
private Drawable backgroundDrawable;
public SizeNotifierRelativeLayoutDelegate delegate;
private int keyboardHeight;
private SizeNotifierRelativeLayoutDelegate delegate;
public abstract interface SizeNotifierRelativeLayoutDelegate {
public abstract void onSizeChanged(int keyboardHeight);
@ -56,6 +58,10 @@ public class SizeNotifierRelativeLayout extends RelativeLayout {
return backgroundDrawable;
}
public void setDelegate(SizeNotifierRelativeLayoutDelegate delegate) {
this.delegate = delegate;
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
@ -63,7 +69,7 @@ public class SizeNotifierRelativeLayout extends RelativeLayout {
View rootView = this.getRootView();
int usableViewHeight = rootView.getHeight() - AndroidUtilities.statusBarHeight - AndroidUtilities.getViewInset(rootView);
this.getWindowVisibleDisplayFrame(rect);
int keyboardHeight = usableViewHeight - (rect.bottom - rect.top);
keyboardHeight = usableViewHeight - (rect.bottom - rect.top);
delegate.onSizeChanged(keyboardHeight);
}
}
@ -71,15 +77,20 @@ public class SizeNotifierRelativeLayout extends RelativeLayout {
@Override
protected void onDraw(Canvas canvas) {
if (backgroundDrawable != null) {
float scaleX = (float)getMeasuredWidth() / (float)backgroundDrawable.getIntrinsicWidth();
float scaleY = (float)getMeasuredHeight() / (float)backgroundDrawable.getIntrinsicHeight();
float scale = scaleX < scaleY ? scaleY : scaleX;
int width = (int)Math.ceil(backgroundDrawable.getIntrinsicWidth() * scale);
int height = (int)Math.ceil(backgroundDrawable.getIntrinsicHeight() * scale);
int x = (getMeasuredWidth() - width) / 2;
int y = (getMeasuredHeight() - height) / 2;
backgroundDrawable.setBounds(x, y, x + width, y + height);
backgroundDrawable.draw(canvas);
if (backgroundDrawable instanceof ColorDrawable) {
backgroundDrawable.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight());
backgroundDrawable.draw(canvas);
} else {
float scaleX = (float) getMeasuredWidth() / (float) backgroundDrawable.getIntrinsicWidth();
float scaleY = (float) (getMeasuredHeight() + keyboardHeight) / (float) backgroundDrawable.getIntrinsicHeight();
float scale = scaleX < scaleY ? scaleY : scaleX;
int width = (int) Math.ceil(backgroundDrawable.getIntrinsicWidth() * scale);
int height = (int) Math.ceil(backgroundDrawable.getIntrinsicHeight() * scale);
int x = (getMeasuredWidth() - width) / 2;
int y = (getMeasuredHeight() - height + keyboardHeight) / 2;
backgroundDrawable.setBounds(x, y, x + width, y + height);
backgroundDrawable.draw(canvas);
}
} else {
super.onDraw(canvas);
}

View File

@ -78,7 +78,7 @@ public class ContactAddActivity extends BaseFragment implements NotificationCent
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);

View File

@ -15,6 +15,7 @@ import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
@ -47,7 +48,7 @@ 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.Components.SectionsListView;
import org.telegram.ui.Components.LetterSectionsListView;
import java.util.ArrayList;
import java.util.HashMap;
@ -56,7 +57,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
private BaseSectionsAdapter listViewAdapter;
private TextView emptyTextView;
private SectionsListView listView;
private LetterSectionsListView listView;
private ContactsSearchAdapter searchListViewAdapter;
private boolean searchWas;
@ -87,6 +88,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
NotificationCenter.getInstance().addObserver(this, NotificationCenter.contactsDidLoaded);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.encryptedChatCreated);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.closeChats);
if (arguments != null) {
onlyUsers = getArguments().getBoolean("onlyUsers", false);
destroyAfterSelect = arguments.getBoolean("destroyAfterSelect", false);
@ -109,11 +111,12 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.contactsDidLoaded);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.encryptedChatCreated);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.closeChats);
delegate = null;
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
searching = false;
searchWas = false;
@ -124,7 +127,11 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
if (returnAsResult) {
actionBar.setTitle(LocaleController.getString("SelectContact", R.string.SelectContact));
} else {
actionBar.setTitle(LocaleController.getString("NewMessageTitle", R.string.NewMessageTitle));
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));
@ -151,7 +158,6 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
searchListViewAdapter.searchDialogs(null);
searching = false;
searchWas = false;
ViewGroup group = (ViewGroup) listView.getParent();
listView.setAdapter(listViewAdapter);
listViewAdapter.notifyDataSetChanged();
if (android.os.Build.VERSION.SDK_INT >= 11) {
@ -211,7 +217,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
emptyTextView = new TextView(getParentActivity());
emptyTextView.setTextColor(0xff808080);
emptyTextView.setTextSize(20);
emptyTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
emptyTextView.setGravity(Gravity.CENTER);
emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts));
emptyTextLayout.addView(emptyTextView);
@ -229,7 +235,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
layoutParams1.weight = 0.5f;
frameLayout.setLayoutParams(layoutParams1);
listView = new SectionsListView(getParentActivity());
listView = new LetterSectionsListView(getParentActivity());
listView.setEmptyView(emptyTextLayout);
listView.setVerticalScrollBarEnabled(false);
listView.setDivider(null);
@ -289,24 +295,24 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, ContactsController.getInstance().getInviteText());
getParentActivity().startActivity(Intent.createChooser(intent, ""));
getParentActivity().startActivityForResult(Intent.createChooser(intent, LocaleController.getString("InviteFriends", R.string.InviteFriends)), 500);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
} else {
if (row == 0) {
presentFragment(new GroupCreateActivity(), true);
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), true);
presentFragment(new ContactsActivity(args), false);
} else if (row == 2) {
Bundle args = new Bundle();
args.putBoolean("broadcast", true);
presentFragment(new GroupCreateActivity(args), true);
presentFragment(new GroupCreateActivity(args), false);
}
}
} else {
@ -348,7 +354,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", arg1, null));
intent.putExtra("sms_body", LocaleController.getString("InviteText", R.string.InviteText));
getParentActivity().startActivity(intent);
getParentActivity().startActivityForResult(intent, 500);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
@ -462,8 +468,13 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
TLRPC.EncryptedChat encryptedChat = (TLRPC.EncryptedChat)args[0];
Bundle args2 = new Bundle();
args2.putInt("enc_id", encryptedChat.id);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats);
presentFragment(new ChatActivity(args2), true);
}
} else if (id == NotificationCenter.closeChats) {
if (!creatingChat) {
removeSelfFromStack();
}
}
}

View File

@ -32,7 +32,7 @@ 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.Components.SectionsListView;
import org.telegram.ui.Components.LetterSectionsListView;
public class CountrySelectActivity extends BaseFragment {
@ -40,7 +40,7 @@ public class CountrySelectActivity extends BaseFragment {
public abstract void didSelectCountry(String name);
}
private SectionsListView listView;
private LetterSectionsListView listView;
private TextView emptyTextView;
private CountryAdapter listViewAdapter;
private CountrySearchAdapter searchListViewAdapter;
@ -61,7 +61,7 @@ public class CountrySelectActivity extends BaseFragment {
}
@Override
public View createView(LayoutInflater inflater, final ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);
@ -88,7 +88,6 @@ public class CountrySelectActivity extends BaseFragment {
searchListViewAdapter.search(null);
searching = false;
searchWas = false;
ViewGroup group = (ViewGroup) listView.getParent();
listView.setAdapter(listViewAdapter);
if (android.os.Build.VERSION.SDK_INT >= 11) {
listView.setFastScrollAlwaysVisible(true);
@ -165,7 +164,7 @@ public class CountrySelectActivity extends BaseFragment {
layoutParams1.weight = 0.5f;
frameLayout.setLayoutParams(layoutParams1);
listView = new SectionsListView(getParentActivity());
listView = new LetterSectionsListView(getParentActivity());
listView.setEmptyView(emptyTextLayout);
listView.setVerticalScrollBarEnabled(false);
listView.setDivider(null);

View File

@ -65,7 +65,7 @@ public class DocumentSelectActivity extends BaseFragment {
private ArrayList<ListItem> items = new ArrayList<>();
private boolean receiverRegistered = false;
private ArrayList<HistoryEntry> history = new ArrayList<>();
private long sizeLimit = 1024 * 1024 * 1024;
private long sizeLimit = 1024 * 1024 * 1536;
private DocumentSelectActivityDelegate delegate;
private HashMap<String, ListItem> selectedFiles = new HashMap<>();
private ArrayList<View> actionModeViews = new ArrayList<>();
@ -125,7 +125,7 @@ public class DocumentSelectActivity extends BaseFragment {
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (!receiverRegistered) {
receiverRegistered = true;
IntentFilter filter = new IntentFilter();
@ -194,7 +194,7 @@ public class DocumentSelectActivity extends BaseFragment {
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, container, false);
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() {

View File

@ -54,7 +54,7 @@ import org.telegram.ui.ActionBar.ActionBar;
import org.telegram.ui.ActionBar.ActionBarMenu;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.Cells.UserCell;
import org.telegram.ui.Components.SectionsListView;
import org.telegram.ui.Components.LetterSectionsListView;
import java.util.ArrayList;
import java.util.HashMap;
@ -93,7 +93,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
private ContactsAdapter listViewAdapter;
private TextView emptyTextView;
private EditText userSelectEditText;
private SectionsListView listView;
private LetterSectionsListView listView;
private ContactsSearchAdapter searchListViewAdapter;
private GroupCreateActivityDelegate delegate;
@ -141,7 +141,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
searching = false;
searchWas = false;
@ -307,7 +307,6 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
searchListViewAdapter.searchDialogs(null);
searching = false;
searchWas = false;
ViewGroup group = (ViewGroup) listView.getParent();
listView.setAdapter(listViewAdapter);
listViewAdapter.notifyDataSetChanged();
if (android.os.Build.VERSION.SDK_INT >= 11) {
@ -357,7 +356,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
layoutParams.weight = 0.5f;
frameLayout2.setLayoutParams(layoutParams);
listView = new SectionsListView(getParentActivity());
listView = new LetterSectionsListView(getParentActivity());
listView.setEmptyView(emptyTextLayout);
listView.setVerticalScrollBarEnabled(false);
listView.setDivider(null);
@ -434,7 +433,6 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
searchListViewAdapter.searchDialogs(null);
searching = false;
searchWas = false;
ViewGroup group = (ViewGroup) listView.getParent();
listView.setAdapter(listViewAdapter);
listViewAdapter.notifyDataSetChanged();
if (android.os.Build.VERSION.SDK_INT >= 11) {

View File

@ -85,7 +85,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
avatarUpdater.parentFragment = this;
avatarUpdater.delegate = this;
selectedContacts = getArguments().getIntegerArrayList("result");
final ArrayList<Integer> usersToLoad = new ArrayList<Integer>();
final ArrayList<Integer> usersToLoad = new ArrayList<>();
for (Integer uid : selectedContacts) {
if (MessagesController.getInstance().getUser(uid) == null) {
usersToLoad.add(uid);
@ -93,7 +93,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
}
if (!usersToLoad.isEmpty()) {
final Semaphore semaphore = new Semaphore(0);
final ArrayList<TLRPC.User> users = new ArrayList<TLRPC.User>();
final ArrayList<TLRPC.User> users = new ArrayList<>();
MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
@Override
public void run() {
@ -138,7 +138,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);
@ -402,6 +402,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
FileLog.e("tmessages", e);
}
}
NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats);
Bundle args2 = new Bundle();
args2.putInt("chat_id", (Integer)args[0]);
presentFragment(new ChatActivity(args2), true);

View File

@ -45,7 +45,7 @@ public class IdenticonActivity extends BaseFragment {
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);
@ -60,7 +60,7 @@ public class IdenticonActivity extends BaseFragment {
}
});
fragmentView = inflater.inflate(R.layout.identicon_layout, container, false);
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);

View File

@ -52,7 +52,7 @@ public class LanguageSelectActivity extends BaseFragment {
public ArrayList<LocaleController.LocaleInfo> searchResult;
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
searching = false;
searchWas = false;
@ -285,7 +285,7 @@ public class LanguageSelectActivity extends BaseFragment {
return;
}
long time = System.currentTimeMillis();
ArrayList<LocaleController.LocaleInfo> resultArray = new ArrayList<LocaleController.LocaleInfo>();
ArrayList<LocaleController.LocaleInfo> resultArray = new ArrayList<>();
for (LocaleController.LocaleInfo c : LocaleController.getInstance().sortedLanguages) {
if (c.name.toLowerCase().startsWith(query) || c.nameEnglish.toLowerCase().startsWith(query)) {

View File

@ -99,7 +99,7 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);

View File

@ -75,7 +75,7 @@ public class LastSeenUsersActivity extends BaseFragment implements NotificationC
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);

View File

@ -91,7 +91,7 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);
@ -139,9 +139,9 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
item.addSubItem(map_list_menu_hybrid, LocaleController.getString("Hybrid", R.string.Hybrid), 0);
if (messageObject != null) {
fragmentView = inflater.inflate(R.layout.location_view_layout, container, false);
fragmentView = inflater.inflate(R.layout.location_view_layout, null, false);
} else {
fragmentView = inflater.inflate(R.layout.location_attach_layout, container, false);
fragmentView = inflater.inflate(R.layout.location_attach_layout, null, false);
}
avatarImageView = (BackupImageView)fragmentView.findViewById(R.id.location_avatar_view);

View File

@ -103,7 +103,7 @@ public class LoginActivity extends BaseFragment {
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setTitle(LocaleController.getString("AppName", R.string.AppName));
@ -829,9 +829,6 @@ public class LoginActivity extends BaseFragment {
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);
if (res.phone_registered) {
params.putString("registered", "true");
}
setPage(1, true, params, false);
} else {
if (error.text != null) {
@ -898,7 +895,6 @@ public class LoginActivity extends BaseFragment {
private String phoneHash;
private String requestPhone;
private String registered;
private EditText codeField;
private TextView confirmTextView;
private TextView timeText;
@ -1067,7 +1063,6 @@ public class LoginActivity extends BaseFragment {
String phone = params.getString("phone");
requestPhone = params.getString("phoneFormated");
phoneHash = params.getString("phoneHash");
registered = params.getString("registered");
time = params.getInt("calltime");
if (phone == null) {
@ -1241,7 +1236,7 @@ public class LoginActivity extends BaseFragment {
} else {
lastError = error.text;
if (error.text.contains("PHONE_NUMBER_UNOCCUPIED") && registered == null) {
if (error.text.contains("PHONE_NUMBER_UNOCCUPIED")) {
Bundle params = new Bundle();
params.putString("phoneFormated", requestPhone);
params.putString("phoneHash", phoneHash);

File diff suppressed because it is too large Load Diff

View File

@ -26,7 +26,6 @@ import android.view.ViewTreeObserver;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
@ -67,6 +66,7 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
private View searchEmptyView;
private View progressView;
private View emptyView;
private ActionBarMenuItem passcodeItem;
private ImageView floatingButton;
private int prevPosition;
private int prevTop;
@ -88,6 +88,8 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
private long openedDialogId = 0;
private static final int passcode_menu_item = 1;
public static interface MessagesActivityDelegate {
public abstract void didSelectDialog(MessagesActivity fragment, long dialog_id, boolean param);
}
@ -107,6 +109,10 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
NotificationCenter.getInstance().addObserver(this, NotificationCenter.appDidLogout);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.openedChatChanged);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.notificationsSettingsUpdated);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.messageReceivedByAck);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.messageReceivedByServer);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.messageSendError);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.didSetPasscode);
if (getArguments() != null) {
onlySelect = arguments.getBoolean("onlySelect", false);
@ -133,25 +139,37 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.appDidLogout);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.openedChatChanged);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.notificationsSettingsUpdated);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.messageReceivedByAck);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.messageReceivedByServer);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.messageSendError);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didSetPasscode);
delegate = null;
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
searching = false;
searchWas = false;
ActionBarMenu menu = actionBar.createMenu();
if (!onlySelect) {
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) {
messagesListView.setEmptyView(searchEmptyView);
emptyView.setVisibility(View.GONE);
progressView.setVisibility(View.GONE);
emptyView.setVisibility(View.INVISIBLE);
progressView.setVisibility(View.INVISIBLE);
if (!onlySelect) {
floatingButton.setVisibility(View.GONE);
}
}
updatePasscodeButton();
}
@Override
@ -160,14 +178,14 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
searchWas = false;
if (messagesListView != null) {
if (MessagesController.getInstance().loadingDialogs && MessagesController.getInstance().dialogs.isEmpty()) {
searchEmptyView.setVisibility(View.GONE);
emptyView.setVisibility(View.GONE);
searchEmptyView.setVisibility(View.INVISIBLE);
emptyView.setVisibility(View.INVISIBLE);
progressView.setVisibility(View.VISIBLE);
messagesListView.setEmptyView(progressView);
} else {
messagesListView.setEmptyView(emptyView);
searchEmptyView.setVisibility(View.GONE);
progressView.setVisibility(View.GONE);
searchEmptyView.setVisibility(View.INVISIBLE);
progressView.setVisibility(View.INVISIBLE);
}
if (!onlySelect) {
floatingButton.setVisibility(View.VISIBLE);
@ -183,6 +201,7 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
if (dialogsSearchAdapter != null) {
dialogsSearchAdapter.searchDialogs(null, false);
}
updatePasscodeButton();
}
@Override
@ -196,8 +215,8 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
}
if (searchEmptyView != null && messagesListView.getEmptyView() == emptyView) {
messagesListView.setEmptyView(searchEmptyView);
emptyView.setVisibility(View.GONE);
progressView.setVisibility(View.GONE);
emptyView.setVisibility(View.INVISIBLE);
progressView.setVisibility(View.INVISIBLE);
}
}
if (dialogsSearchAdapter != null) {
@ -224,14 +243,15 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
} else if (parentLayout != null) {
parentLayout.getDrawerLayoutContainer().openDrawer(false);
}
} else if (id == passcode_menu_item) {
UserConfig.appLocked = !UserConfig.appLocked;
UserConfig.saveConfig(false);
updatePasscodeButton();
}
}
});
searching = false;
searchWas = false;
fragmentView = inflater.inflate(R.layout.messages_list, container, false);
fragmentView = inflater.inflate(R.layout.messages_list, null, false);
dialogsAdapter = new DialogsAdapter(getParentActivity(), serverOnly);
if (AndroidUtilities.isTablet() && openedDialogId != 0) {
@ -242,8 +262,8 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
@Override
public void searchStateChanged(boolean search) {
if (searching && searchWas && messagesListView != null) {
progressView.setVisibility(search ? View.VISIBLE : View.GONE);
searchEmptyView.setVisibility(search ? View.GONE : View.VISIBLE);
progressView.setVisibility(search ? View.VISIBLE : View.INVISIBLE);
searchEmptyView.setVisibility(search ? View.INVISIBLE : View.VISIBLE);
messagesListView.setEmptyView(search ? progressView : searchEmptyView);
}
}
@ -309,14 +329,14 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
});
if (MessagesController.getInstance().loadingDialogs && MessagesController.getInstance().dialogs.isEmpty()) {
searchEmptyView.setVisibility(View.GONE);
emptyView.setVisibility(View.GONE);
searchEmptyView.setVisibility(View.INVISIBLE);
emptyView.setVisibility(View.INVISIBLE);
progressView.setVisibility(View.VISIBLE);
messagesListView.setEmptyView(progressView);
} else {
messagesListView.setEmptyView(emptyView);
searchEmptyView.setVisibility(View.GONE);
progressView.setVisibility(View.GONE);
searchEmptyView.setVisibility(View.INVISIBLE);
progressView.setVisibility(View.INVISIBLE);
}
messagesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@ -559,29 +579,30 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
public void didReceivedNotification(int id, Object... args) {
if (id == NotificationCenter.dialogsNeedReload) {
if (dialogsAdapter != null) {
dialogsAdapter.notifyDataSetChanged();
if (dialogsAdapter.isDataSetChanged()) {
dialogsAdapter.notifyDataSetChanged();
} else {
updateVisibleRows(MessagesController.UPDATE_MASK_NEW_MESSAGE);
}
}
if (dialogsSearchAdapter != null) {
dialogsSearchAdapter.notifyDataSetChanged();
}
if (messagesListView != null) {
try {
if (messagesListView.getAdapter() != null && messagesListView.getAdapter() instanceof BaseAdapter) {
((BaseAdapter) messagesListView.getAdapter()).notifyDataSetChanged();
}
if (MessagesController.getInstance().loadingDialogs && MessagesController.getInstance().dialogs.isEmpty()) {
searchEmptyView.setVisibility(View.GONE);
emptyView.setVisibility(View.GONE);
searchEmptyView.setVisibility(View.INVISIBLE);
emptyView.setVisibility(View.INVISIBLE);
messagesListView.setEmptyView(progressView);
} else {
if (searching && searchWas) {
messagesListView.setEmptyView(searchEmptyView);
emptyView.setVisibility(View.GONE);
emptyView.setVisibility(View.INVISIBLE);
} else {
messagesListView.setEmptyView(emptyView);
searchEmptyView.setVisibility(View.GONE);
searchEmptyView.setVisibility(View.INVISIBLE);
}
progressView.setVisibility(View.GONE);
progressView.setVisibility(View.INVISIBLE);
}
} catch (Exception e) {
FileLog.e("tmessages", e); //TODO fix it in other way?
@ -616,9 +637,27 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
updateVisibleRows(MessagesController.UPDATE_MASK_SELECT_DIALOG);
}
} else if (id == NotificationCenter.notificationsSettingsUpdated) {
if (messagesListView != null) {
updateVisibleRows(0);
updateVisibleRows(0);
} else if (id == NotificationCenter.messageReceivedByAck || id == NotificationCenter.messageReceivedByServer || id == NotificationCenter.messageSendError) {
updateVisibleRows(MessagesController.UPDATE_MASK_SEND_STATE);
} else if (id == NotificationCenter.didSetPasscode) {
updatePasscodeButton();
}
}
private void updatePasscodeButton() {
if (passcodeItem == null) {
return;
}
if (UserConfig.passcodeHash.length() != 0 && !searching) {
passcodeItem.setVisibility(View.VISIBLE);
if (UserConfig.appLocked) {
passcodeItem.setIcon(R.drawable.lock_close);
} else {
passcodeItem.setIcon(R.drawable.lock_open);
}
} else {
passcodeItem.setVisibility(View.GONE);
}
}
@ -642,13 +681,14 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
View child = messagesListView.getChildAt(a);
if (child instanceof DialogCell) {
DialogCell cell = (DialogCell) child;
if ((mask & MessagesController.UPDATE_MASK_SELECT_DIALOG) != 0) {
if ((mask & MessagesController.UPDATE_MASK_NEW_MESSAGE) != 0) {
cell.checkCurrentDialogIndex();
if (!serverOnly && AndroidUtilities.isTablet()) {
if (cell.getDialogId() == openedDialogId) {
child.setBackgroundColor(0x0f000000);
} else {
child.setBackgroundColor(0);
}
child.setBackgroundColor(cell.getDialogId() == openedDialogId ? 0x0f000000 : 0);
}
} else if ((mask & MessagesController.UPDATE_MASK_SELECT_DIALOG) != 0) {
if (!serverOnly && AndroidUtilities.isTablet()) {
child.setBackgroundColor(cell.getDialogId() == openedDialogId ? 0x0f000000 : 0);
}
} else {
cell.update(mask);

View File

@ -154,7 +154,7 @@ public class NotificationsSettingsActivity extends BaseFragment implements Notif
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);

View File

@ -0,0 +1,710 @@
/*
* 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.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Vibrator;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
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.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
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.TextView;
import android.widget.Toast;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.LocaleController;
import org.telegram.android.NotificationCenter;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.R;
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.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;
import org.telegram.ui.Components.NumberPicker;
public class PasscodeActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate {
private ListAdapter listAdapter;
private ListView listView;
private TextView titleTextView;
private EditText passwordEditText;
private TextView dropDown;
private ActionBarMenuItem dropDownContainer;
private int type;
private int currentPasswordType = 0;
private String firstPassword;
private int passcodeRow;
private int changePasscodeRow;
private int passcodeDetailRow;
private int autoLockRow;
private int autoLockDetailRow;
private int rowCount;
private final static int done_button = 1;
private final static int pin_item = 2;
private final static int password_item = 3;
public PasscodeActivity(int type) {
super();
this.type = type;
}
@Override
public boolean onFragmentCreate() {
super.onFragmentCreate();
updateRows();
if (type == 0) {
NotificationCenter.getInstance().addObserver(this, NotificationCenter.didSetPasscode);
}
return true;
}
@Override
public void onFragmentDestroy() {
super.onFragmentDestroy();
if (type == 0) {
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didSetPasscode);
}
}
@Override
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
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();
}
}
});
fragmentView = new FrameLayout(getParentActivity());
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(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;
}
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();
}
}
}
}
});
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();
} 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);
}
}
});
}
} 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();
}
if (type != 0) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
if (passwordEditText != null) {
passwordEditText.requestFocus();
AndroidUtilities.showKeyboard(passwordEditText);
}
}
}, 200);
}
fixLayoutInternal();
}
@Override
public void didReceivedNotification(int id, Object... args) {
if (id == NotificationCenter.didSetPasscode) {
if (type == 0) {
updateRows();
if (listAdapter != null) {
listAdapter.notifyDataSetChanged();
}
}
}
}
private void updateRows() {
rowCount = 0;
passcodeRow = rowCount++;
changePasscodeRow = rowCount++;
passcodeDetailRow = rowCount++;
if (UserConfig.passcodeHash.length() > 0) {
autoLockRow = rowCount++;
autoLockDetailRow = rowCount++;
} else {
autoLockRow = -1;
autoLockDetailRow = -1;
}
}
@Override
public void onConfigurationChanged(android.content.res.Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (listView != null) {
ViewTreeObserver obs = listView.getViewTreeObserver();
obs.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
listView.getViewTreeObserver().removeOnPreDrawListener(this);
fixLayoutInternal();
return false;
}
});
}
}
@Override
public void onOpenAnimationEnd() {
super.onOpenAnimationEnd();
if (type != 0) {
AndroidUtilities.showKeyboard(passwordEditText);
}
}
private void updateDropDownTextView() {
if (dropDown != null) {
if (currentPasswordType == 0) {
dropDown.setText(LocaleController.getString("PasscodePIN", R.string.PasscodePIN));
} else if (currentPasswordType == 1) {
dropDown.setText(LocaleController.getString("PasscodePassword", R.string.PasscodePassword));
}
}
if (type == 1 && currentPasswordType == 0 || type == 2 && UserConfig.passcodeType == 0) {
InputFilter[] filterArray = new InputFilter[1];
filterArray[0] = new InputFilter.LengthFilter(4);
passwordEditText.setFilters(filterArray);
passwordEditText.setInputType(InputType.TYPE_CLASS_PHONE);
passwordEditText.setKeyListener(DigitsKeyListener.getInstance("123456789"));
} else if (type == 1 && currentPasswordType == 1 || type == 2 && UserConfig.passcodeType == 1) {
passwordEditText.setFilters(new InputFilter[0]);
passwordEditText.setKeyListener(null);
passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
}
passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
private void processNext() {
if (passwordEditText.getText().length() == 0 || currentPasswordType == 0 && passwordEditText.getText().length() != 4) {
onPasscodeError();
return;
}
if (currentPasswordType == 0) {
actionBar.setTitle(LocaleController.getString("PasscodePIN", R.string.PasscodePIN));
} else {
actionBar.setTitle(LocaleController.getString("PasscodePassword", R.string.PasscodePassword));
}
dropDownContainer.setVisibility(View.GONE);
titleTextView.setText(LocaleController.getString("ReEnterYourPasscode", R.string.ReEnterYourPasscode));
firstPassword = passwordEditText.getText().toString();
passwordEditText.setText("");
passwordEditText.setImeOptions(EditorInfo.IME_ACTION_DONE);
}
private void processDone() {
if (passwordEditText.getText().length() == 0) {
onPasscodeError();
return;
}
if (type == 1) {
if (!firstPassword.equals(passwordEditText.getText().toString())) {
try {
Toast.makeText(getParentActivity(), LocaleController.getString("PasscodeDoNotMatch", R.string.PasscodeDoNotMatch), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
shakeTextView(2, 0);
passwordEditText.setText("");
return;
}
UserConfig.passcodeHash = Utilities.MD5(firstPassword);
UserConfig.passcodeType = currentPasswordType;
UserConfig.saveConfig(false);
//TODO show alert
finishFragment();
NotificationCenter.getInstance().postNotificationName(NotificationCenter.didSetPasscode);
passwordEditText.clearFocus();
AndroidUtilities.hideKeyboard(passwordEditText);
} else if (type == 2) {
if (!Utilities.MD5(passwordEditText.getText().toString()).equals(UserConfig.passcodeHash)) {
passwordEditText.setText("");
onPasscodeError();
return;
}
passwordEditText.clearFocus();
AndroidUtilities.hideKeyboard(passwordEditText);
presentFragment(new PasscodeActivity(0), true);
}
}
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;
}
Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE);
if (v != null) {
v.vibrate(200);
}
shakeTextView(2, 0);
}
private void fixLayoutInternal() {
if (dropDownContainer != null) {
if (!AndroidUtilities.isTablet()) {
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) dropDownContainer.getLayoutParams();
layoutParams.topMargin = (Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0);
dropDownContainer.setLayoutParams(layoutParams);
}
if (!AndroidUtilities.isTablet() && ApplicationLoader.applicationContext.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
dropDown.setTextSize(18);
} else {
dropDown.setTextSize(20);
}
}
}
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 == passcodeRow || i == autoLockRow || UserConfig.passcodeHash.length() != 0 && i == changePasscodeRow;
}
@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 TextCheckCell(mContext);
view.setBackgroundColor(0xffffffff);
}
TextCheckCell textCell = (TextCheckCell) view;
if (i == passcodeRow) {
textCell.setTextAndCheck(LocaleController.getString("Passcode", R.string.Passcode), UserConfig.passcodeHash.length() > 0, true);
}
} else if (viewType == 1) {
if (view == null) {
view = new TextSettingsCell(mContext);
view.setBackgroundColor(0xffffffff);
}
TextSettingsCell textCell = (TextSettingsCell) view;
if (i == changePasscodeRow) {
textCell.setText(LocaleController.getString("ChangePasscode", R.string.ChangePasscode), false);
textCell.setTextColor(UserConfig.passcodeHash.length() == 0 ? 0xffc6c6c6 : 0xff000000);
} else if (i == autoLockRow) {
String val;
if (UserConfig.autoLockIn == 0) {
val = LocaleController.formatString("AutoLockDisabled", R.string.AutoLockDisabled);
} else if (UserConfig.autoLockIn < 60 * 60) {
val = LocaleController.formatString("AutoLockInTime", R.string.AutoLockInTime, LocaleController.formatPluralString("Minutes", UserConfig.autoLockIn / 60));
} else if (UserConfig.autoLockIn < 60 * 60 * 24) {
val = LocaleController.formatString("AutoLockInTime", R.string.AutoLockInTime, LocaleController.formatPluralString("Hours", (int) Math.ceil(UserConfig.autoLockIn / 60.0f / 60)));
} else {
val = LocaleController.formatString("AutoLockInTime", R.string.AutoLockInTime, LocaleController.formatPluralString("Days", (int) Math.ceil(UserConfig.autoLockIn / 60.0f / 60 / 24)));
}
textCell.setTextAndValue(LocaleController.getString("AutoLock", R.string.AutoLock), val, true);
textCell.setTextColor(0xff000000);
}
} else if (viewType == 2) {
if (view == null) {
view = new TextInfoPrivacyCell(mContext);
}
if (i == passcodeDetailRow) {
((TextInfoPrivacyCell) view).setText(LocaleController.getString("ChangePasscodeInfo", R.string.ChangePasscodeInfo));
if (autoLockDetailRow != -1) {
view.setBackgroundResource(R.drawable.greydivider);
} else {
view.setBackgroundResource(R.drawable.greydivider_bottom);
}
} else if (i == autoLockDetailRow) {
((TextInfoPrivacyCell) view).setText(LocaleController.getString("AutoLockInfo", R.string.AutoLockInfo));
view.setBackgroundResource(R.drawable.greydivider_bottom);
}
}
return view;
}
@Override
public int getItemViewType(int i) {
if (i == passcodeRow) {
return 0;
} else if (i == changePasscodeRow || i == autoLockRow) {
return 1;
} else if (i == passcodeDetailRow || i == autoLockDetailRow) {
return 2;
}
return 0;
}
@Override
public int getViewTypeCount() {
return 3;
}
@Override
public boolean isEmpty() {
return false;
}
}
}

View File

@ -67,9 +67,15 @@ public class PhotoAlbumPickerActivity extends BaseFragment implements Notificati
private TextView emptyView;
private PhotoPickerBottomLayout photoPickerBottomLayout;
private boolean sendPressed = false;
private boolean singlePhoto = false;
private PhotoAlbumPickerActivityDelegate delegate;
public PhotoAlbumPickerActivity(boolean onlyOnePhoto) {
super();
singlePhoto = onlyOnePhoto;
}
@Override
public boolean onFragmentCreate() {
loading = true;
@ -90,7 +96,7 @@ public class PhotoAlbumPickerActivity extends BaseFragment implements Notificati
@SuppressWarnings("unchecked")
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackgroundColor(0xff333333);
actionBar.setItemsBackground(R.drawable.bar_selector_picker);
@ -292,7 +298,11 @@ public class PhotoAlbumPickerActivity extends BaseFragment implements Notificati
boolean webChange = false;
for (HashMap.Entry<String, MediaController.SearchImage> entry : selectedWebPhotos.entrySet()) {
MediaController.SearchImage searchImage = entry.getValue();
webPhotos.add(searchImage);
if (searchImage.imagePath != null) {
photos.add(searchImage.imagePath);
} else {
webPhotos.add(searchImage);
}
searchImage.date = (int) (System.currentTimeMillis() / 1000);
if (searchImage.type == 0) {
@ -364,7 +374,7 @@ public class PhotoAlbumPickerActivity extends BaseFragment implements Notificati
recentImages = recentGifImages;
}
}
PhotoPickerActivity fragment = new PhotoPickerActivity(type, albumEntry, selectedPhotos, selectedWebPhotos, recentImages);
PhotoPickerActivity fragment = new PhotoPickerActivity(type, albumEntry, selectedPhotos, selectedWebPhotos, recentImages, singlePhoto);
fragment.setDelegate(new PhotoPickerActivity.PhotoPickerActivityDelegate() {
@Override
public void selectedPhotosChanged() {
@ -403,6 +413,9 @@ public class PhotoAlbumPickerActivity extends BaseFragment implements Notificati
@Override
public int getCount() {
if (singlePhoto) {
return albumsSorted != null ? (int) Math.ceil(albumsSorted.size() / (float) columnsCount) : 0;
}
return 1 + (albumsSorted != null ? (int) Math.ceil(albumsSorted.size() / (float) columnsCount) : 0);
}
@ -440,7 +453,12 @@ public class PhotoAlbumPickerActivity extends BaseFragment implements Notificati
}
photoPickerAlbumsCell.setAlbumsCount(columnsCount);
for (int a = 0; a < columnsCount; a++) {
int index = (i - 1) * columnsCount + a;
int index;
if (singlePhoto) {
index = i * columnsCount + a;
} else {
index = (i - 1) * columnsCount + a;
}
if (index < albumsSorted.size()) {
MediaController.AlbumEntry albumEntry = albumsSorted.get(index);
photoPickerAlbumsCell.setAlbum(a, albumEntry);
@ -464,6 +482,9 @@ public class PhotoAlbumPickerActivity extends BaseFragment implements Notificati
@Override
public int getItemViewType(int i) {
if (singlePhoto) {
return 0;
}
if (i == 0) {
return 1;
}
@ -472,6 +493,9 @@ public class PhotoAlbumPickerActivity extends BaseFragment implements Notificati
@Override
public int getViewTypeCount() {
if (singlePhoto) {
return 1;
}
return 2;
}

View File

@ -303,6 +303,12 @@ public class PhotoCropActivity extends BaseFragment {
int y = (int)(percY * imageToCrop.getHeight());
int sizeX = (int)(percSizeX * imageToCrop.getWidth());
int sizeY = (int)(percSizeY * imageToCrop.getWidth());
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
if (x + sizeX > imageToCrop.getWidth()) {
sizeX = imageToCrop.getWidth() - x;
}
@ -426,7 +432,7 @@ public class PhotoCropActivity extends BaseFragment {
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackgroundColor(0xff333333);
actionBar.setItemsBackground(R.drawable.bar_selector_picker);

View File

@ -12,7 +12,6 @@ import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.util.Base64;
import android.view.Gravity;
import android.view.LayoutInflater;
@ -33,7 +32,6 @@ import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONObject;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.ImageLoader;
import org.telegram.android.LocaleController;
import org.telegram.android.MediaController;
import org.telegram.android.MessagesStorage;
@ -47,7 +45,6 @@ import org.telegram.android.volley.toolbox.JsonObjectRequest;
import org.telegram.android.volley.toolbox.Volley;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.BuildVars;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.R;
import org.telegram.messenger.TLRPC;
@ -68,7 +65,7 @@ import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
public class PhotoPickerActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, PhotoViewer.PhotoViewerProvider, PhotoCropActivity.PhotoEditActivityDelegate {
public class PhotoPickerActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, PhotoViewer.PhotoViewerProvider {
public static interface PhotoPickerActivityDelegate {
public abstract void selectedPhotosChanged();
@ -102,16 +99,18 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen
private ActionBarMenuItem searchItem;
private int itemWidth = 100;
private boolean sendPressed;
private boolean singlePhoto;
private PhotoPickerActivityDelegate delegate;
public PhotoPickerActivity(int type, MediaController.AlbumEntry selectedAlbum, HashMap<Integer, MediaController.PhotoEntry> selectedPhotos, HashMap<String, MediaController.SearchImage> selectedWebPhotos, ArrayList<MediaController.SearchImage> recentImages) {
public PhotoPickerActivity(int type, MediaController.AlbumEntry selectedAlbum, HashMap<Integer, MediaController.PhotoEntry> selectedPhotos, HashMap<String, MediaController.SearchImage> selectedWebPhotos, ArrayList<MediaController.SearchImage> recentImages, boolean onlyOnePhoto) {
super();
this.selectedAlbum = selectedAlbum;
this.selectedPhotos = selectedPhotos;
this.selectedWebPhotos = selectedWebPhotos;
this.type = type;
this.recentImages = recentImages;
this.singlePhoto = onlyOnePhoto;
}
@Override
@ -141,7 +140,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen
@SuppressWarnings("unchecked")
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackgroundColor(0xff333333);
actionBar.setItemsBackground(R.drawable.bar_selector_picker);
@ -257,7 +256,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams();
layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams.bottomMargin = AndroidUtilities.dp(48);
layoutParams.bottomMargin = singlePhoto ? 0 : AndroidUtilities.dp(48);
listView.setLayoutParams(layoutParams);
listView.setAdapter(listAdapter = new ListAdapter(getParentActivity()));
AndroidUtilities.setListViewEdgeEffectColor(listView, 0xff333333);
@ -278,7 +277,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen
return;
}
PhotoViewer.getInstance().setParentActivity(getParentActivity());
PhotoViewer.getInstance().openPhotoForSelect(arrayList, i, PhotoPickerActivity.this);
PhotoViewer.getInstance().openPhotoForSelect(arrayList, i, singlePhoto ? 1 : 0, PhotoPickerActivity.this);
}
});
@ -300,7 +299,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen
layoutParams = (FrameLayout.LayoutParams) emptyView.getLayoutParams();
layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams.bottomMargin = AndroidUtilities.dp(48);
layoutParams.bottomMargin = singlePhoto ? 0 : AndroidUtilities.dp(48);
emptyView.setLayoutParams(layoutParams);
emptyView.setOnTouchListener(new View.OnTouchListener() {
@Override
@ -336,7 +335,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen
layoutParams = (FrameLayout.LayoutParams) progressView.getLayoutParams();
layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams.bottomMargin = AndroidUtilities.dp(48);
layoutParams.bottomMargin = singlePhoto ? 0 : AndroidUtilities.dp(48);
progressView.setLayoutParams(layoutParams);
ProgressBar progressBar = new ProgressBar(getParentActivity());
@ -370,6 +369,9 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen
sendSelectedPhotos();
}
});
if (singlePhoto) {
photoPickerBottomLayout.setVisibility(View.GONE);
}
listView.setEmptyView(emptyView);
photoPickerBottomLayout.updateSelectedCount(selectedPhotos.size() + selectedWebPhotos.size(), true);
@ -464,6 +466,40 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen
return null;
}
@Override
public void updatePhotoAtIndex(int index) {
PhotoPickerPhotoCell cell = getCellForIndex(index);
if (cell != null) {
if (selectedAlbum != null) {
cell.photoImage.setOrientation(0, true);
MediaController.PhotoEntry photoEntry = selectedAlbum.photos.get(index);
if (photoEntry.thumbPath != null) {
cell.photoImage.setImage(photoEntry.thumbPath, null, cell.getContext().getResources().getDrawable(R.drawable.nophotos));
} else if (photoEntry.path != null) {
cell.photoImage.setOrientation(photoEntry.orientation, true);
cell.photoImage.setImage("thumb://" + photoEntry.imageId + ":" + photoEntry.path, null, cell.getContext().getResources().getDrawable(R.drawable.nophotos));
} else {
cell.photoImage.setImageResource(R.drawable.nophotos);
}
} else {
ArrayList<MediaController.SearchImage> array = null;
if (searchResult.isEmpty() && lastSearchString == null) {
array = recentImages;
} else {
array = searchResult;
}
MediaController.SearchImage photoEntry = array.get(index);
if (photoEntry.thumbPath != null) {
cell.photoImage.setImage(photoEntry.thumbPath, null, cell.getContext().getResources().getDrawable(R.drawable.nophotos));
} else if (photoEntry.thumbUrl != null && photoEntry.thumbUrl.length() > 0) {
cell.photoImage.setImage(photoEntry.thumbUrl, null, cell.getContext().getResources().getDrawable(R.drawable.nophotos));
} else {
cell.photoImage.setImageResource(R.drawable.nophotos);
}
}
}
}
@Override
public Bitmap getThumbForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) {
PhotoPickerPhotoCell cell = getCellForIndex(index);
@ -618,20 +654,6 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen
}
}
@Override
public void didFinishEdit(Bitmap bitmap, Bundle args) {
TLRPC.PhotoSize size = ImageLoader.scaleAndSaveImage(bitmap, AndroidUtilities.getPhotoSize(), AndroidUtilities.getPhotoSize(), 80, false, 101, 101);
if (size != null) {
int id = args.getInt("id");
MediaController.PhotoEntry entry = selectedAlbum.photosByIds.get(id);
entry.imagePath = FileLoader.getPathToAttach(size, true).toString();
selectedPhotos.put(entry.imageId, entry);
listAdapter.notifyDataSetChanged();
photoPickerBottomLayout.updateSelectedCount(selectedPhotos.size() + selectedWebPhotos.size(), true);
delegate.selectedPhotosChanged();
}
}
private void updateSearchInterface() {
if (listAdapter != null) {
listAdapter.notifyDataSetChanged();
@ -654,7 +676,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen
}
try {
searching = true;
String url = String.format("https://api.giphy.com/v1/gifs/search?q=%s&offset=%d&limit=%d&api_key=141Wa2KDAfNfxu", URLEncoder.encode(query, "UTF-8"), offset, count);
String url = String.format(Locale.US, "https://api.giphy.com/v1/gifs/search?q=%s&offset=%d&limit=%d&api_key=141Wa2KDAfNfxu", URLEncoder.encode(query, "UTF-8"), offset, count);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
@ -933,15 +955,17 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen
cell.checkFrame.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int index = (Integer) ((View) v.getParent()).getTag();
if (selectedAlbum != null) {
MediaController.PhotoEntry photoEntry = selectedAlbum.photos.get((Integer) ((View) v.getParent()).getTag());
MediaController.PhotoEntry photoEntry = selectedAlbum.photos.get(index);
if (selectedPhotos.containsKey(photoEntry.imageId)) {
selectedPhotos.remove(photoEntry.imageId);
photoEntry.imagePath = null;
photoEntry.thumbPath = null;
updatePhotoAtIndex(index);
} else {
selectedPhotos.put(photoEntry.imageId, photoEntry);
}
((PhotoPickerPhotoCell) v.getParent()).editedImage.setVisibility(photoEntry.imagePath != null ? View.VISIBLE : View.GONE);
((PhotoPickerPhotoCell) v.getParent()).checkBox.setChecked(selectedPhotos.containsKey(photoEntry.imageId), true);
} else {
AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus());
@ -953,32 +977,38 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen
}
if (selectedWebPhotos.containsKey(photoEntry.id)) {
selectedWebPhotos.remove(photoEntry.id);
photoEntry.imagePath = null;
photoEntry.thumbPath = null;
updatePhotoAtIndex(index);
} else {
selectedWebPhotos.put(photoEntry.id, photoEntry);
}
((PhotoPickerPhotoCell) v.getParent()).editedImage.setVisibility(View.GONE);
((PhotoPickerPhotoCell) v.getParent()).checkBox.setChecked(selectedWebPhotos.containsKey(photoEntry.id), true);
}
photoPickerBottomLayout.updateSelectedCount(selectedPhotos.size() + selectedWebPhotos.size(), true);
delegate.selectedPhotosChanged();
}
});
cell.checkFrame.setVisibility(singlePhoto ? View.GONE : View.VISIBLE);
}
cell.itemWidth = itemWidth;
BackupImageView imageView = ((PhotoPickerPhotoCell) view).photoImage;
imageView.setTag(i);
view.setTag(i);
boolean showing = false;
imageView.setOrientation(0, true);
if (selectedAlbum != null) {
MediaController.PhotoEntry photoEntry = selectedAlbum.photos.get(i);
if (photoEntry.path != null) {
if (photoEntry.thumbPath != null) {
imageView.setImage(photoEntry.thumbPath, null, mContext.getResources().getDrawable(R.drawable.nophotos));
} else if (photoEntry.path != null) {
imageView.setOrientation(photoEntry.orientation, true);
imageView.setImage("thumb://" + photoEntry.imageId + ":" + photoEntry.path, null, mContext.getResources().getDrawable(R.drawable.nophotos));
} else {
imageView.setImageResource(R.drawable.nophotos);
}
cell.checkBox.setChecked(selectedPhotos.containsKey(photoEntry.imageId), false);
cell.editedImage.setVisibility(photoEntry.imagePath != null ? View.VISIBLE : View.GONE);
showing = PhotoViewer.getInstance().isShowingImage(photoEntry.path);
} else {
MediaController.SearchImage photoEntry = null;
@ -987,17 +1017,18 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen
} else {
photoEntry = searchResult.get(i);
}
if (photoEntry.thumbUrl != null && photoEntry.thumbUrl.length() > 0) {
if (photoEntry.thumbPath != null) {
imageView.setImage(photoEntry.thumbPath, null, mContext.getResources().getDrawable(R.drawable.nophotos));
} else if (photoEntry.thumbUrl != null && photoEntry.thumbUrl.length() > 0) {
imageView.setImage(photoEntry.thumbUrl, null, mContext.getResources().getDrawable(R.drawable.nophotos));
} else {
imageView.setImageResource(R.drawable.nophotos);
}
cell.checkBox.setChecked(selectedWebPhotos.containsKey(photoEntry.id), false);
cell.editedImage.setVisibility(View.GONE);
showing = PhotoViewer.getInstance().isShowingImage(photoEntry.thumbUrl);
}
imageView.imageReceiver.setVisible(!showing, false);
cell.checkBox.setVisibility(showing ? View.GONE : View.VISIBLE);
cell.checkBox.setVisibility(singlePhoto || showing ? View.GONE : View.VISIBLE);
} else if (viewType == 1) {
if (view == null) {
LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

File diff suppressed because it is too large Load Diff

View File

@ -53,6 +53,7 @@ import org.telegram.ui.Components.BackupImageView;
import org.telegram.ui.Components.ChatActivityEnterView;
import org.telegram.ui.Components.FrameLayoutFixed;
import org.telegram.ui.Components.PopupAudioView;
import org.telegram.ui.Components.SizeNotifierRelativeLayout;
import org.telegram.ui.Components.TypingDotsDrawable;
import java.io.File;
@ -159,7 +160,38 @@ public class PopupNotificationActivity extends Activity implements NotificationC
typingDotsDrawable = new TypingDotsDrawable();
chatActivityEnterView = new ChatActivityEnterView();
SizeNotifierRelativeLayout contentView = new SizeNotifierRelativeLayout(this);
setContentView(contentView);
contentView.setBackgroundColor(0x99000000);
RelativeLayout relativeLayout = new RelativeLayout(this);
contentView.addView(relativeLayout);
RelativeLayout.LayoutParams layoutParams3 = (RelativeLayout.LayoutParams) relativeLayout.getLayoutParams();
layoutParams3.width = RelativeLayout.LayoutParams.MATCH_PARENT;
layoutParams3.height = RelativeLayout.LayoutParams.MATCH_PARENT;
relativeLayout.setLayoutParams(layoutParams3);
RelativeLayout popupContainer = new RelativeLayout(this);
popupContainer.setBackgroundColor(0xffffffff);
relativeLayout.addView(popupContainer);
layoutParams3 = (RelativeLayout.LayoutParams) popupContainer.getLayoutParams();
layoutParams3.width = RelativeLayout.LayoutParams.MATCH_PARENT;
layoutParams3.height = AndroidUtilities.dp(240);
layoutParams3.leftMargin = AndroidUtilities.dp(12);
layoutParams3.rightMargin = AndroidUtilities.dp(12);
layoutParams3.addRule(RelativeLayout.CENTER_IN_PARENT);
popupContainer.setLayoutParams(layoutParams3);
if (chatActivityEnterView != null) {
chatActivityEnterView.onDestroy();
}
chatActivityEnterView = new ChatActivityEnterView(this, contentView, true);
popupContainer.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() {
@ -202,15 +234,13 @@ public class PopupNotificationActivity extends Activity implements NotificationC
}
});
setContentView(R.layout.popup_notification_layout);
RelativeLayout popupContainer = (RelativeLayout) findViewById(R.id.popup_container);
messageContainer = new FrameLayoutTouch(this);
popupContainer.addView(messageContainer, 0);
actionBar = new ActionBar(this);
actionBar.setOccupyStatusBar(false);
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setBackgroundResource(R.color.header);
actionBar.setBackgroundColor(0xff54759e);
actionBar.setItemsBackground(R.drawable.bar_selector);
popupContainer.addView(actionBar);
ViewGroup.LayoutParams layoutParams = actionBar.getLayoutParams();
@ -292,8 +322,6 @@ public class PopupNotificationActivity extends Activity implements NotificationC
}
});
chatActivityEnterView.setContainerView(this, findViewById(R.id.chat_layout));
PowerManager pm = (PowerManager) ApplicationLoader.applicationContext.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "screen");
wakeLock.setReferenceCounted(false);

View File

@ -53,6 +53,7 @@ public class PrivacySettingsActivity extends BaseFragment implements Notificatio
private int securitySectionRow;
private int terminateSessionsRow;
private int passwordRow;
private int passcodeRow;
private int terminateSessionsDetailRow;
private int deleteAccountSectionRow;
private int deleteAccountRow;
@ -71,6 +72,7 @@ public class PrivacySettingsActivity extends BaseFragment implements Notificatio
lastSeenRow = rowCount++;
lastSeenDetailRow = rowCount++;
securitySectionRow = rowCount++;
passcodeRow = rowCount++;
terminateSessionsRow = rowCount++;
terminateSessionsDetailRow = rowCount++;
deleteAccountSectionRow = rowCount++;
@ -90,7 +92,7 @@ public class PrivacySettingsActivity extends BaseFragment implements Notificatio
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);
@ -227,6 +229,12 @@ public class PrivacySettingsActivity extends BaseFragment implements Notificatio
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));
}
}
}
});
@ -319,7 +327,7 @@ public class PrivacySettingsActivity extends BaseFragment implements Notificatio
@Override
public boolean isEnabled(int i) {
return i == passwordRow || i == blockedRow || i == terminateSessionsRow || i == lastSeenRow && !ContactsController.getInstance().getLoadingLastSeenInfo() || i == deleteAccountRow && !ContactsController.getInstance().getLoadingDeleteInfo();
return i == passcodeRow || i == passwordRow || i == blockedRow || i == terminateSessionsRow || i == lastSeenRow && !ContactsController.getInstance().getLoadingLastSeenInfo() || i == deleteAccountRow && !ContactsController.getInstance().getLoadingDeleteInfo();
}
@Override
@ -357,6 +365,8 @@ public class PrivacySettingsActivity extends BaseFragment implements Notificatio
textCell.setText(LocaleController.getString("TerminateAllSessions", R.string.TerminateAllSessions), false);
} else if (i == passwordRow) {
textCell.setText(LocaleController.getString("Password", R.string.Password), true);
} else if (i == passcodeRow) {
textCell.setText(LocaleController.getString("Passcode", R.string.Passcode), true);
} else if (i == lastSeenRow) {
String value;
if (ContactsController.getInstance().getLoadingLastSeenInfo()) {
@ -413,7 +423,7 @@ public class PrivacySettingsActivity extends BaseFragment implements Notificatio
@Override
public int getItemViewType(int i) {
if (i == lastSeenRow || i == blockedRow || i == deleteAccountRow || i == terminateSessionsRow || i == passwordRow) {
if (i == lastSeenRow || i == blockedRow || i == deleteAccountRow || i == terminateSessionsRow || i == passwordRow || i == passcodeRow) {
return 0;
} else if (i == deleteAccountDetailRow || i == lastSeenDetailRow || i == terminateSessionsDetailRow) {
return 1;

View File

@ -224,7 +224,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter.
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
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));
@ -485,7 +485,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter.
try {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:+" + user.phone));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getParentActivity().startActivity(intent);
getParentActivity().startActivityForResult(intent, 500);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
@ -884,6 +884,11 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter.
fixLayout();
}
@Override
public void updatePhotoAtIndex(int index) {
}
@Override
public PhotoViewer.PlaceProviderObject getPlaceForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) {
if (fileLocation == null) {

View File

@ -85,7 +85,7 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);
@ -425,10 +425,16 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi
val = LocaleController.formatString("WillUnmuteIn", R.string.WillUnmuteIn, LocaleController.formatPluralString("Minutes", delta / 60));
} else if (delta < 60 * 60 * 24) {
val = LocaleController.formatString("WillUnmuteIn", R.string.WillUnmuteIn, LocaleController.formatPluralString("Hours", (int) Math.ceil(delta / 60.0f / 60)));
} else {
} else if (delta < 60 * 60 * 24 * 365) {
val = LocaleController.formatString("WillUnmuteIn", R.string.WillUnmuteIn, LocaleController.formatPluralString("Days", (int) Math.ceil(delta / 60.0f / 60 / 24)));
} else {
val = null;
}
if (val != null) {
textCell.setTextAndValue(LocaleController.getString("Notifications", R.string.Notifications), val, true);
} else {
textCell.setTextAndValue(LocaleController.getString("Notifications", R.string.Notifications), LocaleController.getString("Disabled", R.string.Disabled), true);
}
textCell.setTextAndValue(LocaleController.getString("Notifications", R.string.Notifications), val, true);
}
} else if (i == settingsSoundRow) {
String value = preferences.getString("sound_" + dialog_id, LocaleController.getString("Default", R.string.Default));

View File

@ -265,7 +265,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackgroundColor(AvatarDrawable.getProfileBackColorForId(5));
actionBar.setItemsBackground(AvatarDrawable.getButtonColorForId(5));
@ -491,7 +491,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
} else if (i == telegramFaqRow) {
try {
Intent pickIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(LocaleController.getString("TelegramFaqUrl", R.string.TelegramFaqUrl)));
getParentActivity().startActivity(pickIntent);
getParentActivity().startActivityForResult(pickIntent, 500);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
@ -706,6 +706,11 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
MediaController.getInstance().checkAutodownloadSettings();
}
@Override
public void updatePhotoAtIndex(int index) {
}
@Override
public PhotoViewer.PlaceProviderObject getPlaceForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) {
if (fileLocation == null) {
@ -994,7 +999,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
i.putExtra(Intent.EXTRA_EMAIL, new String[]{BuildVars.SEND_LOGS_EMAIL});
i.putExtra(Intent.EXTRA_SUBJECT, "last logs");
i.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
getParentActivity().startActivity(Intent.createChooser(i, "Select email application."));
getParentActivity().startActivityForResult(Intent.createChooser(i, "Select email application."), 500);
} catch (Exception e) {
e.printStackTrace();
}

View File

@ -221,7 +221,7 @@ public class VideoEditorActivity extends BaseFragment implements TextureView.Sur
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackgroundColor(0xff333333);
actionBar.setItemsBackground(R.drawable.bar_selector_white);
@ -259,7 +259,7 @@ public class VideoEditorActivity extends BaseFragment implements TextureView.Sur
ActionBarMenu menu = actionBar.createMenu();
menu.addItemWithWidth(1, R.drawable.ic_done, AndroidUtilities.dp(56));
fragmentView = inflater.inflate(R.layout.video_editor_layout, container, false);
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);
@ -578,6 +578,9 @@ public class VideoEditorActivity extends BaseFragment implements TextureView.Sur
}
private void fixLayoutInternal() {
if (getParentActivity() == null) {
return;
}
if (!AndroidUtilities.isTablet() && getParentActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) videoContainerView.getLayoutParams();
layoutParams.topMargin = AndroidUtilities.dp(16);

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