file_id
int64
1
46.7k
content
stringlengths
14
344k
repo
stringlengths
7
109
path
stringlengths
8
171
41,644
package com.blankj.utilcode.util; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.os.storage.StorageManager; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.text.TextUtils; import android.util.Log; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Array; import java.lang.reflect.Method; import androidx.core.content.FileProvider; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2018/04/20 * desc : utils about uri * </pre> */ public final class UriUtils { private UriUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /** * Resource to uri. * <p>res2Uri([res type]/[res name]) -> res2Uri(drawable/icon), res2Uri(raw/icon)</p> * <p>res2Uri([resource_id]) -> res2Uri(R.drawable.icon)</p> * * @param resPath The path of res. * @return uri */ public static Uri res2Uri(String resPath) { return Uri.parse("android.resource://" + Utils.getApp().getPackageName() + "/" + resPath); } /** * File to uri. * * @param file The file. * @return uri */ public static Uri file2Uri(final File file) { if (!UtilsBridge.isFileExists(file)) return null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { String authority = Utils.getApp().getPackageName() + ".utilcode.fileprovider"; return FileProvider.getUriForFile(Utils.getApp(), authority, file); } else { return Uri.fromFile(file); } } /** * Uri to file. * * @param uri The uri. * @return file */ public static File uri2File(final Uri uri) { if (uri == null) return null; File file = uri2FileReal(uri); if (file != null) return file; return copyUri2Cache(uri); } /** * Uri to file, without creating the cache copy if the path cannot be resolved. * * @param uri The uri. * @return file */ public static File uri2FileNoCacheCopy(final Uri uri) { if (uri == null) return null; return uri2FileReal(uri); } /** * Uri to file. * * @param uri The uri. * @return file */ private static File uri2FileReal(final Uri uri) { Log.d("UriUtils", uri.toString()); String authority = uri.getAuthority(); String scheme = uri.getScheme(); String path = uri.getPath(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && path != null) { String[] externals = new String[]{"/external/", "/external_path/"}; File file = null; for (String external : externals) { if (path.startsWith(external)) { file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + path.replace(external, "/")); if (file.exists()) { Log.d("UriUtils", uri.toString() + " -> " + external); return file; } } } file = null; if (path.startsWith("/files_path/")) { file = new File(Utils.getApp().getFilesDir().getAbsolutePath() + path.replace("/files_path/", "/")); } else if (path.startsWith("/cache_path/")) { file = new File(Utils.getApp().getCacheDir().getAbsolutePath() + path.replace("/cache_path/", "/")); } else if (path.startsWith("/external_files_path/")) { file = new File(Utils.getApp().getExternalFilesDir(null).getAbsolutePath() + path.replace("/external_files_path/", "/")); } else if (path.startsWith("/external_cache_path/")) { file = new File(Utils.getApp().getExternalCacheDir().getAbsolutePath() + path.replace("/external_cache_path/", "/")); } if (file != null && file.exists()) { Log.d("UriUtils", uri.toString() + " -> " + path); return file; } } if (ContentResolver.SCHEME_FILE.equals(scheme)) { if (path != null) return new File(path); Log.d("UriUtils", uri.toString() + " parse failed. -> 0"); return null; }// end 0 else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(Utils.getApp(), uri)) { if ("com.android.externalstorage.documents".equals(authority)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("primary".equalsIgnoreCase(type)) { return new File(Environment.getExternalStorageDirectory() + "/" + split[1]); } else { // Below logic is how External Storage provider build URI for documents // http://stackoverflow.com/questions/28605278/android-5-sd-card-label StorageManager mStorageManager = (StorageManager) Utils.getApp().getSystemService(Context.STORAGE_SERVICE); try { Class<?> storageVolumeClazz = Class.forName("android.os.storage.StorageVolume"); Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList"); Method getUuid = storageVolumeClazz.getMethod("getUuid"); Method getState = storageVolumeClazz.getMethod("getState"); Method getPath = storageVolumeClazz.getMethod("getPath"); Method isPrimary = storageVolumeClazz.getMethod("isPrimary"); Method isEmulated = storageVolumeClazz.getMethod("isEmulated"); Object result = getVolumeList.invoke(mStorageManager); final int length = Array.getLength(result); for (int i = 0; i < length; i++) { Object storageVolumeElement = Array.get(result, i); //String uuid = (String) getUuid.invoke(storageVolumeElement); final boolean mounted = Environment.MEDIA_MOUNTED.equals(getState.invoke(storageVolumeElement)) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(getState.invoke(storageVolumeElement)); //if the media is not mounted, we need not get the volume details if (!mounted) continue; //Primary storage is already handled. if ((Boolean) isPrimary.invoke(storageVolumeElement) && (Boolean) isEmulated.invoke(storageVolumeElement)) { continue; } String uuid = (String) getUuid.invoke(storageVolumeElement); if (uuid != null && uuid.equals(type)) { return new File(getPath.invoke(storageVolumeElement) + "/" + split[1]); } } } catch (Exception ex) { Log.d("UriUtils", uri.toString() + " parse failed. " + ex.toString() + " -> 1_0"); } } Log.d("UriUtils", uri.toString() + " parse failed. -> 1_0"); return null; }// end 1_0 else if ("com.android.providers.downloads.documents".equals(authority)) { String id = DocumentsContract.getDocumentId(uri); if (TextUtils.isEmpty(id)) { Log.d("UriUtils", uri.toString() + " parse failed(id is null). -> 1_1"); return null; } if (id.startsWith("raw:")) { return new File(id.substring(4)); } else if (id.startsWith("msf:")) { id = id.split(":")[1]; } long availableId = 0; try { availableId = Long.parseLong(id); } catch (Exception e) { return null; } String[] contentUriPrefixesToTry = new String[]{ "content://downloads/public_downloads", "content://downloads/all_downloads", "content://downloads/my_downloads" }; for (String contentUriPrefix : contentUriPrefixesToTry) { Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), availableId); try { File file = getFileFromUri(contentUri, "1_1"); if (file != null) { return file; } } catch (Exception ignore) { } } Log.d("UriUtils", uri.toString() + " parse failed. -> 1_1"); return null; }// end 1_1 else if ("com.android.providers.media.documents".equals(authority)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } else { Log.d("UriUtils", uri.toString() + " parse failed. -> 1_2"); return null; } final String selection = "_id=?"; final String[] selectionArgs = new String[]{split[1]}; return getFileFromUri(contentUri, selection, selectionArgs, "1_2"); }// end 1_2 else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) { return getFileFromUri(uri, "1_3"); }// end 1_3 else { Log.d("UriUtils", uri.toString() + " parse failed. -> 1_4"); return null; }// end 1_4 }// end 1 else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) { return getFileFromUri(uri, "2"); }// end 2 else { Log.d("UriUtils", uri.toString() + " parse failed. -> 3"); return null; }// end 3 } private static File getFileFromUri(final Uri uri, final String code) { return getFileFromUri(uri, null, null, code); } private static File getFileFromUri(final Uri uri, final String selection, final String[] selectionArgs, final String code) { if ("com.google.android.apps.photos.content".equals(uri.getAuthority())) { if (!TextUtils.isEmpty(uri.getLastPathSegment())) { return new File(uri.getLastPathSegment()); } } else if ("com.tencent.mtt.fileprovider".equals(uri.getAuthority())) { String path = uri.getPath(); if (!TextUtils.isEmpty(path)) { File fileDir = Environment.getExternalStorageDirectory(); return new File(fileDir, path.substring("/QQBrowser".length(), path.length())); } } else if ("com.huawei.hidisk.fileprovider".equals(uri.getAuthority())) { String path = uri.getPath(); if (!TextUtils.isEmpty(path)) { return new File(path.replace("/root", "")); } } final Cursor cursor = Utils.getApp().getContentResolver().query( uri, new String[]{"_data"}, selection, selectionArgs, null); if (cursor == null) { Log.d("UriUtils", uri.toString() + " parse failed(cursor is null). -> " + code); return null; } try { if (cursor.moveToFirst()) { final int columnIndex = cursor.getColumnIndex("_data"); if (columnIndex > -1) { return new File(cursor.getString(columnIndex)); } else { Log.d("UriUtils", uri.toString() + " parse failed(columnIndex: " + columnIndex + " is wrong). -> " + code); return null; } } else { Log.d("UriUtils", uri.toString() + " parse failed(moveToFirst return false). -> " + code); return null; } } catch (Exception e) { Log.d("UriUtils", uri.toString() + " parse failed. -> " + code); return null; } finally { cursor.close(); } } private static File copyUri2Cache(Uri uri) { Log.d("UriUtils", "copyUri2Cache() called"); InputStream is = null; try { is = Utils.getApp().getContentResolver().openInputStream(uri); File file = new File(Utils.getApp().getCacheDir(), "" + System.currentTimeMillis()); UtilsBridge.writeFileFromIS(file.getAbsolutePath(), is); return file; } catch (FileNotFoundException e) { e.printStackTrace(); return null; } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * uri to input stream. * * @param uri The uri. * @return the input stream */ public static byte[] uri2Bytes(Uri uri) { if (uri == null) return null; InputStream is = null; try { is = Utils.getApp().getContentResolver().openInputStream(uri); return UtilsBridge.inputStream2Bytes(is); } catch (FileNotFoundException e) { e.printStackTrace(); Log.d("UriUtils", "uri to bytes failed."); return null; } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
Blankj/AndroidUtilCode
lib/utilcode/src/main/java/com/blankj/utilcode/util/UriUtils.java
41,645
/* * Copyright 2012-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.web.server; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicBoolean; import org.springframework.aot.hint.RuntimeHints; import org.springframework.aot.hint.RuntimeHintsRegistrar; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.support.PropertiesLoaderUtils; import org.springframework.util.Assert; /** * Simple server-independent abstraction for mime mappings. Roughly equivalent to the * {@literal &lt;mime-mapping&gt;} element traditionally found in web.xml. * * @author Phillip Webb * @author Guirong Hu * @since 2.0.0 */ public sealed class MimeMappings implements Iterable<MimeMappings.Mapping> { /** * Default mime mapping commonly used. */ public static final MimeMappings DEFAULT = new DefaultMimeMappings(); private final Map<String, Mapping> map; /** * Create a new empty {@link MimeMappings} instance. */ public MimeMappings() { this.map = new LinkedHashMap<>(); } /** * Create a new {@link MimeMappings} instance from the specified mappings. * @param mappings the source mappings */ public MimeMappings(MimeMappings mappings) { this(mappings, true); } /** * Create a new {@link MimeMappings} from the specified mappings. * @param mappings the source mappings with extension as the key and mime-type as the * value */ public MimeMappings(Map<String, String> mappings) { Assert.notNull(mappings, "Mappings must not be null"); this.map = new LinkedHashMap<>(); mappings.forEach(this::add); } /** * Internal constructor. * @param mappings source mappings * @param mutable if the new object should be mutable. */ MimeMappings(MimeMappings mappings, boolean mutable) { Assert.notNull(mappings, "Mappings must not be null"); this.map = (mutable ? new LinkedHashMap<>(mappings.map) : Collections.unmodifiableMap(mappings.map)); } /** * Add a new mime mapping. * @param extension the file extension (excluding '.') * @param mimeType the mime type to map * @return any previous mapping or {@code null} */ public String add(String extension, String mimeType) { Assert.notNull(extension, "Extension must not be null"); Assert.notNull(mimeType, "MimeType must not be null"); Mapping previous = this.map.put(extension.toLowerCase(Locale.ENGLISH), new Mapping(extension, mimeType)); return (previous != null) ? previous.getMimeType() : null; } /** * Remove an existing mapping. * @param extension the file extension (excluding '.') * @return the removed mime mapping or {@code null} if no item was removed */ public String remove(String extension) { Assert.notNull(extension, "Extension must not be null"); Mapping previous = this.map.remove(extension.toLowerCase(Locale.ENGLISH)); return (previous != null) ? previous.getMimeType() : null; } /** * Get a mime mapping for the given extension. * @param extension the file extension (excluding '.') * @return a mime mapping or {@code null} */ public String get(String extension) { Assert.notNull(extension, "Extension must not be null"); Mapping mapping = this.map.get(extension.toLowerCase(Locale.ENGLISH)); return (mapping != null) ? mapping.getMimeType() : null; } /** * Returns all defined mappings. * @return the mappings. */ public Collection<Mapping> getAll() { return this.map.values(); } @Override public final Iterator<Mapping> iterator() { return getAll().iterator(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj instanceof MimeMappings other) { return getMap().equals(other.map); } return false; } @Override public int hashCode() { return getMap().hashCode(); } Map<String, Mapping> getMap() { return this.map; } /** * Create a new unmodifiable view of the specified mapping. Methods that attempt to * modify the returned map will throw {@link UnsupportedOperationException}s. * @param mappings the mappings * @return an unmodifiable view of the specified mappings. */ public static MimeMappings unmodifiableMappings(MimeMappings mappings) { Assert.notNull(mappings, "Mappings must not be null"); return new MimeMappings(mappings, false); } /** * Create a new lazy copy of the given mappings that will only copy entries if the * mappings are mutated. * @param mappings the source mappings * @return a new mappings instance * @since 3.0.0 */ public static MimeMappings lazyCopy(MimeMappings mappings) { Assert.notNull(mappings, "Mappings must not be null"); return new LazyMimeMappingsCopy(mappings); } /** * A single mime mapping. */ public static final class Mapping { private final String extension; private final String mimeType; public Mapping(String extension, String mimeType) { Assert.notNull(extension, "Extension must not be null"); Assert.notNull(mimeType, "MimeType must not be null"); this.extension = extension; this.mimeType = mimeType; } public String getExtension() { return this.extension; } public String getMimeType() { return this.mimeType; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj instanceof Mapping other) { return this.extension.equals(other.extension) && this.mimeType.equals(other.mimeType); } return false; } @Override public int hashCode() { return this.extension.hashCode(); } @Override public String toString() { return "Mapping [extension=" + this.extension + ", mimeType=" + this.mimeType + "]"; } } /** * {@link MimeMappings} implementation used for {@link MimeMappings#DEFAULT}. Provides * in-memory access for common mappings and lazily loads the complete set when * necessary. */ static final class DefaultMimeMappings extends MimeMappings { static final String MIME_MAPPINGS_PROPERTIES = "mime-mappings.properties"; private static final MimeMappings COMMON; static { MimeMappings mappings = new MimeMappings(); mappings.add("avi", "video/x-msvideo"); mappings.add("bin", "application/octet-stream"); mappings.add("body", "text/html"); mappings.add("class", "application/java"); mappings.add("css", "text/css"); mappings.add("dtd", "application/xml-dtd"); mappings.add("gif", "image/gif"); mappings.add("gtar", "application/x-gtar"); mappings.add("gz", "application/x-gzip"); mappings.add("htm", "text/html"); mappings.add("html", "text/html"); mappings.add("jar", "application/java-archive"); mappings.add("java", "text/x-java-source"); mappings.add("jnlp", "application/x-java-jnlp-file"); mappings.add("jpe", "image/jpeg"); mappings.add("jpeg", "image/jpeg"); mappings.add("jpg", "image/jpeg"); mappings.add("js", "text/javascript"); mappings.add("json", "application/json"); mappings.add("otf", "font/otf"); mappings.add("pdf", "application/pdf"); mappings.add("png", "image/png"); mappings.add("ps", "application/postscript"); mappings.add("tar", "application/x-tar"); mappings.add("tif", "image/tiff"); mappings.add("tiff", "image/tiff"); mappings.add("ttf", "font/ttf"); mappings.add("txt", "text/plain"); mappings.add("xht", "application/xhtml+xml"); mappings.add("xhtml", "application/xhtml+xml"); mappings.add("xls", "application/vnd.ms-excel"); mappings.add("xml", "application/xml"); mappings.add("xsl", "application/xml"); mappings.add("xslt", "application/xslt+xml"); mappings.add("wasm", "application/wasm"); mappings.add("zip", "application/zip"); COMMON = unmodifiableMappings(mappings); } private volatile Map<String, Mapping> loaded; DefaultMimeMappings() { super(new MimeMappings(), false); } @Override public Collection<Mapping> getAll() { return load().values(); } @Override public String get(String extension) { Assert.notNull(extension, "Extension must not be null"); extension = extension.toLowerCase(Locale.ENGLISH); Map<String, Mapping> loaded = this.loaded; if (loaded != null) { return get(loaded, extension); } String commonMimeType = COMMON.get(extension); if (commonMimeType != null) { return commonMimeType; } loaded = load(); return get(loaded, extension); } private String get(Map<String, Mapping> mappings, String extension) { Mapping mapping = mappings.get(extension); return (mapping != null) ? mapping.getMimeType() : null; } @Override Map<String, Mapping> getMap() { return load(); } private Map<String, Mapping> load() { Map<String, Mapping> loaded = this.loaded; if (loaded != null) { return loaded; } try { loaded = new LinkedHashMap<>(); for (Entry<?, ?> entry : PropertiesLoaderUtils .loadProperties(new ClassPathResource(MIME_MAPPINGS_PROPERTIES, getClass())) .entrySet()) { loaded.put((String) entry.getKey(), new Mapping((String) entry.getKey(), (String) entry.getValue())); } loaded = Collections.unmodifiableMap(loaded); this.loaded = loaded; return loaded; } catch (IOException ex) { throw new IllegalArgumentException("Unable to load the default MIME types", ex); } } } /** * {@link MimeMappings} implementation used to create a lazy copy only when the * mappings are mutated. */ static final class LazyMimeMappingsCopy extends MimeMappings { private final MimeMappings source; private final AtomicBoolean copied = new AtomicBoolean(); LazyMimeMappingsCopy(MimeMappings source) { this.source = source; } @Override public String add(String extension, String mimeType) { copyIfNecessary(); return super.add(extension, mimeType); } @Override public String remove(String extension) { copyIfNecessary(); return super.remove(extension); } private void copyIfNecessary() { if (this.copied.compareAndSet(false, true)) { this.source.forEach((mapping) -> add(mapping.getExtension(), mapping.getMimeType())); } } @Override public String get(String extension) { return !this.copied.get() ? this.source.get(extension) : super.get(extension); } @Override public Collection<Mapping> getAll() { return !this.copied.get() ? this.source.getAll() : super.getAll(); } @Override Map<String, Mapping> getMap() { return !this.copied.get() ? this.source.getMap() : super.getMap(); } } static class MimeMappingsRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, ClassLoader classLoader) { hints.resources() .registerPattern("org/springframework/boot/web/server/" + DefaultMimeMappings.MIME_MAPPINGS_PROPERTIES); } } }
spring-projects/spring-boot
spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/MimeMappings.java
41,646
package org.schabi.newpipe.util; import static org.schabi.newpipe.extractor.ServiceList.YouTube; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.net.ConnectivityManager; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.core.content.ContextCompat; import androidx.preference.PreferenceManager; import org.schabi.newpipe.R; import org.schabi.newpipe.extractor.MediaFormat; import org.schabi.newpipe.extractor.stream.AudioStream; import org.schabi.newpipe.extractor.stream.AudioTrackType; import org.schabi.newpipe.extractor.stream.DeliveryMethod; import org.schabi.newpipe.extractor.stream.Stream; import org.schabi.newpipe.extractor.stream.VideoStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; public final class ListHelper { // Video format in order of quality. 0=lowest quality, n=highest quality private static final List<MediaFormat> VIDEO_FORMAT_QUALITY_RANKING = List.of(MediaFormat.v3GPP, MediaFormat.WEBM, MediaFormat.MPEG_4); // Audio format in order of quality. 0=lowest quality, n=highest quality private static final List<MediaFormat> AUDIO_FORMAT_QUALITY_RANKING = List.of(MediaFormat.MP3, MediaFormat.WEBMA, MediaFormat.M4A); // Audio format in order of efficiency. 0=least efficient, n=most efficient private static final List<MediaFormat> AUDIO_FORMAT_EFFICIENCY_RANKING = List.of(MediaFormat.MP3, MediaFormat.M4A, MediaFormat.WEBMA); // Use a Set for better performance private static final Set<String> HIGH_RESOLUTION_LIST = Set.of("1440p", "2160p"); // Audio track types in order of priority. 0=lowest, n=highest private static final List<AudioTrackType> AUDIO_TRACK_TYPE_RANKING = List.of(AudioTrackType.DESCRIPTIVE, AudioTrackType.DUBBED, AudioTrackType.ORIGINAL); // Audio track types in order of priority when descriptive audio is preferred. private static final List<AudioTrackType> AUDIO_TRACK_TYPE_RANKING_DESCRIPTIVE = List.of(AudioTrackType.ORIGINAL, AudioTrackType.DUBBED, AudioTrackType.DESCRIPTIVE); /** * List of supported YouTube Itag ids. * The original order is kept. * @see {@link org.schabi.newpipe.extractor.services.youtube.ItagItem#ITAG_LIST} */ private static final List<Integer> SUPPORTED_ITAG_IDS = List.of( 17, 36, // video v3GPP 18, 34, 35, 59, 78, 22, 37, 38, // video MPEG4 43, 44, 45, 46, // video webm 171, 172, 139, 140, 141, 249, 250, 251, // audio 160, 133, 134, 135, 212, 136, 298, 137, 299, 266, // video only 278, 242, 243, 244, 245, 246, 247, 248, 271, 272, 302, 303, 308, 313, 315 ); private ListHelper() { } /** * @param context Android app context * @param videoStreams list of the video streams to check * @return index of the video stream with the default index * @see #getDefaultResolutionIndex(String, String, MediaFormat, List) */ public static int getDefaultResolutionIndex(final Context context, final List<VideoStream> videoStreams) { final String defaultResolution = computeDefaultResolution(context, R.string.default_resolution_key, R.string.default_resolution_value); return getDefaultResolutionWithDefaultFormat(context, defaultResolution, videoStreams); } /** * @param context Android app context * @param videoStreams list of the video streams to check * @param defaultResolution the default resolution to look for * @return index of the video stream with the default index * @see #getDefaultResolutionIndex(String, String, MediaFormat, List) */ public static int getResolutionIndex(final Context context, final List<VideoStream> videoStreams, final String defaultResolution) { return getDefaultResolutionWithDefaultFormat(context, defaultResolution, videoStreams); } /** * @param context Android app context * @param videoStreams list of the video streams to check * @return index of the video stream with the default index * @see #getDefaultResolutionIndex(String, String, MediaFormat, List) */ public static int getPopupDefaultResolutionIndex(final Context context, final List<VideoStream> videoStreams) { final String defaultResolution = computeDefaultResolution(context, R.string.default_popup_resolution_key, R.string.default_popup_resolution_value); return getDefaultResolutionWithDefaultFormat(context, defaultResolution, videoStreams); } /** * @param context Android app context * @param videoStreams list of the video streams to check * @param defaultResolution the default resolution to look for * @return index of the video stream with the default index * @see #getDefaultResolutionIndex(String, String, MediaFormat, List) */ public static int getPopupResolutionIndex(final Context context, final List<VideoStream> videoStreams, final String defaultResolution) { return getDefaultResolutionWithDefaultFormat(context, defaultResolution, videoStreams); } public static int getDefaultAudioFormat(final Context context, final List<AudioStream> audioStreams) { return getAudioIndexByHighestRank(audioStreams, getAudioTrackComparator(context).thenComparing(getAudioFormatComparator(context))); } public static int getDefaultAudioTrackGroup(final Context context, final List<List<AudioStream>> groupedAudioStreams) { if (groupedAudioStreams == null || groupedAudioStreams.isEmpty()) { return -1; } final Comparator<AudioStream> cmp = getAudioTrackComparator(context); final List<AudioStream> highestRanked = groupedAudioStreams.stream() .max((o1, o2) -> cmp.compare(o1.get(0), o2.get(0))) .orElse(null); return groupedAudioStreams.indexOf(highestRanked); } public static int getAudioFormatIndex(final Context context, final List<AudioStream> audioStreams, @Nullable final String trackId) { if (trackId != null) { for (int i = 0; i < audioStreams.size(); i++) { final AudioStream s = audioStreams.get(i); if (s.getAudioTrackId() != null && s.getAudioTrackId().equals(trackId)) { return i; } } } return getDefaultAudioFormat(context, audioStreams); } /** * Return a {@link Stream} list which uses the given delivery method from a {@link Stream} * list. * * @param streamList the original {@link Stream stream} list * @param deliveryMethod the {@link DeliveryMethod delivery method} * @param <S> the item type's class that extends {@link Stream} * @return a {@link Stream stream} list which uses the given delivery method */ @NonNull public static <S extends Stream> List<S> getStreamsOfSpecifiedDelivery( @Nullable final List<S> streamList, final DeliveryMethod deliveryMethod) { return getFilteredStreamList(streamList, stream -> stream.getDeliveryMethod() == deliveryMethod); } /** * Return a {@link Stream} list which only contains URL streams and non-torrent streams. * * @param streamList the original stream list * @param <S> the item type's class that extends {@link Stream} * @return a stream list which only contains URL streams and non-torrent streams */ @NonNull public static <S extends Stream> List<S> getUrlAndNonTorrentStreams( @Nullable final List<S> streamList) { return getFilteredStreamList(streamList, stream -> stream.isUrl() && stream.getDeliveryMethod() != DeliveryMethod.TORRENT); } /** * Return a {@link Stream} list which only contains streams which can be played by the player. * * <p> * Some formats are not supported, see {@link #SUPPORTED_ITAG_IDS} for more details. * Torrent streams are also removed, because they cannot be retrieved, like OPUS streams using * HLS as their delivery method, since they are not supported by ExoPlayer. * </p> * * @param <S> the item type's class that extends {@link Stream} * @param streamList the original stream list * @param serviceId the service ID from which the streams' list comes from * @return a stream list which only contains streams that can be played the player */ @NonNull public static <S extends Stream> List<S> getPlayableStreams( @Nullable final List<S> streamList, final int serviceId) { final int youtubeServiceId = YouTube.getServiceId(); return getFilteredStreamList(streamList, stream -> stream.getDeliveryMethod() != DeliveryMethod.TORRENT && (stream.getDeliveryMethod() != DeliveryMethod.HLS || stream.getFormat() != MediaFormat.OPUS) && (serviceId != youtubeServiceId || stream.getItagItem() == null || SUPPORTED_ITAG_IDS.contains(stream.getItagItem().id))); } /** * Join the two lists of video streams (video_only and normal videos), * and sort them according with default format chosen by the user. * * @param context the context to search for the format to give preference * @param videoStreams the normal videos list * @param videoOnlyStreams the video-only stream list * @param ascendingOrder true -> smallest to greatest | false -> greatest to smallest * @param preferVideoOnlyStreams if video-only streams should preferred when both video-only * streams and normal video streams are available * @return the sorted list */ @NonNull public static List<VideoStream> getSortedStreamVideosList( @NonNull final Context context, @Nullable final List<VideoStream> videoStreams, @Nullable final List<VideoStream> videoOnlyStreams, final boolean ascendingOrder, final boolean preferVideoOnlyStreams) { final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); final boolean showHigherResolutions = preferences.getBoolean( context.getString(R.string.show_higher_resolutions_key), false); final MediaFormat defaultFormat = getDefaultFormat(context, R.string.default_video_format_key, R.string.default_video_format_value); return getSortedStreamVideosList(defaultFormat, showHigherResolutions, videoStreams, videoOnlyStreams, ascendingOrder, preferVideoOnlyStreams); } /** * Get a sorted list containing a set of default resolution info * and additional resolution info if showHigherResolutions is true. * * @param resources the resources to get the resolutions from * @param defaultResolutionKey the settings key of the default resolution * @param additionalResolutionKey the settings key of the additional resolutions * @param showHigherResolutions if higher resolutions should be included in the sorted list * @return a sorted list containing the default and maybe additional resolutions */ public static List<String> getSortedResolutionList( final Resources resources, final int defaultResolutionKey, final int additionalResolutionKey, final boolean showHigherResolutions) { final List<String> resolutions = new ArrayList<>(Arrays.asList( resources.getStringArray(defaultResolutionKey))); if (!showHigherResolutions) { return resolutions; } final List<String> additionalResolutions = Arrays.asList( resources.getStringArray(additionalResolutionKey)); // keep "best resolution" at the top resolutions.addAll(1, additionalResolutions); return resolutions; } public static boolean isHighResolutionSelected(final String selectedResolution, final int additionalResolutionKey, final Resources resources) { return Arrays.asList(resources.getStringArray( additionalResolutionKey)) .contains(selectedResolution); } /** * Filter the list of audio streams and return a list with the preferred stream for * each audio track. Streams are sorted with the preferred language in the first position. * * @param context the context to search for the track to give preference * @param audioStreams the list of audio streams * @return the sorted, filtered list */ public static List<AudioStream> getFilteredAudioStreams( @NonNull final Context context, @Nullable final List<AudioStream> audioStreams) { if (audioStreams == null) { return Collections.emptyList(); } final HashMap<String, AudioStream> collectedStreams = new HashMap<>(); final Comparator<AudioStream> cmp = getAudioFormatComparator(context); for (final AudioStream stream : audioStreams) { if (stream.getDeliveryMethod() == DeliveryMethod.TORRENT || (stream.getDeliveryMethod() == DeliveryMethod.HLS && stream.getFormat() == MediaFormat.OPUS)) { continue; } final String trackId = Objects.toString(stream.getAudioTrackId(), ""); final AudioStream presentStream = collectedStreams.get(trackId); if (presentStream == null || cmp.compare(stream, presentStream) > 0) { collectedStreams.put(trackId, stream); } } // Filter unknown audio tracks if there are multiple tracks if (collectedStreams.size() > 1) { collectedStreams.remove(""); } // Sort collected streams by name return collectedStreams.values().stream().sorted(getAudioTrackNameComparator(context)) .collect(Collectors.toList()); } /** * Group the list of audioStreams by their track ID and sort the resulting list by track name. * * @param context app context to get track names for sorting * @param audioStreams list of audio streams * @return list of audio streams lists representing individual tracks */ public static List<List<AudioStream>> getGroupedAudioStreams( @NonNull final Context context, @Nullable final List<AudioStream> audioStreams) { if (audioStreams == null) { return Collections.emptyList(); } final HashMap<String, List<AudioStream>> collectedStreams = new HashMap<>(); for (final AudioStream stream : audioStreams) { final String trackId = Objects.toString(stream.getAudioTrackId(), ""); if (collectedStreams.containsKey(trackId)) { collectedStreams.get(trackId).add(stream); } else { final List<AudioStream> list = new ArrayList<>(); list.add(stream); collectedStreams.put(trackId, list); } } // Filter unknown audio tracks if there are multiple tracks if (collectedStreams.size() > 1) { collectedStreams.remove(""); } // Sort tracks alphabetically, sort track streams by quality final Comparator<AudioStream> nameCmp = getAudioTrackNameComparator(context); final Comparator<AudioStream> formatCmp = getAudioFormatComparator(context); return collectedStreams.values().stream() .sorted((o1, o2) -> nameCmp.compare(o1.get(0), o2.get(0))) .map(streams -> streams.stream().sorted(formatCmp).collect(Collectors.toList())) .collect(Collectors.toList()); } /*////////////////////////////////////////////////////////////////////////// // Utils //////////////////////////////////////////////////////////////////////////*/ /** * Get a filtered stream list, by using Java 8 Stream's API and the given predicate. * * @param streamList the stream list to filter * @param streamListPredicate the predicate which will be used to filter streams * @param <S> the item type's class that extends {@link Stream} * @return a new stream list filtered using the given predicate */ private static <S extends Stream> List<S> getFilteredStreamList( @Nullable final List<S> streamList, final Predicate<S> streamListPredicate) { if (streamList == null) { return Collections.emptyList(); } return streamList.stream() .filter(streamListPredicate) .collect(Collectors.toList()); } private static String computeDefaultResolution(@NonNull final Context context, final int key, final int value) { final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); // Load the preferred resolution otherwise the best available String resolution = preferences != null ? preferences.getString(context.getString(key), context.getString(value)) : context.getString(R.string.best_resolution_key); final String maxResolution = getResolutionLimit(context); if (maxResolution != null && (resolution.equals(context.getString(R.string.best_resolution_key)) || compareVideoStreamResolution(maxResolution, resolution) < 1)) { resolution = maxResolution; } return resolution; } /** * Return the index of the default stream in the list, that will be sorted in the process, based * on the parameters defaultResolution and defaultFormat. * * @param defaultResolution the default resolution to look for * @param bestResolutionKey key of the best resolution * @param defaultFormat the default format to look for * @param videoStreams a mutable list of the video streams to check (it will be sorted in * place) * @return index of the default resolution&format in the sorted videoStreams */ static int getDefaultResolutionIndex(final String defaultResolution, final String bestResolutionKey, final MediaFormat defaultFormat, @Nullable final List<VideoStream> videoStreams) { if (videoStreams == null || videoStreams.isEmpty()) { return -1; } sortStreamList(videoStreams, false); if (defaultResolution.equals(bestResolutionKey)) { return 0; } final int defaultStreamIndex = getVideoStreamIndex(defaultResolution, defaultFormat, videoStreams); // this is actually an error, // but maybe there is really no stream fitting to the default value. if (defaultStreamIndex == -1) { return 0; } return defaultStreamIndex; } /** * Join the two lists of video streams (video_only and normal videos), * and sort them according with default format chosen by the user. * * @param defaultFormat format to give preference * @param showHigherResolutions show >1080p resolutions * @param videoStreams normal videos list * @param videoOnlyStreams video only stream list * @param ascendingOrder true -> smallest to greatest | false -> greatest to smallest * @param preferVideoOnlyStreams if video-only streams should preferred when both video-only * streams and normal video streams are available * @return the sorted list */ @NonNull static List<VideoStream> getSortedStreamVideosList( @Nullable final MediaFormat defaultFormat, final boolean showHigherResolutions, @Nullable final List<VideoStream> videoStreams, @Nullable final List<VideoStream> videoOnlyStreams, final boolean ascendingOrder, final boolean preferVideoOnlyStreams ) { // Determine order of streams // The last added list is preferred final List<List<VideoStream>> videoStreamsOrdered = preferVideoOnlyStreams ? Arrays.asList(videoStreams, videoOnlyStreams) : Arrays.asList(videoOnlyStreams, videoStreams); final List<VideoStream> allInitialStreams = videoStreamsOrdered.stream() // Ignore lists that are null .filter(Objects::nonNull) .flatMap(List::stream) // Filter out higher resolutions (or not if high resolutions should always be shown) .filter(stream -> showHigherResolutions || !HIGH_RESOLUTION_LIST.contains(stream.getResolution() // Replace any frame rate with nothing .replaceAll("p\\d+$", "p"))) .collect(Collectors.toList()); final HashMap<String, VideoStream> hashMap = new HashMap<>(); // Add all to the hashmap for (final VideoStream videoStream : allInitialStreams) { hashMap.put(videoStream.getResolution(), videoStream); } // Override the values when the key == resolution, with the defaultFormat for (final VideoStream videoStream : allInitialStreams) { if (videoStream.getFormat() == defaultFormat) { hashMap.put(videoStream.getResolution(), videoStream); } } // Return the sorted list return sortStreamList(new ArrayList<>(hashMap.values()), ascendingOrder); } /** * Sort the streams list depending on the parameter ascendingOrder; * <p> * It works like that:<br> * - Take a string resolution, remove the letters, replace "0p60" (for 60fps videos) with "1" * and sort by the greatest:<br> * <blockquote><pre> * 720p -> 720 * 720p60 -> 721 * 360p -> 360 * 1080p -> 1080 * 1080p60 -> 1081 * <br> * ascendingOrder ? 360 < 720 < 721 < 1080 < 1081 * !ascendingOrder ? 1081 < 1080 < 721 < 720 < 360</pre></blockquote> * * @param videoStreams list that the sorting will be applied * @param ascendingOrder true -> smallest to greatest | false -> greatest to smallest * @return The sorted list (same reference as parameter videoStreams) */ private static List<VideoStream> sortStreamList(final List<VideoStream> videoStreams, final boolean ascendingOrder) { // Compares the quality of two video streams. final Comparator<VideoStream> comparator = Comparator.nullsLast(Comparator .comparing(VideoStream::getResolution, ListHelper::compareVideoStreamResolution) .thenComparingInt(s -> VIDEO_FORMAT_QUALITY_RANKING.indexOf(s.getFormat()))); Collections.sort(videoStreams, ascendingOrder ? comparator : comparator.reversed()); return videoStreams; } /** * Get the audio-stream from the list with the highest rank, depending on the comparator. * Format will be ignored if it yields no results. * * @param audioStreams List of audio streams * @param comparator The comparator used for determining the max/best/highest ranked value * @return Index of audio stream that produces the highest ranked result or -1 if not found */ static int getAudioIndexByHighestRank(@Nullable final List<AudioStream> audioStreams, final Comparator<AudioStream> comparator) { if (audioStreams == null || audioStreams.isEmpty()) { return -1; } final AudioStream highestRankedAudioStream = audioStreams.stream() .max(comparator).orElse(null); return audioStreams.indexOf(highestRankedAudioStream); } /** * Locates a possible match for the given resolution and format in the provided list. * * <p>In this order:</p> * * <ol> * <li>Find a format and resolution match</li> * <li>Find a format and resolution match and ignore the refresh</li> * <li>Find a resolution match</li> * <li>Find a resolution match and ignore the refresh</li> * <li>Find a resolution just below the requested resolution and ignore the refresh</li> * <li>Give up</li> * </ol> * * @param targetResolution the resolution to look for * @param targetFormat the format to look for * @param videoStreams the available video streams * @return the index of the preferred video stream */ static int getVideoStreamIndex(@NonNull final String targetResolution, final MediaFormat targetFormat, @NonNull final List<VideoStream> videoStreams) { int fullMatchIndex = -1; int fullMatchNoRefreshIndex = -1; int resMatchOnlyIndex = -1; int resMatchOnlyNoRefreshIndex = -1; int lowerResMatchNoRefreshIndex = -1; final String targetResolutionNoRefresh = targetResolution.replaceAll("p\\d+$", "p"); for (int idx = 0; idx < videoStreams.size(); idx++) { final MediaFormat format = targetFormat == null ? null : videoStreams.get(idx).getFormat(); final String resolution = videoStreams.get(idx).getResolution(); final String resolutionNoRefresh = resolution.replaceAll("p\\d+$", "p"); if (format == targetFormat && resolution.equals(targetResolution)) { fullMatchIndex = idx; } if (format == targetFormat && resolutionNoRefresh.equals(targetResolutionNoRefresh)) { fullMatchNoRefreshIndex = idx; } if (resMatchOnlyIndex == -1 && resolution.equals(targetResolution)) { resMatchOnlyIndex = idx; } if (resMatchOnlyNoRefreshIndex == -1 && resolutionNoRefresh.equals(targetResolutionNoRefresh)) { resMatchOnlyNoRefreshIndex = idx; } if (lowerResMatchNoRefreshIndex == -1 && compareVideoStreamResolution( resolutionNoRefresh, targetResolutionNoRefresh) < 0) { lowerResMatchNoRefreshIndex = idx; } } if (fullMatchIndex != -1) { return fullMatchIndex; } if (fullMatchNoRefreshIndex != -1) { return fullMatchNoRefreshIndex; } if (resMatchOnlyIndex != -1) { return resMatchOnlyIndex; } if (resMatchOnlyNoRefreshIndex != -1) { return resMatchOnlyNoRefreshIndex; } return lowerResMatchNoRefreshIndex; } /** * Fetches the desired resolution or returns the default if it is not found. * The resolution will be reduced if video chocking is active. * * @param context Android app context * @param defaultResolution the default resolution * @param videoStreams the list of video streams to check * @return the index of the preferred video stream */ private static int getDefaultResolutionWithDefaultFormat(@NonNull final Context context, final String defaultResolution, final List<VideoStream> videoStreams) { final MediaFormat defaultFormat = getDefaultFormat(context, R.string.default_video_format_key, R.string.default_video_format_value); return getDefaultResolutionIndex(defaultResolution, context.getString(R.string.best_resolution_key), defaultFormat, videoStreams); } @Nullable private static MediaFormat getDefaultFormat(@NonNull final Context context, @StringRes final int defaultFormatKey, @StringRes final int defaultFormatValueKey) { final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); final String defaultFormat = context.getString(defaultFormatValueKey); final String defaultFormatString = preferences.getString( context.getString(defaultFormatKey), defaultFormat ); return getMediaFormatFromKey(context, defaultFormatString); } @Nullable private static MediaFormat getMediaFormatFromKey(@NonNull final Context context, @NonNull final String formatKey) { MediaFormat format = null; if (formatKey.equals(context.getString(R.string.video_webm_key))) { format = MediaFormat.WEBM; } else if (formatKey.equals(context.getString(R.string.video_mp4_key))) { format = MediaFormat.MPEG_4; } else if (formatKey.equals(context.getString(R.string.video_3gp_key))) { format = MediaFormat.v3GPP; } else if (formatKey.equals(context.getString(R.string.audio_webm_key))) { format = MediaFormat.WEBMA; } else if (formatKey.equals(context.getString(R.string.audio_m4a_key))) { format = MediaFormat.M4A; } return format; } private static int compareVideoStreamResolution(@NonNull final String r1, @NonNull final String r2) { try { final int res1 = Integer.parseInt(r1.replaceAll("0p\\d+$", "1") .replaceAll("[^\\d.]", "")); final int res2 = Integer.parseInt(r2.replaceAll("0p\\d+$", "1") .replaceAll("[^\\d.]", "")); return res1 - res2; } catch (final NumberFormatException e) { // Consider the first one greater because we don't know if the two streams are // different or not (a NumberFormatException was thrown so we don't know the resolution // of one stream or of all streams) return 1; } } static boolean isLimitingDataUsage(@NonNull final Context context) { return getResolutionLimit(context) != null; } /** * The maximum resolution allowed. * * @param context App context * @return maximum resolution allowed or null if there is no maximum */ private static String getResolutionLimit(@NonNull final Context context) { String resolutionLimit = null; if (isMeteredNetwork(context)) { final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); final String defValue = context.getString(R.string.limit_data_usage_none_key); final String value = preferences.getString( context.getString(R.string.limit_mobile_data_usage_key), defValue); resolutionLimit = defValue.equals(value) ? null : value; } return resolutionLimit; } /** * The current network is metered (like mobile data)? * * @param context App context * @return {@code true} if connected to a metered network */ public static boolean isMeteredNetwork(@NonNull final Context context) { final ConnectivityManager manager = ContextCompat.getSystemService(context, ConnectivityManager.class); if (manager == null || manager.getActiveNetworkInfo() == null) { return false; } return manager.isActiveNetworkMetered(); } /** * Get a {@link Comparator} to compare {@link AudioStream}s by their format and bitrate. * * <p>The preferred stream will be ordered last.</p> * * @param context app context * @return Comparator */ private static Comparator<AudioStream> getAudioFormatComparator( final @NonNull Context context) { final MediaFormat defaultFormat = getDefaultFormat(context, R.string.default_audio_format_key, R.string.default_audio_format_value); return getAudioFormatComparator(defaultFormat, isLimitingDataUsage(context)); } /** * Get a {@link Comparator} to compare {@link AudioStream}s by their format and bitrate. * * <p>The preferred stream will be ordered last.</p> * * @param defaultFormat the default format to look for * @param limitDataUsage choose low bitrate audio stream * @return Comparator */ static Comparator<AudioStream> getAudioFormatComparator( @Nullable final MediaFormat defaultFormat, final boolean limitDataUsage) { final List<MediaFormat> formatRanking = limitDataUsage ? AUDIO_FORMAT_EFFICIENCY_RANKING : AUDIO_FORMAT_QUALITY_RANKING; Comparator<AudioStream> bitrateComparator = Comparator.comparingInt(AudioStream::getAverageBitrate); if (limitDataUsage) { bitrateComparator = bitrateComparator.reversed(); } return Comparator.comparing(AudioStream::getFormat, (o1, o2) -> { if (defaultFormat != null) { return Boolean.compare(o1 == defaultFormat, o2 == defaultFormat); } return 0; }).thenComparing(bitrateComparator).thenComparingInt( stream -> formatRanking.indexOf(stream.getFormat())); } /** * Get a {@link Comparator} to compare {@link AudioStream}s by their tracks. * * <p>Tracks will be compared this order:</p> * <ol> * <li>If {@code preferOriginalAudio}: use original audio</li> * <li>Language matches {@code preferredLanguage}</li> * <li> * Track type ranks highest in this order: * <i>Original</i> > <i>Dubbed</i> > <i>Descriptive</i> * <p>If {@code preferDescriptiveAudio}: * <i>Descriptive</i> > <i>Dubbed</i> > <i>Original</i></p> * </li> * <li>Language is English</li> * </ol> * * <p>The preferred track will be ordered last.</p> * * @param context App context * @return Comparator */ private static Comparator<AudioStream> getAudioTrackComparator( @NonNull final Context context) { final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); final Locale preferredLanguage = Localization.getPreferredLocale(context); final boolean preferOriginalAudio = preferences.getBoolean(context.getString(R.string.prefer_original_audio_key), false); final boolean preferDescriptiveAudio = preferences.getBoolean(context.getString(R.string.prefer_descriptive_audio_key), false); return getAudioTrackComparator(preferredLanguage, preferOriginalAudio, preferDescriptiveAudio); } /** * Get a {@link Comparator} to compare {@link AudioStream}s by their tracks. * * <p>Tracks will be compared this order:</p> * <ol> * <li>If {@code preferOriginalAudio}: use original audio</li> * <li>Language matches {@code preferredLanguage}</li> * <li> * Track type ranks highest in this order: * <i>Original</i> > <i>Dubbed</i> > <i>Descriptive</i> * <p>If {@code preferDescriptiveAudio}: * <i>Descriptive</i> > <i>Dubbed</i> > <i>Original</i></p> * </li> * <li>Language is English</li> * </ol> * * <p>The preferred track will be ordered last.</p> * * @param preferredLanguage Preferred audio stream language * @param preferOriginalAudio Get the original audio track regardless of its language * @param preferDescriptiveAudio Prefer the descriptive audio track if available * @return Comparator */ static Comparator<AudioStream> getAudioTrackComparator( final Locale preferredLanguage, final boolean preferOriginalAudio, final boolean preferDescriptiveAudio) { final String langCode = preferredLanguage.getISO3Language(); final List<AudioTrackType> trackTypeRanking = preferDescriptiveAudio ? AUDIO_TRACK_TYPE_RANKING_DESCRIPTIVE : AUDIO_TRACK_TYPE_RANKING; return Comparator.comparing(AudioStream::getAudioTrackType, (o1, o2) -> { if (preferOriginalAudio) { return Boolean.compare( o1 == AudioTrackType.ORIGINAL, o2 == AudioTrackType.ORIGINAL); } return 0; }).thenComparing(AudioStream::getAudioLocale, Comparator.nullsFirst(Comparator.comparing( locale -> locale.getISO3Language().equals(langCode)))) .thenComparing(AudioStream::getAudioTrackType, Comparator.nullsFirst(Comparator.comparingInt(trackTypeRanking::indexOf))) .thenComparing(AudioStream::getAudioLocale, Comparator.nullsFirst(Comparator.comparing( locale -> locale.getISO3Language().equals( Locale.ENGLISH.getISO3Language())))); } /** * Get a {@link Comparator} to compare {@link AudioStream}s by their languages and track types * for alphabetical sorting. * * @param context app context for localization * @return Comparator */ private static Comparator<AudioStream> getAudioTrackNameComparator( @NonNull final Context context) { final Locale appLoc = Localization.getAppLocale(context); return Comparator.comparing(AudioStream::getAudioLocale, Comparator.nullsLast( Comparator.comparing(locale -> locale.getDisplayName(appLoc)))) .thenComparing(AudioStream::getAudioTrackType, Comparator.nullsLast( Comparator.naturalOrder())); } }
TeamNewPipe/NewPipe
app/src/main/java/org/schabi/newpipe/util/ListHelper.java
41,647
package cn.hutool.core.io; import cn.hutool.core.util.ArrayUtil; import java.math.BigInteger; import java.util.Arrays; import java.util.Objects; /** * 文件类型魔数封装 * * @author CherryRum * @since 5.8.12 */ public enum FileMagicNumber { UNKNOWN(null, null) { @Override public boolean match(final byte[] bytes) { return false; } }, //image start--------------------------------------------- JPEG("image/jpeg", "jpg") { @Override public boolean match(final byte[] bytes) { return bytes.length > 2 && Objects.equals(bytes[0], (byte) 0xff) && Objects.equals(bytes[1], (byte) 0xd8) && Objects.equals(bytes[2], (byte) 0xff); } }, JXR("image/vnd.ms-photo", "jxr") { @Override public boolean match(final byte[] bytes) { //file magic number https://www.iana.org/assignments/media-types/image/jxr return bytes.length > 2 && Objects.equals(bytes[0], (byte) 0x49) && Objects.equals(bytes[1], (byte) 0x49) && Objects.equals(bytes[2], (byte) 0xbc); } }, APNG("image/apng", "apng") { @Override public boolean match(final byte[] bytes) { final boolean b = bytes.length > 8 && Objects.equals(bytes[0], (byte) 0x89) && Objects.equals(bytes[1], (byte) 0x50) && Objects.equals(bytes[2], (byte) 0x4e) && Objects.equals(bytes[3], (byte) 0x47) && Objects.equals(bytes[4], (byte) 0x0d) && Objects.equals(bytes[5], (byte) 0x0a) && Objects.equals(bytes[6], (byte) 0x1a) && Objects.equals(bytes[7], (byte) 0x0a); if (b) { int i = 8; while (i < bytes.length) { try { final int dataLength = new BigInteger(1, Arrays.copyOfRange(bytes, i, i + 4)).intValue(); i += 4; final byte[] bytes1 = Arrays.copyOfRange(bytes, i, i + 4); final String chunkType = new String(bytes1); i += 4; if (Objects.equals(chunkType, "IDAT") || Objects.equals(chunkType, "IEND")) { return false; } else if (Objects.equals(chunkType, "acTL")) { return true; } i += dataLength + 4; } catch (final Exception e) { return false; } } } return false; } }, PNG("image/png", "png") { @Override public boolean match(final byte[] bytes) { return bytes.length > 3 && Objects.equals(bytes[0], (byte) 0x89) && Objects.equals(bytes[1], (byte) 0x50) && Objects.equals(bytes[2], (byte) 0x4e) && Objects.equals(bytes[3], (byte) 0x47); } }, GIF("image/gif", "gif") { @Override public boolean match(final byte[] bytes) { return bytes.length > 2 && Objects.equals(bytes[0], (byte) 0x47) && Objects.equals(bytes[1], (byte) 0x49) && Objects.equals(bytes[2], (byte) 0x46); } }, BMP("image/bmp", "bmp") { @Override public boolean match(final byte[] bytes) { return bytes.length > 1 && Objects.equals(bytes[0], (byte) 0x42) && Objects.equals(bytes[1], (byte) 0x4d); } }, TIFF("image/tiff", "tiff") { @Override public boolean match(final byte[] bytes) { if (bytes.length < 4) { return false; } final boolean flag1 = Objects.equals(bytes[0], (byte) 0x49) && Objects.equals(bytes[1], (byte) 0x49) && Objects.equals(bytes[2], (byte) 0x2a) && Objects.equals(bytes[3], (byte) 0x00); final boolean flag2 = (Objects.equals(bytes[0], (byte) 0x4d) && Objects.equals(bytes[1], (byte) 0x4d) && Objects.equals(bytes[2], (byte) 0x00) && Objects.equals(bytes[3], (byte) 0x2a)); return flag1 || flag2; } }, DWG("image/vnd.dwg", "dwg") { @Override public boolean match(final byte[] bytes) { return bytes.length > 10 && Objects.equals(bytes[0], (byte) 0x41) && Objects.equals(bytes[1], (byte) 0x43) && Objects.equals(bytes[2], (byte) 0x31) && Objects.equals(bytes[3], (byte) 0x30); } }, WEBP("image/webp", "webp") { @Override public boolean match(final byte[] bytes) { return bytes.length > 11 && Objects.equals(bytes[8], (byte) 0x57) && Objects.equals(bytes[9], (byte) 0x45) && Objects.equals(bytes[10], (byte) 0x42) && Objects.equals(bytes[11], (byte) 0x50); } }, PSD("image/vnd.adobe.photoshop", "psd") { @Override public boolean match(final byte[] bytes) { return bytes.length > 3 && Objects.equals(bytes[0], (byte) 0x38) && Objects.equals(bytes[1], (byte) 0x42) && Objects.equals(bytes[2], (byte) 0x50) && Objects.equals(bytes[3], (byte) 0x53); } }, ICO("image/x-icon", "ico") { @Override public boolean match(final byte[] bytes) { return bytes.length > 3 && Objects.equals(bytes[0], (byte) 0x00) && Objects.equals(bytes[1], (byte) 0x00) && Objects.equals(bytes[2], (byte) 0x01) && Objects.equals(bytes[3], (byte) 0x00); } }, XCF("image/x-xcf", "xcf") { @Override public boolean match(final byte[] bytes) { return bytes.length > 9 && Objects.equals(bytes[0], (byte) 0x67) && Objects.equals(bytes[1], (byte) 0x69) && Objects.equals(bytes[2], (byte) 0x6d) && Objects.equals(bytes[3], (byte) 0x70) && Objects.equals(bytes[4], (byte) 0x20) && Objects.equals(bytes[5], (byte) 0x78) && Objects.equals(bytes[6], (byte) 0x63) && Objects.equals(bytes[7], (byte) 0x66) && Objects.equals(bytes[8], (byte) 0x20) && Objects.equals(bytes[9], (byte) 0x76); } }, //image end----------------------------------------------- //audio start--------------------------------------------- WAV("audio/x-wav", "wav") { @Override public boolean match(final byte[] bytes) { return bytes.length > 11 && Objects.equals(bytes[0], (byte) 0x52) && Objects.equals(bytes[1], (byte) 0x49) && Objects.equals(bytes[2], (byte) 0x46) && Objects.equals(bytes[3], (byte) 0x46) && Objects.equals(bytes[8], (byte) 0x57) && Objects.equals(bytes[9], (byte) 0x41) && Objects.equals(bytes[10], (byte) 0x56) && Objects.equals(bytes[11], (byte) 0x45); } }, MIDI("audio/midi", "midi") { @Override public boolean match(final byte[] bytes) { return bytes.length > 3 && Objects.equals(bytes[0], (byte) 0x4d) && Objects.equals(bytes[1], (byte) 0x54) && Objects.equals(bytes[2], (byte) 0x68) && Objects.equals(bytes[3], (byte) 0x64); } }, MP3("audio/mpeg", "mp3") { @Override public boolean match(final byte[] bytes) { if (bytes.length < 2) { return false; } final boolean flag1 = Objects.equals(bytes[0], (byte) 0x49) && Objects.equals(bytes[1], (byte) 0x44) && Objects.equals(bytes[2], (byte) 0x33); final boolean flag2 = Objects.equals(bytes[0], (byte) 0xFF) && Objects.equals(bytes[1], (byte) 0xFB); final boolean flag3 = Objects.equals(bytes[0], (byte) 0xFF) && Objects.equals(bytes[1], (byte) 0xF3); final boolean flag4 = Objects.equals(bytes[0], (byte) 0xFF) && Objects.equals(bytes[1], (byte) 0xF2); return flag1 || flag2 || flag3 || flag4; } }, OGG("audio/ogg", "ogg") { @Override public boolean match(final byte[] bytes) { return bytes.length > 3 && Objects.equals(bytes[0], (byte) 0x4f) && Objects.equals(bytes[1], (byte) 0x67) && Objects.equals(bytes[2], (byte) 0x67) && Objects.equals(bytes[3], (byte) 0x53); } }, FLAC("audio/x-flac", "flac") { @Override public boolean match(final byte[] bytes) { return bytes.length > 3 && Objects.equals(bytes[0], (byte) 0x66) && Objects.equals(bytes[1], (byte) 0x4c) && Objects.equals(bytes[2], (byte) 0x61) && Objects.equals(bytes[3], (byte) 0x43); } }, M4A("audio/mp4", "m4a") { @Override public boolean match(final byte[] bytes) { return (bytes.length > 10 && Objects.equals(bytes[4], (byte) 0x66) && Objects.equals(bytes[5], (byte) 0x74) && Objects.equals(bytes[6], (byte) 0x79) && Objects.equals(bytes[7], (byte) 0x70) && Objects.equals(bytes[8], (byte) 0x4d) && Objects.equals(bytes[9], (byte) 0x34) && Objects.equals(bytes[10], (byte) 0x41)) || (Objects.equals(bytes[0], (byte) 0x4d) && Objects.equals(bytes[1], (byte) 0x34) && Objects.equals(bytes[2], (byte) 0x41) && Objects.equals(bytes[3], (byte) 0x20)); } }, AAC("audio/aac", "aac") { @Override public boolean match(final byte[] bytes) { if (bytes.length < 1) { return false; } final boolean flag1 = Objects.equals(bytes[0], (byte) 0xFF) && Objects.equals(bytes[1], (byte) 0xF1); final boolean flag2 = Objects.equals(bytes[0], (byte) 0xFF) && Objects.equals(bytes[1], (byte) 0xF9); return flag1 || flag2; } }, AMR("audio/amr", "amr") { @Override public boolean match(final byte[] bytes) { //single-channel if (bytes.length < 11) { return false; } final boolean flag1 = Objects.equals(bytes[0], (byte) 0x23) && Objects.equals(bytes[1], (byte) 0x21) && Objects.equals(bytes[2], (byte) 0x41) && Objects.equals(bytes[3], (byte) 0x4d) && Objects.equals(bytes[4], (byte) 0x52) && Objects.equals(bytes[5], (byte) 0x0A); //multi-channel: final boolean flag2 = Objects.equals(bytes[0], (byte) 0x23) && Objects.equals(bytes[1], (byte) 0x21) && Objects.equals(bytes[2], (byte) 0x41) && Objects.equals(bytes[3], (byte) 0x4d) && Objects.equals(bytes[4], (byte) 0x52) && Objects.equals(bytes[5], (byte) 0x5F) && Objects.equals(bytes[6], (byte) 0x4d) && Objects.equals(bytes[7], (byte) 0x43) && Objects.equals(bytes[8], (byte) 0x31) && Objects.equals(bytes[9], (byte) 0x2e) && Objects.equals(bytes[10], (byte) 0x30) && Objects.equals(bytes[11], (byte) 0x0a); return flag1 || flag2; } }, AC3("audio/ac3", "ac3") { @Override public boolean match(final byte[] bytes) { return bytes.length > 2 && Objects.equals(bytes[0], (byte) 0x0b) && Objects.equals(bytes[1], (byte) 0x77); } }, AIFF("audio/x-aiff", "aiff") { @Override public boolean match(final byte[] bytes) { return bytes.length > 11 && Objects.equals(bytes[0], (byte) 0x46) && Objects.equals(bytes[1], (byte) 0x4f) && Objects.equals(bytes[2], (byte) 0x52) && Objects.equals(bytes[3], (byte) 0x4d) && Objects.equals(bytes[8], (byte) 0x41) && Objects.equals(bytes[9], (byte) 0x49) && Objects.equals(bytes[10], (byte) 0x46) && Objects.equals(bytes[11], (byte) 0x46); } }, //audio end----------------------------------------------- //font start--------------------------------------------- // The existing registration "application/font-woff" is deprecated in favor of "font/woff". WOFF("font/woff", "woff") { @Override public boolean match(final byte[] bytes) { if (bytes.length < 8) { return false; } final boolean flag1 = Objects.equals(bytes[0], (byte) 0x77) && Objects.equals(bytes[1], (byte) 0x4f) && Objects.equals(bytes[2], (byte) 0x46) && Objects.equals(bytes[3], (byte) 0x46); final boolean flag2 = Objects.equals(bytes[4], (byte) 0x00) && Objects.equals(bytes[5], (byte) 0x01) && Objects.equals(bytes[6], (byte) 0x00) && Objects.equals(bytes[7], (byte) 0x00); final boolean flag3 = Objects.equals(bytes[4], (byte) 0x4f) && Objects.equals(bytes[5], (byte) 0x54) && Objects.equals(bytes[6], (byte) 0x54) && Objects.equals(bytes[7], (byte) 0x4f); final boolean flag4 = Objects.equals(bytes[4], (byte) 0x74) && Objects.equals(bytes[5], (byte) 0x72) && Objects.equals(bytes[6], (byte) 0x75) && Objects.equals(bytes[7], (byte) 0x65); return flag1 && (flag2 || flag3 || flag4); } }, WOFF2("font/woff2", "woff2") { @Override public boolean match(final byte[] bytes) { if (bytes.length < 8) { return false; } final boolean flag1 = Objects.equals(bytes[0], (byte) 0x77) && Objects.equals(bytes[1], (byte) 0x4f) && Objects.equals(bytes[2], (byte) 0x46) && Objects.equals(bytes[3], (byte) 0x32); final boolean flag2 = Objects.equals(bytes[4], (byte) 0x00) && Objects.equals(bytes[5], (byte) 0x01) && Objects.equals(bytes[6], (byte) 0x00) && Objects.equals(bytes[7], (byte) 0x00); final boolean flag3 = Objects.equals(bytes[4], (byte) 0x4f) && Objects.equals(bytes[5], (byte) 0x54) && Objects.equals(bytes[6], (byte) 0x54) && Objects.equals(bytes[7], (byte) 0x4f); final boolean flag4 = Objects.equals(bytes[4], (byte) 0x74) && Objects.equals(bytes[5], (byte) 0x72) && Objects.equals(bytes[6], (byte) 0x75) && Objects.equals(bytes[7], (byte) 0x65); return flag1 && (flag2 || flag3 || flag4); } }, TTF("font/ttf", "ttf") { @Override public boolean match(final byte[] bytes) { return bytes.length > 4 && Objects.equals(bytes[0], (byte) 0x00) && Objects.equals(bytes[1], (byte) 0x01) && Objects.equals(bytes[2], (byte) 0x00) && Objects.equals(bytes[3], (byte) 0x00) && Objects.equals(bytes[4], (byte) 0x00); } }, OTF("font/otf", "otf") { @Override public boolean match(final byte[] bytes) { return bytes.length > 4 && Objects.equals(bytes[0], (byte) 0x4f) && Objects.equals(bytes[1], (byte) 0x54) && Objects.equals(bytes[2], (byte) 0x54) && Objects.equals(bytes[3], (byte) 0x4f) && Objects.equals(bytes[4], (byte) 0x00); } }, //font end----------------------------------------------- //archive start----------------------------------------- EPUB("application/epub+zip", "epub") { @Override public boolean match(final byte[] bytes) { return bytes.length > 58 && Objects.equals(bytes[0], (byte) 0x50) && Objects.equals(bytes[1], (byte) 0x4b) && Objects.equals(bytes[2], (byte) 0x03) && Objects.equals(bytes[3], (byte) 0x04) && Objects.equals(bytes[30], (byte) 0x6d) && Objects.equals(bytes[31], (byte) 0x69) && Objects.equals(bytes[32], (byte) 0x6d) && Objects.equals(bytes[33], (byte) 0x65) && Objects.equals(bytes[34], (byte) 0x74) && Objects.equals(bytes[35], (byte) 0x79) && Objects.equals(bytes[36], (byte) 0x70) && Objects.equals(bytes[37], (byte) 0x65) && Objects.equals(bytes[38], (byte) 0x61) && Objects.equals(bytes[39], (byte) 0x70) && Objects.equals(bytes[40], (byte) 0x70) && Objects.equals(bytes[41], (byte) 0x6c) && Objects.equals(bytes[42], (byte) 0x69) && Objects.equals(bytes[43], (byte) 0x63) && Objects.equals(bytes[44], (byte) 0x61) && Objects.equals(bytes[45], (byte) 0x74) && Objects.equals(bytes[46], (byte) 0x69) && Objects.equals(bytes[47], (byte) 0x6f) && Objects.equals(bytes[48], (byte) 0x6e) && Objects.equals(bytes[49], (byte) 0x2f) && Objects.equals(bytes[50], (byte) 0x65) && Objects.equals(bytes[51], (byte) 0x70) && Objects.equals(bytes[52], (byte) 0x75) && Objects.equals(bytes[53], (byte) 0x62) && Objects.equals(bytes[54], (byte) 0x2b) && Objects.equals(bytes[55], (byte) 0x7a) && Objects.equals(bytes[56], (byte) 0x69) && Objects.equals(bytes[57], (byte) 0x70); } }, ZIP("application/zip", "zip") { @Override public boolean match(final byte[] bytes) { if (bytes.length < 4) { return false; } final boolean flag1 = Objects.equals(bytes[0], (byte) 0x50) && Objects.equals(bytes[1], (byte) 0x4b); final boolean flag2 = Objects.equals(bytes[2], (byte) 0x03) || Objects.equals(bytes[2], (byte) 0x05) || Objects.equals(bytes[2], (byte) 0x07); final boolean flag3 = Objects.equals(bytes[3], (byte) 0x04) || Objects.equals(bytes[3], (byte) 0x06) || Objects.equals(bytes[3], (byte) 0x08); return flag1 && flag2 && flag3; } }, TAR("application/x-tar", "tar") { @Override public boolean match(final byte[] bytes) { return bytes.length > 261 && Objects.equals(bytes[257], (byte) 0x75) && Objects.equals(bytes[258], (byte) 0x73) && Objects.equals(bytes[259], (byte) 0x74) && Objects.equals(bytes[260], (byte) 0x61) && Objects.equals(bytes[261], (byte) 0x72); } }, RAR("application/x-rar-compressed", "rar") { @Override public boolean match(final byte[] bytes) { return bytes.length > 6 && Objects.equals(bytes[0], (byte) 0x52) && Objects.equals(bytes[1], (byte) 0x61) && Objects.equals(bytes[2], (byte) 0x72) && Objects.equals(bytes[3], (byte) 0x21) && Objects.equals(bytes[4], (byte) 0x1a) && Objects.equals(bytes[5], (byte) 0x07) && (Objects.equals(bytes[6], (byte) 0x00) || Objects.equals(bytes[6], (byte) 0x01)); } }, GZ("application/gzip", "gz") { @Override public boolean match(final byte[] bytes) { return bytes.length > 2 && Objects.equals(bytes[0], (byte) 0x1f) && Objects.equals(bytes[1], (byte) 0x8b) && Objects.equals(bytes[2], (byte) 0x08); } }, BZ2("application/x-bzip2", "bz2") { @Override public boolean match(final byte[] bytes) { return bytes.length > 2 && Objects.equals(bytes[0], (byte) 0x42) && Objects.equals(bytes[1], (byte) 0x5a) && Objects.equals(bytes[2], (byte) 0x68); } }, SevenZ("application/x-7z-compressed", "7z") { @Override public boolean match(final byte[] bytes) { return bytes.length > 6 && Objects.equals(bytes[0], (byte) 0x37) && Objects.equals(bytes[1], (byte) 0x7a) && Objects.equals(bytes[2], (byte) 0xbc) && Objects.equals(bytes[3], (byte) 0xaf) && Objects.equals(bytes[4], (byte) 0x27) && Objects.equals(bytes[5], (byte) 0x1c) && Objects.equals(bytes[6], (byte) 0x00); } }, PDF("application/pdf", "pdf") { @Override public boolean match(byte[] bytes) { //去除bom头并且跳过三个字节 if (bytes.length > 3 && Objects.equals(bytes[0], (byte) 0xEF) && Objects.equals(bytes[1], (byte) 0xBB) && Objects.equals(bytes[2], (byte) 0xBF)) { bytes = Arrays.copyOfRange(bytes, 3, bytes.length); } return bytes.length > 3 && Objects.equals(bytes[0], (byte) 0x25) && Objects.equals(bytes[1], (byte) 0x50) && Objects.equals(bytes[2], (byte) 0x44) && Objects.equals(bytes[3], (byte) 0x46); } }, EXE("application/x-msdownload", "exe") { @Override public boolean match(final byte[] bytes) { return bytes.length > 1 && Objects.equals(bytes[0], (byte) 0x4d) && Objects.equals(bytes[1], (byte) 0x5a); } }, SWF("application/x-shockwave-flash", "swf") { @Override public boolean match(final byte[] bytes) { return bytes.length > 2 && (Objects.equals(bytes[0], 0x43) || Objects.equals(bytes[0], (byte) 0x46)) && Objects.equals(bytes[1], (byte) 0x57) && Objects.equals(bytes[2], (byte) 0x53); } }, RTF("application/rtf", "rtf") { @Override public boolean match(final byte[] bytes) { return bytes.length > 4 && Objects.equals(bytes[0], (byte) 0x7b) && Objects.equals(bytes[1], (byte) 0x5c) && Objects.equals(bytes[2], (byte) 0x72) && Objects.equals(bytes[3], (byte) 0x74) && Objects.equals(bytes[4], (byte) 0x66); } }, NES("application/x-nintendo-nes-rom", "nes") { @Override public boolean match(final byte[] bytes) { return bytes.length > 3 && Objects.equals(bytes[0], (byte) 0x4e) && Objects.equals(bytes[1], (byte) 0x45) && Objects.equals(bytes[2], (byte) 0x53) && Objects.equals(bytes[3], (byte) 0x1a); } }, CRX("application/x-google-chrome-extension", "crx") { @Override public boolean match(final byte[] bytes) { return bytes.length > 3 && Objects.equals(bytes[0], (byte) 0x43) && Objects.equals(bytes[1], (byte) 0x72) && Objects.equals(bytes[2], (byte) 0x32) && Objects.equals(bytes[3], (byte) 0x34); } }, CAB("application/vnd.ms-cab-compressed", "cab") { @Override public boolean match(final byte[] bytes) { if (bytes.length < 4) { return false; } final boolean flag1 = Objects.equals(bytes[0], (byte) 0x4d) && Objects.equals(bytes[1], (byte) 0x53) && Objects.equals(bytes[2], (byte) 0x43) && Objects.equals(bytes[3], (byte) 0x46); final boolean flag2 = Objects.equals(bytes[0], (byte) 0x49) && Objects.equals(bytes[1], (byte) 0x53) && Objects.equals(bytes[2], (byte) 0x63) && Objects.equals(bytes[3], (byte) 0x28); return flag1 || flag2; } }, PS("application/postscript", "ps") { @Override public boolean match(final byte[] bytes) { return bytes.length > 1 && Objects.equals(bytes[0], (byte) 0x25) && Objects.equals(bytes[1], (byte) 0x21); } }, XZ("application/x-xz", "xz") { @Override public boolean match(final byte[] bytes) { return bytes.length > 5 && Objects.equals(bytes[0], (byte) 0xFD) && Objects.equals(bytes[1], (byte) 0x37) && Objects.equals(bytes[2], (byte) 0x7A) && Objects.equals(bytes[3], (byte) 0x58) && Objects.equals(bytes[4], (byte) 0x5A) && Objects.equals(bytes[5], (byte) 0x00); } }, SQLITE("application/x-sqlite3", "sqlite") { @Override public boolean match(final byte[] bytes) { return bytes.length > 15 && Objects.equals(bytes[0], (byte) 0x53) && Objects.equals(bytes[1], (byte) 0x51) && Objects.equals(bytes[2], (byte) 0x4c) && Objects.equals(bytes[3], (byte) 0x69) && Objects.equals(bytes[4], (byte) 0x74) && Objects.equals(bytes[5], (byte) 0x65) && Objects.equals(bytes[6], (byte) 0x20) && Objects.equals(bytes[7], (byte) 0x66) && Objects.equals(bytes[8], (byte) 0x6f) && Objects.equals(bytes[9], (byte) 0x72) && Objects.equals(bytes[10], (byte) 0x6d) && Objects.equals(bytes[11], (byte) 0x61) && Objects.equals(bytes[12], (byte) 0x74) && Objects.equals(bytes[13], (byte) 0x20) && Objects.equals(bytes[14], (byte) 0x33) && Objects.equals(bytes[15], (byte) 0x00); } }, DEB("application/x-deb", "deb") { @Override public boolean match(final byte[] bytes) { return bytes.length > 20 && Objects.equals(bytes[0], (byte) 0x21) && Objects.equals(bytes[1], (byte) 0x3c) && Objects.equals(bytes[2], (byte) 0x61) && Objects.equals(bytes[3], (byte) 0x72) && Objects.equals(bytes[4], (byte) 0x63) && Objects.equals(bytes[5], (byte) 0x68) && Objects.equals(bytes[6], (byte) 0x3e) && Objects.equals(bytes[7], (byte) 0x0a) && Objects.equals(bytes[8], (byte) 0x64) && Objects.equals(bytes[9], (byte) 0x65) && Objects.equals(bytes[10], (byte) 0x62) && Objects.equals(bytes[11], (byte) 0x69) && Objects.equals(bytes[12], (byte) 0x61) && Objects.equals(bytes[13], (byte) 0x6e) && Objects.equals(bytes[14], (byte) 0x2d) && Objects.equals(bytes[15], (byte) 0x62) && Objects.equals(bytes[16], (byte) 0x69) && Objects.equals(bytes[17], (byte) 0x6e) && Objects.equals(bytes[18], (byte) 0x61) && Objects.equals(bytes[19], (byte) 0x72) && Objects.equals(bytes[20], (byte) 0x79); } }, AR("application/x-unix-archive", "ar") { @Override public boolean match(final byte[] bytes) { return bytes.length > 6 && Objects.equals(bytes[0], (byte) 0x21) && Objects.equals(bytes[1], (byte) 0x3c) && Objects.equals(bytes[2], (byte) 0x61) && Objects.equals(bytes[3], (byte) 0x72) && Objects.equals(bytes[4], (byte) 0x63) && Objects.equals(bytes[5], (byte) 0x68) && Objects.equals(bytes[6], (byte) 0x3e); } }, LZOP("application/x-lzop", "lzo") { @Override public boolean match(final byte[] bytes) { return bytes.length > 7 && Objects.equals(bytes[0], (byte) 0x89) && Objects.equals(bytes[1], (byte) 0x4c) && Objects.equals(bytes[2], (byte) 0x5a) && Objects.equals(bytes[3], (byte) 0x4f) && Objects.equals(bytes[4], (byte) 0x00) && Objects.equals(bytes[5], (byte) 0x0d) && Objects.equals(bytes[6], (byte) 0x0a) && Objects.equals(bytes[7], (byte) 0x1a); } }, LZ("application/x-lzip", "lz") { @Override public boolean match(final byte[] bytes) { return bytes.length > 3 && Objects.equals(bytes[0], (byte) 0x4c) && Objects.equals(bytes[1], (byte) 0x5a) && Objects.equals(bytes[2], (byte) 0x49) && Objects.equals(bytes[3], (byte) 0x50); } }, ELF("application/x-executable", "elf") { @Override public boolean match(final byte[] bytes) { return bytes.length > 52 && Objects.equals(bytes[0], (byte) 0x7f) && Objects.equals(bytes[1], (byte) 0x45) && Objects.equals(bytes[2], (byte) 0x4c) && Objects.equals(bytes[3], (byte) 0x46); } }, LZ4("application/x-lz4", "lz4") { @Override public boolean match(final byte[] bytes) { return bytes.length > 4 && Objects.equals(bytes[0], (byte) 0x04) && Objects.equals(bytes[1], (byte) 0x22) && Objects.equals(bytes[2], (byte) 0x4d) && Objects.equals(bytes[3], (byte) 0x18); } }, //https://github.com/madler/brotli/blob/master/br-format-v3.txt,brotli 没有固定的file magic number,所以此处只是参考 BR("application/x-brotli", "br") { @Override public boolean match(final byte[] bytes) { return bytes.length > 3 && Objects.equals(bytes[0], (byte) 0xce) && Objects.equals(bytes[1], (byte) 0xb2) && Objects.equals(bytes[2], (byte) 0xcf) && Objects.equals(bytes[3], (byte) 0x81); } }, DCM("application/x-dicom", "dcm") { @Override public boolean match(final byte[] bytes) { return bytes.length > 128 && Objects.equals(bytes[128], (byte) 0x44) && Objects.equals(bytes[129], (byte) 0x49) && Objects.equals(bytes[130], (byte) 0x43) && Objects.equals(bytes[131], (byte) 0x4d); } }, RPM("application/x-rpm", "rpm") { @Override public boolean match(final byte[] bytes) { return bytes.length > 4 && Objects.equals(bytes[0], (byte) 0xed) && Objects.equals(bytes[1], (byte) 0xab) && Objects.equals(bytes[2], (byte) 0xee) && Objects.equals(bytes[3], (byte) 0xdb); } }, ZSTD("application/x-zstd", "zst") { @Override public boolean match(final byte[] bytes) { final int length = bytes.length; if (length < 5) { return false; } final byte[] buf1 = new byte[]{(byte) 0x22, (byte) 0x23, (byte) 0x24, (byte) 0x25, (byte) 0x26, (byte) 0x27, (byte) 0x28}; final boolean flag1 = ArrayUtil.contains(buf1, bytes[0]) && Objects.equals(bytes[1], (byte) 0xb5) && Objects.equals(bytes[2], (byte) 0x2f) && Objects.equals(bytes[3], (byte) 0xfd); if (flag1) { return true; } if ((bytes[0] & 0xF0) == 0x50) { return bytes[1] == 0x2A && bytes[2] == 0x4D && bytes[3] == 0x18; } return false; } }, //archive end------------------------------------------------------------ //video start------------------------------------------------------------ MP4("video/mp4", "mp4") { @Override public boolean match(final byte[] bytes) { if (bytes.length < 13) { return false; } final boolean flag1 = Objects.equals(bytes[4], (byte) 0x66) && Objects.equals(bytes[5], (byte) 0x74) && Objects.equals(bytes[6], (byte) 0x79) && Objects.equals(bytes[7], (byte) 0x70) && Objects.equals(bytes[8], (byte) 0x4d) && Objects.equals(bytes[9], (byte) 0x53) && Objects.equals(bytes[10], (byte) 0x4e) && Objects.equals(bytes[11], (byte) 0x56); final boolean flag2 = Objects.equals(bytes[4], (byte) 0x66) && Objects.equals(bytes[5], (byte) 0x74) && Objects.equals(bytes[6], (byte) 0x79) && Objects.equals(bytes[7], (byte) 0x70) && Objects.equals(bytes[8], (byte) 0x69) && Objects.equals(bytes[9], (byte) 0x73) && Objects.equals(bytes[10], (byte) 0x6f) && Objects.equals(bytes[11], (byte) 0x6d); return flag1 || flag2; } }, AVI("video/x-msvideo", "avi") { @Override public boolean match(final byte[] bytes) { return bytes.length > 11 && Objects.equals(bytes[0], (byte) 0x52) && Objects.equals(bytes[1], (byte) 0x49) && Objects.equals(bytes[2], (byte) 0x46) && Objects.equals(bytes[3], (byte) 0x46) && Objects.equals(bytes[8], (byte) 0x41) && Objects.equals(bytes[9], (byte) 0x56) && Objects.equals(bytes[10], (byte) 0x49) && Objects.equals(bytes[11], (byte) 0x20); } }, WMV("video/x-ms-wmv", "wmv") { @Override public boolean match(final byte[] bytes) { return bytes.length > 9 && Objects.equals(bytes[0], (byte) 0x30) && Objects.equals(bytes[1], (byte) 0x26) && Objects.equals(bytes[2], (byte) 0xb2) && Objects.equals(bytes[3], (byte) 0x75) && Objects.equals(bytes[4], (byte) 0x8e) && Objects.equals(bytes[5], (byte) 0x66) && Objects.equals(bytes[6], (byte) 0xcf) && Objects.equals(bytes[7], (byte) 0x11) && Objects.equals(bytes[8], (byte) 0xa6) && Objects.equals(bytes[9], (byte) 0xd9); } }, M4V("video/x-m4v", "m4v") { @Override public boolean match(final byte[] bytes) { if (bytes.length < 12) { return false; } final boolean flag1 = Objects.equals(bytes[4], (byte) 0x66) && Objects.equals(bytes[5], (byte) 0x74) && Objects.equals(bytes[6], (byte) 0x79) && Objects.equals(bytes[7], (byte) 0x70) && Objects.equals(bytes[8], (byte) 0x4d) && Objects.equals(bytes[9], (byte) 0x34) && Objects.equals(bytes[10], (byte) 0x56) && Objects.equals(bytes[11], (byte) 0x20); final boolean flag2 = Objects.equals(bytes[4], (byte) 0x66) && Objects.equals(bytes[5], (byte) 0x74) && Objects.equals(bytes[6], (byte) 0x79) && Objects.equals(bytes[7], (byte) 0x70) && Objects.equals(bytes[8], (byte) 0x6d) && Objects.equals(bytes[9], (byte) 0x70) && Objects.equals(bytes[10], (byte) 0x34) && Objects.equals(bytes[11], (byte) 0x32); return flag1 || flag2; } }, FLV("video/x-flv", "flv") { @Override public boolean match(final byte[] bytes) { return bytes.length > 3 && Objects.equals(bytes[0], (byte) 0x46) && Objects.equals(bytes[1], (byte) 0x4c) && Objects.equals(bytes[2], (byte) 0x56) && Objects.equals(bytes[3], (byte) 0x01); } }, MKV("video/x-matroska", "mkv") { @Override public boolean match(final byte[] bytes) { //0x42 0x82 0x88 0x6d 0x61 0x74 0x72 0x6f 0x73 0x6b 0x61 final boolean flag1 = bytes.length > 11 && Objects.equals(bytes[0], (byte) 0x1a) && Objects.equals(bytes[1], (byte) 0x45) && Objects.equals(bytes[2], (byte) 0xdf) && Objects.equals(bytes[3], (byte) 0xa3); if (flag1) { //此处需要判断是否是'\x42\x82\x88matroska',算法类似kmp判断 final byte[] bytes1 = {(byte) 0x42, (byte) 0x82, (byte) 0x88, (byte) 0x6d, (byte) 0x61, (byte) 0x74, (byte) 0x72, (byte) 0x6f, (byte) 0x73, (byte) 0x6b, (byte) 0x61}; final int index = FileMagicNumber.indexOf(bytes, bytes1); return index > 0; } return false; } }, WEBM("video/webm", "webm") { @Override public boolean match(final byte[] bytes) { final boolean flag1 = bytes.length > 8 && Objects.equals(bytes[0], (byte) 0x1a) && Objects.equals(bytes[1], (byte) 0x45) && Objects.equals(bytes[2], (byte) 0xdf) && Objects.equals(bytes[3], (byte) 0xa3); if (flag1) { //此处需要判断是否是'\x42\x82\x88webm',算法类似kmp判断 final byte[] bytes1 = {(byte) 0x42, (byte) 0x82, (byte) 0x88, (byte) 0x77, (byte) 0x65, (byte) 0x62, (byte) 0x6d}; final int index = FileMagicNumber.indexOf(bytes, bytes1); return index > 0; } return false; } }, //此文件签名非常复杂,只判断常见的几种 MOV("video/quicktime", "mov") { @Override public boolean match(final byte[] bytes) { if (bytes.length < 12) { return false; } final boolean flag1 = Objects.equals(bytes[4], (byte) 0x66) && Objects.equals(bytes[5], (byte) 0x74) && Objects.equals(bytes[6], (byte) 0x79) && Objects.equals(bytes[7], (byte) 0x70) && Objects.equals(bytes[8], (byte) 0x71) && Objects.equals(bytes[9], (byte) 0x74) && Objects.equals(bytes[10], (byte) 0x20) && Objects.equals(bytes[11], (byte) 0x20); final boolean flag2 = Objects.equals(bytes[4], (byte) 0x6D) && Objects.equals(bytes[5], (byte) 0x6F) && Objects.equals(bytes[6], (byte) 0x6F) && Objects.equals(bytes[7], (byte) 0x76); final boolean flag3 = Objects.equals(bytes[4], (byte) 0x66) && Objects.equals(bytes[5], (byte) 0x72) && Objects.equals(bytes[6], (byte) 0x65) && Objects.equals(bytes[7], (byte) 0x65); final boolean flag4 = Objects.equals(bytes[4], (byte) 0x6D) && Objects.equals(bytes[5], (byte) 0x64) && Objects.equals(bytes[6], (byte) 0x61) && Objects.equals(bytes[7], (byte) 0x74); final boolean flag5 = Objects.equals(bytes[4], (byte) 0x77) && Objects.equals(bytes[5], (byte) 0x69) && Objects.equals(bytes[6], (byte) 0x64) && Objects.equals(bytes[7], (byte) 0x65); final boolean flag6 = Objects.equals(bytes[4], (byte) 0x70) && Objects.equals(bytes[5], (byte) 0x6E) && Objects.equals(bytes[6], (byte) 0x6F) && Objects.equals(bytes[7], (byte) 0x74); final boolean flag7 = Objects.equals(bytes[4], (byte) 0x73) && Objects.equals(bytes[5], (byte) 0x6B) && Objects.equals(bytes[6], (byte) 0x69) && Objects.equals(bytes[7], (byte) 0x70); return flag1 || flag2 || flag3 || flag4 || flag5 || flag6 || flag7; } }, MPEG("video/mpeg", "mpg") { @Override public boolean match(final byte[] bytes) { return bytes.length > 3 && Objects.equals(bytes[0], (byte) 0x00) && Objects.equals(bytes[1], (byte) 0x00) && Objects.equals(bytes[2], (byte) 0x01) && (bytes[3] >= (byte) 0xb0 && bytes[3] <= (byte) 0xbf); } }, RMVB("video/vnd.rn-realvideo", "rmvb") { @Override public boolean match(final byte[] bytes) { return bytes.length > 4 && Objects.equals(bytes[0], (byte) 0x2E) && Objects.equals(bytes[1], (byte) 0x52) && Objects.equals(bytes[2], (byte) 0x4D) && Objects.equals(bytes[3], (byte) 0x46); } }, M3GP("video/3gpp", "3gp") { @Override public boolean match(final byte[] bytes) { return bytes.length > 10 && Objects.equals(bytes[4], (byte) 0x66) && Objects.equals(bytes[5], (byte) 0x74) && Objects.equals(bytes[6], (byte) 0x79) && Objects.equals(bytes[7], (byte) 0x70) && Objects.equals(bytes[8], (byte) 0x33) && Objects.equals(bytes[9], (byte) 0x67) && Objects.equals(bytes[10], (byte) 0x70); } }, //video end --------------------------------------------------------------- //document start ---------------------------------------------------------- DOC("application/msword", "doc") { @Override public boolean match(final byte[] bytes) { final byte[] byte1 = new byte[]{(byte) 0xd0, (byte) 0xcf, (byte) 0x11, (byte) 0xe0, (byte) 0xa1, (byte) 0xb1, (byte) 0x1a, (byte) 0xe1}; final boolean flag1 = bytes.length > 515 && Arrays.equals(Arrays.copyOfRange(bytes, 0, 8), byte1); if (flag1) { final byte[] byte2 = new byte[]{(byte) 0xec, (byte) 0xa5, (byte) 0xc1, (byte) 0x00}; final boolean flag2 = Arrays.equals(Arrays.copyOfRange(bytes, 512, 516), byte2); final byte[] byte3 = new byte[]{(byte) 0x00, (byte) 0x0a, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x4d, (byte) 0x53, (byte) 0x57, (byte) 0x6f, (byte) 0x72, (byte) 0x64 , (byte) 0x44, (byte) 0x6f, (byte) 0x63, (byte) 0x00, (byte) 0x10, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x57, (byte) 0x6f, (byte) 0x72, (byte) 0x64, (byte) 0x2e, (byte) 0x44, (byte) 0x6f, (byte) 0x63, (byte) 0x75, (byte) 0x6d, (byte) 0x65, (byte) 0x6e, (byte) 0x74, (byte) 0x2e, (byte) 0x38, (byte) 0x00, (byte) 0xf4, (byte) 0x39, (byte) 0xb2, (byte) 0x71}; final byte[] range = Arrays.copyOfRange(bytes, 2075, 2142); final boolean flag3 = bytes.length > 2142 && FileMagicNumber.indexOf(range, byte3) > 0; return flag2 || flag3; } return false; } }, XLS("application/vnd.ms-excel", "xls") { @Override public boolean match(final byte[] bytes) { final byte[] byte1 = new byte[]{(byte) 0xd0, (byte) 0xcf, (byte) 0x11, (byte) 0xe0, (byte) 0xa1, (byte) 0xb1, (byte) 0x1a, (byte) 0xe1}; final boolean flag1 = bytes.length > 520 && Arrays.equals(Arrays.copyOfRange(bytes, 0, 8), byte1); if (flag1) { final byte[] byte2 = new byte[]{(byte) 0xfd, (byte) 0xff, (byte) 0xff, (byte) 0xff}; final boolean flag2 = Arrays.equals(Arrays.copyOfRange(bytes, 512, 516), byte2) && (bytes[518] == 0x00 || bytes[518] == 0x02); final byte[] byte3 = new byte[]{(byte) 0x09, (byte) 0x08, (byte) 0x10, (byte) 0x00, (byte) 0x00, (byte) 0x06, (byte) 0x05, (byte) 0x00}; final boolean flag3 = Arrays.equals(Arrays.copyOfRange(bytes, 512, 520), byte3); final byte[] byte4 = new byte[]{(byte) 0xe2, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x5c, (byte) 0x00, (byte) 0x70, (byte) 0x00, (byte) 0x04, (byte) 0x00, (byte) 0x00, (byte) 0x43, (byte) 0x61, (byte) 0x6c, (byte) 0x63}; final boolean flag4 = bytes.length > 2095 && Arrays.equals(Arrays.copyOfRange(bytes, 1568, 2095), byte4); return flag2 || flag3 || flag4; } return false; } }, PPT("application/vnd.ms-powerpoint", "ppt") { @Override public boolean match(final byte[] bytes) { final byte[] byte1 = new byte[]{(byte) 0xd0, (byte) 0xcf, (byte) 0x11, (byte) 0xe0, (byte) 0xa1, (byte) 0xb1, (byte) 0x1a, (byte) 0xe1}; final boolean flag1 = bytes.length > 524 && Arrays.equals(Arrays.copyOfRange(bytes, 0, 8), byte1); if (flag1) { final byte[] byte2 = new byte[]{(byte) 0xa0, (byte) 0x46, (byte) 0x1d, (byte) 0xf0}; final byte[] byteRange = Arrays.copyOfRange(bytes, 512, 516); final boolean flag2 = Arrays.equals(byteRange, byte2); final byte[] byte3 = new byte[]{(byte) 0x00, (byte) 0x6e, (byte) 0x1e, (byte) 0xf0}; final boolean flag3 = Arrays.equals(byteRange, byte3); final byte[] byte4 = new byte[]{(byte) 0x0f, (byte) 0x00, (byte) 0xe8, (byte) 0x03}; final boolean flag4 = Arrays.equals(byteRange, byte4); final byte[] byte5 = new byte[]{(byte) 0xfd, (byte) 0xff, (byte) 0xff, (byte) 0xff}; final boolean flag5 = Arrays.equals(byteRange, byte5) && bytes[522] == 0x00 && bytes[523] == 0x00; final byte[] byte6 = new byte[]{(byte) 0x00, (byte) 0xb9, (byte) 0x29, (byte) 0xe8, (byte) 0x11, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x4d, (byte) 0x53, (byte) 0x20, (byte) 0x50, (byte) 0x6f, (byte) 0x77, (byte) 0x65, (byte) 0x72, (byte) 0x50, (byte) 0x6f, (byte) 0x69, (byte) 0x6e, (byte) 0x74, (byte) 0x20, (byte) 0x39, (byte) 0x37}; final boolean flag6 = bytes.length > 2096 && Arrays.equals(Arrays.copyOfRange(bytes, 2072, 2096), byte6); return flag2 || flag3 || flag4 || flag5 || flag6; } return false; } }, DOCX("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "docx") { @Override public boolean match(final byte[] bytes) { return Objects.equals(FileMagicNumber.matchDocument(bytes), DOCX); } }, PPTX("application/vnd.openxmlformats-officedocument.presentationml.presentation", "pptx") { @Override public boolean match(final byte[] bytes) { return Objects.equals(FileMagicNumber.matchDocument(bytes), PPTX); } }, XLSX("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx") { @Override public boolean match(final byte[] bytes) { return Objects.equals(FileMagicNumber.matchDocument(bytes), XLSX); } }, //document end ------------------------------------------------------------ //other start ------------------------------------------------------------- WASM("application/wasm", "wasm") { @Override public boolean match(final byte[] bytes) { return bytes.length > 7 && Objects.equals(bytes[0], (byte) 0x00) && Objects.equals(bytes[1], (byte) 0x61) && Objects.equals(bytes[2], (byte) 0x73) && Objects.equals(bytes[3], (byte) 0x6D) && Objects.equals(bytes[4], (byte) 0x01) && Objects.equals(bytes[5], (byte) 0x00) && Objects.equals(bytes[6], (byte) 0x00) && Objects.equals(bytes[7], (byte) 0x00); } }, // https://source.android.com/devices/tech/dalvik/dex-format#dex-file-magic DEX("application/vnd.android.dex", "dex") { @Override public boolean match(final byte[] bytes) { return bytes.length > 36 && Objects.equals(bytes[0], (byte) 0x64) && Objects.equals(bytes[1], (byte) 0x65) && Objects.equals(bytes[2], (byte) 0x78) && Objects.equals(bytes[3], (byte) 0x0A) && Objects.equals(bytes[36], (byte) 0x70); } }, DEY("application/vnd.android.dey", "dey") { @Override public boolean match(final byte[] bytes) { return bytes.length > 100 && Objects.equals(bytes[0], (byte) 0x64) && Objects.equals(bytes[1], (byte) 0x65) && Objects.equals(bytes[2], (byte) 0x79) && Objects.equals(bytes[3], (byte) 0x0A) && DEX.match(Arrays.copyOfRange(bytes, 40, 100)); } }, EML("message/rfc822", "eml") { @Override public boolean match(final byte[] bytes) { if (bytes.length < 8) { return false; } final byte[] byte1 = new byte[]{(byte) 0x46, (byte) 0x72, (byte) 0x6F, (byte) 0x6D, (byte) 0x20, (byte) 0x20, (byte) 0x20}; final byte[] byte2 = new byte[]{(byte) 0x46, (byte) 0x72, (byte) 0x6F, (byte) 0x6D, (byte) 0x20, (byte) 0x3F, (byte) 0x3F, (byte) 0x3F}; final byte[] byte3 = new byte[]{(byte) 0x46, (byte) 0x72, (byte) 0x6F, (byte) 0x6D, (byte) 0x3A, (byte) 0x20}; final byte[] byte4 = new byte[]{(byte) 0x52, (byte) 0x65, (byte) 0x74, (byte) 0x75, (byte) 0x72, (byte) 0x6E, (byte) 0x2D, (byte) 0x50, (byte) 0x61, (byte) 0x74, (byte) 0x68, (byte) 0x3A, (byte) 0x20}; return Arrays.equals(Arrays.copyOfRange(bytes, 0, 7), byte1) || Arrays.equals(Arrays.copyOfRange(bytes, 0, 8), byte2) || Arrays.equals(Arrays.copyOfRange(bytes, 0, 6), byte3) || bytes.length > 13 && Arrays.equals(Arrays.copyOfRange(bytes, 0, 13), byte4); } }, MDB("application/vnd.ms-access", "mdb") { @Override public boolean match(final byte[] bytes) { final byte[] byte1 = new byte[]{(byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x53, (byte) 0x74, (byte) 0x61, (byte) 0x6E, (byte) 0x64, (byte) 0x61, (byte) 0x72, (byte) 0x64, (byte) 0x20, (byte) 0x4A, (byte) 0x65, (byte) 0x74, (byte) 0x20, (byte) 0x44, (byte) 0x42}; return bytes.length > 18 && Arrays.equals(Arrays.copyOfRange(bytes, 0, 18), byte1); } }, //CHM 49 54 53 46 CHM("application/vnd.ms-htmlhelp", "chm") { @Override public boolean match(final byte[] bytes) { final byte[] byte1 = new byte[]{(byte) 0x49, (byte) 0x54, (byte) 0x53, (byte) 0x46}; return bytes.length > 4 && Arrays.equals(Arrays.copyOfRange(bytes, 0, 4), byte1); } }, //class CA FE BA BE CLASS("application/java-vm", "class") { @Override public boolean match(final byte[] bytes) { final byte[] byte1 = new byte[]{(byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE}; return bytes.length > 4 && Arrays.equals(Arrays.copyOfRange(bytes, 0, 4), byte1); } }, //torrent 64 38 3A 61 6E 6E 6F 75 6E 63 65 TORRENT("application/x-bittorrent", "torrent") { @Override public boolean match(final byte[] bytes) { final byte[] byte1 = new byte[]{(byte) 0x64, (byte) 0x38, (byte) 0x3A, (byte) 0x61, (byte) 0x6E, (byte) 0x6E, (byte) 0x6F, (byte) 0x75, (byte) 0x6E, (byte) 0x63, (byte) 0x65}; return bytes.length > 11 && Arrays.equals(Arrays.copyOfRange(bytes, 0, 11), byte1); } }, WPD("application/vnd.wordperfect", "wpd") { @Override public boolean match(final byte[] bytes) { final byte[] byte1 = new byte[]{(byte) 0xFF, (byte) 0x57, (byte) 0x50, (byte) 0x43}; return bytes.length > 4 && Arrays.equals(Arrays.copyOfRange(bytes, 0, 4), byte1); } }, DBX("", "dbx") { @Override public boolean match(final byte[] bytes) { final byte[] byte1 = new byte[]{(byte) 0xCF, (byte) 0xAD, (byte) 0x12, (byte) 0xFE}; return bytes.length > 4 && Arrays.equals(Arrays.copyOfRange(bytes, 0, 4), byte1); } }, PST("application/vnd.ms-outlook-pst", "pst") { @Override public boolean match(final byte[] bytes) { final byte[] byte1 = new byte[]{(byte) 0x21, (byte) 0x42, (byte) 0x44, (byte) 0x4E}; return bytes.length > 4 && Arrays.equals(Arrays.copyOfRange(bytes, 0, 4), byte1); } }, RAM("audio/x-pn-realaudio", "ram") { @Override public boolean match(final byte[] bytes) { final byte[] byte1 = new byte[]{(byte) 0x2E, (byte) 0x72, (byte) 0x61, (byte) 0xFD, (byte) 0x00}; return bytes.length > 5 && Arrays.equals(Arrays.copyOfRange(bytes, 0, 5), byte1); } } //other end --------------------------------------------------------------- ; private final String mimeType; private final String extension; FileMagicNumber(final String mimeType, final String extension) { this.mimeType = mimeType; this.extension = extension; } public static FileMagicNumber getMagicNumber(final byte[] bytes) { final FileMagicNumber number = Arrays.stream(values()) .filter(fileMagicNumber -> fileMagicNumber.match(bytes)) .findFirst() .orElse(UNKNOWN); if (number.equals(FileMagicNumber.ZIP)) { final FileMagicNumber fn = FileMagicNumber.matchDocument(bytes); return fn == UNKNOWN ? ZIP : fn; } return number; } public String getMimeType() { return mimeType; } public String getExtension() { return extension; } private static int indexOf(final byte[] array, final byte[] target) { if (array == null || target == null || array.length < target.length) { return -1; } if (target.length == 0) { return 0; } else { label1: for (int i = 0; i < array.length - target.length + 1; ++i) { for (int j = 0; j < target.length; ++j) { if (array[i + j] != target[j]) { continue label1; } } return i; } return -1; } } //处理 Open XML 类型的文件 private static boolean compareBytes(final byte[] buf, final byte[] slice, final int startOffset) { final int sl = slice.length; if (startOffset + sl > buf.length) { return false; } final byte[] sub = Arrays.copyOfRange(buf, startOffset, startOffset + sl); return Arrays.equals(sub, slice); } private static FileMagicNumber matchOpenXmlMime(final byte[] bytes, final int offset) { final byte[] word = new byte[]{'w', 'o', 'r', 'd', '/'}; final byte[] ppt = new byte[]{'p', 'p', 't', '/'}; final byte[] xl = new byte[]{'x', 'l', '/'}; if (FileMagicNumber.compareBytes(bytes, word, offset)) { return FileMagicNumber.DOCX; } if (FileMagicNumber.compareBytes(bytes, ppt, offset)) { return FileMagicNumber.PPTX; } if (FileMagicNumber.compareBytes(bytes, xl, offset)) { return FileMagicNumber.XLSX; } return FileMagicNumber.UNKNOWN; } private static FileMagicNumber matchDocument(final byte[] bytes) { final FileMagicNumber fileMagicNumber = FileMagicNumber.matchOpenXmlMime(bytes, (byte) 0x1e); if (false == fileMagicNumber.equals(UNKNOWN)) { return fileMagicNumber; } final byte[] bytes1 = new byte[]{0x5B, 0x43, 0x6F, 0x6E, 0x74, 0x65, 0x6E, 0x74, 0x5F, 0x54, 0x79, 0x70, 0x65, 0x73, 0x5D, 0x2E, 0x78, 0x6D, 0x6C}; final byte[] bytes2 = new byte[]{0x5F, 0x72, 0x65, 0x6C, 0x73, 0x2F, 0x2E, 0x72, 0x65, 0x6C, 0x73}; final byte[] bytes3 = new byte[]{0x64, 0x6F, 0x63, 0x50, 0x72, 0x6F, 0x70, 0x73}; final boolean flag1 = FileMagicNumber.compareBytes(bytes, bytes1, (byte) 0x1e); final boolean flag2 = FileMagicNumber.compareBytes(bytes, bytes2, (byte) 0x1e); final boolean flag3 = FileMagicNumber.compareBytes(bytes, bytes3, (byte) 0x1e); if (false == (flag1 || flag2 || flag3)) { return UNKNOWN; } int index = 0; for (int i = 0; i < 4; i++) { index = searchSignature(bytes, index + 4, 6000); if (index == -1) { continue; } final FileMagicNumber fn = FileMagicNumber.matchOpenXmlMime(bytes, index + 30); if (false == fn.equals(UNKNOWN)) { return fn; } } return UNKNOWN; } private static int searchSignature(final byte[] bytes, final int start, final int rangeNum) { final byte[] signature = new byte[]{0x50, 0x4B, 0x03, 0x04}; final int length = bytes.length; int end = start + rangeNum; if (end > length) { end = length; } final int index = FileMagicNumber.indexOf(Arrays.copyOfRange(bytes, start, end), signature); return (index == -1) ? -1 : (start + index); } public abstract boolean match(byte[] bytes); }
dromara/hutool
hutool-core/src/main/java/cn/hutool/core/io/FileMagicNumber.java
41,648
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.ui.Components; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothProfile; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ImageFormat; import android.graphics.Outline; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.RectF; import android.graphics.SurfaceTexture; import android.graphics.drawable.AnimatedVectorDrawable; import android.hardware.Camera; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioRecord; import android.media.AudioTimestamp; import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaFormat; import android.media.MediaRecorder; import android.net.Uri; import android.opengl.EGL14; import android.opengl.EGLExt; import android.opengl.GLES11Ext; import android.opengl.GLES20; import android.opengl.GLUtils; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import android.view.Gravity; import android.view.HapticFeedbackConstants; import android.view.MotionEvent; import android.view.Surface; import android.view.TextureView; import android.view.View; import android.view.ViewGroup; import android.view.ViewOutlineProvider; import android.view.WindowManager; import android.view.animation.DecelerateInterpolator; import android.widget.FrameLayout; import android.widget.ImageView; import androidx.annotation.RequiresApi; import androidx.core.content.ContextCompat; import androidx.core.graphics.ColorUtils; import com.google.android.exoplayer2.ExoPlayer; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.AutoDeleteMediaTask; import org.telegram.messenger.BuildVars; import org.telegram.messenger.DispatchQueue; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.ImageReceiver; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MediaController; import org.telegram.messenger.MessagesController; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.SharedConfig; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; import org.telegram.messenger.VideoEditedInfo; import org.telegram.messenger.camera.CameraController; import org.telegram.messenger.camera.CameraInfo; import org.telegram.messenger.camera.CameraSession; import org.telegram.messenger.camera.Size; import org.telegram.messenger.video.MP4Builder; import org.telegram.messenger.video.Mp4Movie; import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ChatActivity; import org.telegram.ui.Components.voip.CellFlickerDrawable; import java.io.File; import java.io.FileOutputStream; import java.lang.ref.WeakReference; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.CountDownLatch; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL; @TargetApi(18) public class InstantCameraView extends FrameLayout implements NotificationCenter.NotificationCenterDelegate { private int currentAccount = UserConfig.selectedAccount; private InstantViewCameraContainer cameraContainer; private ChatActivity baseFragment; private Paint paint; private RectF rect; private ImageView switchCameraButton; AnimatedVectorDrawable switchCameraDrawable = null; private ImageView muteImageView; private float progress; private CameraInfo selectedCamera; private boolean isFrontface = true; private volatile boolean cameraReady; private AnimatorSet muteAnimation; private TLRPC.InputFile file; private TLRPC.InputEncryptedFile encryptedFile; private byte[] key; private byte[] iv; private long size; private boolean isSecretChat; private VideoEditedInfo videoEditedInfo; private VideoPlayer videoPlayer; private Bitmap lastBitmap; private int recordingGuid; private int[] position = new int[2]; private int[] cameraTexture = new int[1]; private int[] oldCameraTexture = new int[1]; private float cameraTextureAlpha = 1.0f; private AnimatorSet animatorSet; private boolean deviceHasGoodCamera; private boolean requestingPermissions; private File cameraFile; private long recordStartTime; private boolean recording; private long recordedTime; private boolean cancelled; private CameraGLThread cameraThread; private Size previewSize; private Size pictureSize; private Size aspectRatio = SharedConfig.roundCamera16to9 ? new Size(16, 9) : new Size(4, 3); private TextureView textureView; private BackupImageView textureOverlayView; private CameraSession cameraSession; private boolean needDrawFlickerStub; private float panTranslationY; private float animationTranslationY; private float[] mMVPMatrix = new float[16]; private float[] mSTMatrix = new float[16]; private float[] moldSTMatrix = new float[16]; private static final String VERTEX_SHADER = "uniform mat4 uMVPMatrix;\n" + "uniform mat4 uSTMatrix;\n" + "attribute vec4 aPosition;\n" + "attribute vec4 aTextureCoord;\n" + "varying vec2 vTextureCoord;\n" + "void main() {\n" + " gl_Position = uMVPMatrix * aPosition;\n" + " vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" + "}\n"; private static final String FRAGMENT_SCREEN_SHADER = "#extension GL_OES_EGL_image_external : require\n" + "precision lowp float;\n" + "varying vec2 vTextureCoord;\n" + "uniform samplerExternalOES sTexture;\n" + "void main() {\n" + " gl_FragColor = texture2D(sTexture, vTextureCoord);\n" + "}\n"; private FloatBuffer vertexBuffer; private FloatBuffer textureBuffer; private FloatBuffer oldTextureTextureBuffer; private float scaleX; private float scaleY; private Size oldTexturePreviewSize; private boolean flipAnimationInProgress; private View parentView; public boolean opened; private BlurBehindDrawable blurBehindDrawable; float pinchStartDistance; float pinchScale; boolean isInPinchToZoomTouchMode; boolean maybePinchToZoomTouchMode; private int pointerId1, pointerId2; private int textureViewSize; private boolean isMessageTransition; private boolean updateTextureViewSize; private final Theme.ResourcesProvider resourcesProvider; private final static int audioSampleRate = 48000; private static final int[] ALLOW_BIG_CAMERA_WHITELIST = { 285904780, // XIAOMI (Redmi Note 7) }; @SuppressLint("ClickableViewAccessibility") public InstantCameraView(Context context, ChatActivity parentFragment, Theme.ResourcesProvider resourcesProvider) { super(context); this.resourcesProvider = resourcesProvider; parentView = parentFragment.getFragmentView(); setWillNotDraw(false); baseFragment = parentFragment; recordingGuid = baseFragment.getClassGuid(); isSecretChat = baseFragment.getCurrentEncryptedChat() != null; paint = new Paint(Paint.ANTI_ALIAS_FLAG) { @Override public void setAlpha(int a) { super.setAlpha(a); invalidate(); } }; paint.setStyle(Paint.Style.STROKE); paint.setStrokeCap(Paint.Cap.ROUND); paint.setStrokeWidth(AndroidUtilities.dp(3)); paint.setColor(0xffffffff); rect = new RectF(); if (Build.VERSION.SDK_INT >= 21) { cameraContainer = new InstantViewCameraContainer(context) { @Override public void setScaleX(float scaleX) { super.setScaleX(scaleX); InstantCameraView.this.invalidate(); } @Override public void setAlpha(float alpha) { super.setAlpha(alpha); InstantCameraView.this.invalidate(); } }; cameraContainer.setOutlineProvider(new ViewOutlineProvider() { @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void getOutline(View view, Outline outline) { outline.setOval(0, 0, textureViewSize, textureViewSize); } }); cameraContainer.setClipToOutline(true); cameraContainer.setWillNotDraw(false); } else { final Path path = new Path(); final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(0xff000000); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); cameraContainer = new InstantViewCameraContainer(context) { @Override public void setScaleX(float scaleX) { super.setScaleX(scaleX); InstantCameraView.this.invalidate(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); path.reset(); path.addCircle(w / 2, h / 2, w / 2, Path.Direction.CW); path.toggleInverseFillType(); } @Override protected void dispatchDraw(Canvas canvas) { try { super.dispatchDraw(canvas); canvas.drawPath(path, paint); } catch (Exception ignore) { } } }; cameraContainer.setWillNotDraw(false); cameraContainer.setLayerType(View.LAYER_TYPE_HARDWARE, null); } addView(cameraContainer, new LayoutParams(AndroidUtilities.roundPlayingMessageSize, AndroidUtilities.roundPlayingMessageSize, Gravity.CENTER)); switchCameraButton = new ImageView(context); switchCameraButton.setScaleType(ImageView.ScaleType.CENTER); switchCameraButton.setContentDescription(LocaleController.getString("AccDescrSwitchCamera", R.string.AccDescrSwitchCamera)); addView(switchCameraButton, LayoutHelper.createFrame(62, 62, Gravity.LEFT | Gravity.BOTTOM, 8, 0, 0, 0)); switchCameraButton.setOnClickListener(v -> { if (!cameraReady || cameraSession == null || !cameraSession.isInitied() || cameraThread == null) { return; } switchCamera(); if (switchCameraDrawable != null) { switchCameraDrawable.start(); } flipAnimationInProgress = true; ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1f); valueAnimator.setDuration(300); valueAnimator.setInterpolator(CubicBezierInterpolator.DEFAULT); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { float p = (float) valueAnimator.getAnimatedValue(); if (p < 0.5f) { p = (1f - p / 0.5f); } else { p = (p - 0.5f) / 0.5f; } float scaleDown = 0.9f + 0.1f * p; cameraContainer.setScaleX(p * scaleDown); cameraContainer.setScaleY(scaleDown); textureOverlayView.setScaleX(p * scaleDown); textureOverlayView.setScaleY(scaleDown); } }); valueAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); cameraContainer.setScaleX(1f); cameraContainer.setScaleY(1f); textureOverlayView.setScaleY(1f); textureOverlayView.setScaleX(1f); flipAnimationInProgress = false; invalidate(); } }); valueAnimator.start(); }); muteImageView = new ImageView(context); muteImageView.setScaleType(ImageView.ScaleType.CENTER); muteImageView.setImageResource(R.drawable.video_mute); muteImageView.setAlpha(0.0f); addView(muteImageView, LayoutHelper.createFrame(48, 48, Gravity.CENTER)); Paint blackoutPaint = new Paint(Paint.ANTI_ALIAS_FLAG); blackoutPaint.setColor(ColorUtils.setAlphaComponent(Color.BLACK, 40)); textureOverlayView = new BackupImageView(getContext()) { CellFlickerDrawable flickerDrawable = new CellFlickerDrawable(); @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (needDrawFlickerStub) { flickerDrawable.setParentWidth(textureViewSize); AndroidUtilities.rectTmp.set(0, 0, textureViewSize, textureViewSize); float rad = AndroidUtilities.rectTmp.width() / 2f; canvas.drawRoundRect(AndroidUtilities.rectTmp, rad, rad, blackoutPaint); AndroidUtilities.rectTmp.inset(AndroidUtilities.dp(1), AndroidUtilities.dp(1)); flickerDrawable.draw(canvas, AndroidUtilities.rectTmp, rad, null); invalidate(); } } }; addView(textureOverlayView, new LayoutParams(AndroidUtilities.roundPlayingMessageSize, AndroidUtilities.roundPlayingMessageSize, Gravity.CENTER)); setVisibility(INVISIBLE); blurBehindDrawable = new BlurBehindDrawable(parentView, this, 0, resourcesProvider); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (updateTextureViewSize) { int newSize; if (MeasureSpec.getSize(heightMeasureSpec) > MeasureSpec.getSize(widthMeasureSpec) * 1.3f) { newSize = AndroidUtilities.roundPlayingMessageSize; } else { newSize = AndroidUtilities.roundMessageSize; } if (newSize != textureViewSize) { textureViewSize = newSize; textureOverlayView.getLayoutParams().width = textureOverlayView.getLayoutParams().height = textureViewSize; cameraContainer.getLayoutParams().width = cameraContainer.getLayoutParams().height = textureViewSize; ((LayoutParams) muteImageView.getLayoutParams()).topMargin = textureViewSize / 2 - AndroidUtilities.dp(24); textureOverlayView.setRoundRadius(textureViewSize / 2); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { cameraContainer.invalidateOutline(); } } updateTextureViewSize = false; } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } private boolean checkPointerIds(MotionEvent ev) { if (ev.getPointerCount() < 2) { return false; } if (pointerId1 == ev.getPointerId(0) && pointerId2 == ev.getPointerId(1)) { return true; } if (pointerId1 == ev.getPointerId(1) && pointerId2 == ev.getPointerId(0)) { return true; } return false; } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { getParent().requestDisallowInterceptTouchEvent(true); return super.onInterceptTouchEvent(ev); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); if (getVisibility() != VISIBLE) { animationTranslationY = getMeasuredHeight() / 2; updateTranslationY(); } blurBehindDrawable.checkSizes(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.fileUploaded); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileUploaded); } @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.fileUploaded) { final String location = (String) args[0]; if (cameraFile != null && cameraFile.getAbsolutePath().equals(location)) { file = (TLRPC.InputFile) args[1]; encryptedFile = (TLRPC.InputEncryptedFile) args[2]; size = (Long) args[5]; if (encryptedFile != null) { key = (byte[]) args[3]; iv = (byte[]) args[4]; } } } } public void destroy(boolean async, final Runnable beforeDestroyRunnable) { if (cameraSession != null) { cameraSession.destroy(); CameraController.getInstance().close(cameraSession, !async ? new CountDownLatch(1) : null, beforeDestroyRunnable); } } @Override protected void onDraw(Canvas canvas) { blurBehindDrawable.draw(canvas); float x = cameraContainer.getX(); float y = cameraContainer.getY(); rect.set(x - AndroidUtilities.dp(8), y - AndroidUtilities.dp(8), x + cameraContainer.getMeasuredWidth() + AndroidUtilities.dp(8), y + cameraContainer.getMeasuredHeight() + AndroidUtilities.dp(8)); if (recording) { recordedTime = System.currentTimeMillis() - recordStartTime; progress = Math.min(1f, recordedTime / 60000.0f); invalidate(); } if (progress != 0) { canvas.save(); if (!flipAnimationInProgress) { canvas.scale(cameraContainer.getScaleX(), cameraContainer.getScaleY(), rect.centerX(), rect.centerY()); } canvas.drawArc(rect, -90, 360 * progress, false, paint); canvas.restore(); } if (Theme.chat_roundVideoShadow != null) { int x1 = (int) x - AndroidUtilities.dp(3); int y1 = (int) y - AndroidUtilities.dp(2); canvas.save(); if (isMessageTransition) { canvas.scale(cameraContainer.getScaleX(), cameraContainer.getScaleY(), x, y); } else { canvas.scale(cameraContainer.getScaleX(), cameraContainer.getScaleY(), x + textureViewSize / 2f, y + textureViewSize / 2f); } Theme.chat_roundVideoShadow.setAlpha((int) (cameraContainer.getAlpha() * 255)); Theme.chat_roundVideoShadow.setBounds(x1, y1, x1 + textureViewSize + AndroidUtilities.dp(6), y1 + textureViewSize + AndroidUtilities.dp(6)); Theme.chat_roundVideoShadow.draw(canvas); canvas.restore(); } } @Override public void setVisibility(int visibility) { super.setVisibility(visibility); if (visibility != View.VISIBLE && blurBehindDrawable != null) { blurBehindDrawable.clear(); } switchCameraButton.setAlpha(0.0f); cameraContainer.setAlpha(0.0f); textureOverlayView.setAlpha(0.0f); muteImageView.setAlpha(0.0f); muteImageView.setScaleX(1.0f); muteImageView.setScaleY(1.0f); cameraContainer.setScaleX(0.1f); cameraContainer.setScaleY(0.1f); textureOverlayView.setScaleX(0.1f); textureOverlayView.setScaleY(0.1f); if (cameraContainer.getMeasuredWidth() != 0) { cameraContainer.setPivotX(cameraContainer.getMeasuredWidth() / 2); cameraContainer.setPivotY(cameraContainer.getMeasuredHeight() / 2); textureOverlayView.setPivotX(textureOverlayView.getMeasuredWidth() / 2); textureOverlayView.setPivotY(textureOverlayView.getMeasuredHeight() / 2); } try { if (visibility == VISIBLE) { ((Activity) getContext()).getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } else { ((Activity) getContext()).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } } catch (Exception e) { FileLog.e(e); } } public void showCamera() { if (textureView != null) { return; } if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { switchCameraDrawable = (AnimatedVectorDrawable) ContextCompat.getDrawable(getContext(), R.drawable.avd_flip); switchCameraButton.setImageDrawable(switchCameraDrawable); } else { switchCameraButton.setImageResource(R.drawable.vd_flip); } textureOverlayView.setAlpha(1.0f); textureOverlayView.invalidate(); if (lastBitmap == null) { try { File file = new File(ApplicationLoader.getFilesDirFixed(), "icthumb.jpg"); lastBitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); } catch (Throwable ignore) { } } if (lastBitmap != null) { textureOverlayView.setImageBitmap(lastBitmap); } else { textureOverlayView.setImageResource(R.drawable.icplaceholder); } cameraReady = false; isFrontface = true; selectedCamera = null; recordedTime = 0; progress = 0; cancelled = false; file = null; encryptedFile = null; key = null; iv = null; needDrawFlickerStub = true; if (!initCamera()) { return; } MediaController.getInstance().pauseMessage(MediaController.getInstance().getPlayingMessageObject()); cameraFile = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_DOCUMENT), System.currentTimeMillis() + "_" + SharedConfig.getLastLocalId() + ".mp4") { @Override public boolean delete() { if (BuildVars.LOGS_ENABLED) { FileLog.e("delete camera file"); } return super.delete(); } }; SharedConfig.saveConfig(); AutoDeleteMediaTask.lockFile(cameraFile); if (BuildVars.LOGS_ENABLED) { FileLog.d("show round camera " + cameraFile.getAbsolutePath()); } textureView = new TextureView(getContext()); textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { if (BuildVars.LOGS_ENABLED) { FileLog.d("camera surface available"); } if (cameraThread == null && surface != null) { if (cancelled) { return; } if (BuildVars.LOGS_ENABLED) { FileLog.d("start create thread"); } cameraThread = new CameraGLThread(surface, width, height); } } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture surface, final int width, final int height) { if (cameraThread != null) { cameraThread.surfaceWidth = width; cameraThread.surfaceHeight = height; cameraThread.updateScale(); } } @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { if (cameraThread != null) { cameraThread.shutdown(0); cameraThread = null; } if (cameraSession != null) { CameraController.getInstance().close(cameraSession, null, null); } return true; } @Override public void onSurfaceTextureUpdated(SurfaceTexture surface) { } }); cameraContainer.addView(textureView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); updateTextureViewSize = true; setVisibility(VISIBLE); startAnimation(true); MediaController.getInstance().requestAudioFocus(true); } public InstantViewCameraContainer getCameraContainer() { return cameraContainer; } public void startAnimation(boolean open) { if (animatorSet != null) { animatorSet.removeAllListeners(); animatorSet.cancel(); } PipRoundVideoView pipRoundVideoView = PipRoundVideoView.getInstance(); if (pipRoundVideoView != null) { pipRoundVideoView.showTemporary(!open); } if (open && !opened) { cameraContainer.setTranslationX(0); textureOverlayView.setTranslationX(0); animationTranslationY = getMeasuredHeight() / 2f; updateTranslationY(); } opened = open; if (parentView != null) { parentView.invalidate(); } blurBehindDrawable.show(open); animatorSet = new AnimatorSet(); float toX = 0; if (!open) { toX = recordedTime > 300 ? AndroidUtilities.dp(24) - getMeasuredWidth() / 2f : 0; } ValueAnimator translationYAnimator = ValueAnimator.ofFloat(open ? 1f : 0f, open ? 0 : 1f); translationYAnimator.addUpdateListener(animation -> { animationTranslationY = (getMeasuredHeight() / 2f) * (float) animation.getAnimatedValue(); updateTranslationY(); }); animatorSet.playTogether( ObjectAnimator.ofFloat(switchCameraButton, View.ALPHA, open ? 1.0f : 0.0f), ObjectAnimator.ofFloat(muteImageView, View.ALPHA, 0.0f), ObjectAnimator.ofInt(paint, AnimationProperties.PAINT_ALPHA, open ? 255 : 0), ObjectAnimator.ofFloat(cameraContainer, View.ALPHA, open ? 1.0f : 0.0f), ObjectAnimator.ofFloat(cameraContainer, View.SCALE_X, open ? 1.0f : 0.1f), ObjectAnimator.ofFloat(cameraContainer, View.SCALE_Y, open ? 1.0f : 0.1f), ObjectAnimator.ofFloat(cameraContainer, View.TRANSLATION_X, toX), ObjectAnimator.ofFloat(textureOverlayView, View.ALPHA, open ? 1.0f : 0.0f), ObjectAnimator.ofFloat(textureOverlayView, View.SCALE_X, open ? 1.0f : 0.1f), ObjectAnimator.ofFloat(textureOverlayView, View.SCALE_Y, open ? 1.0f : 0.1f), ObjectAnimator.ofFloat(textureOverlayView, View.TRANSLATION_X, toX), translationYAnimator ); if (!open) { animatorSet.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (animation.equals(animatorSet)) { hideCamera(true); setVisibility(INVISIBLE); } } }); } else { setTranslationX(0); } animatorSet.setDuration(180); animatorSet.setInterpolator(new DecelerateInterpolator()); animatorSet.start(); } private void updateTranslationY() { textureOverlayView.setTranslationY(animationTranslationY + panTranslationY); cameraContainer.setTranslationY(animationTranslationY + panTranslationY); } public Rect getCameraRect() { cameraContainer.getLocationOnScreen(position); return new Rect(position[0], position[1], cameraContainer.getWidth(), cameraContainer.getHeight()); } public void changeVideoPreviewState(int state, float progress) { if (videoPlayer == null) { return; } if (state == 0) { startProgressTimer(); videoPlayer.play(); } else if (state == 1) { stopProgressTimer(); videoPlayer.pause(); } else if (state == 2) { videoPlayer.seekTo((long) (progress * videoPlayer.getDuration())); } } public void send(int state, boolean notify, int scheduleDate) { if (textureView == null) { return; } stopProgressTimer(); if (videoPlayer != null) { videoPlayer.releasePlayer(true); videoPlayer = null; } if (state == 4) { if (BuildVars.DEBUG_VERSION && !cameraFile.exists()) { FileLog.e(new RuntimeException("file not found :( round video")); } if (videoEditedInfo.needConvert()) { file = null; encryptedFile = null; key = null; iv = null; double totalDuration = videoEditedInfo.estimatedDuration; long startTime = videoEditedInfo.startTime >= 0 ? videoEditedInfo.startTime : 0; long endTime = videoEditedInfo.endTime >= 0 ? videoEditedInfo.endTime : videoEditedInfo.estimatedDuration; videoEditedInfo.estimatedDuration = endTime - startTime; videoEditedInfo.estimatedSize = Math.max(1, (long) (size * (videoEditedInfo.estimatedDuration / totalDuration))); videoEditedInfo.bitrate = 1000000; if (videoEditedInfo.startTime > 0) { videoEditedInfo.startTime *= 1000; } if (videoEditedInfo.endTime > 0) { videoEditedInfo.endTime *= 1000; } FileLoader.getInstance(currentAccount).cancelFileUpload(cameraFile.getAbsolutePath(), false); } else { videoEditedInfo.estimatedSize = Math.max(1, size); } videoEditedInfo.file = file; videoEditedInfo.encryptedFile = encryptedFile; videoEditedInfo.key = key; videoEditedInfo.iv = iv; baseFragment.sendMedia(new MediaController.PhotoEntry(0, 0, 0, cameraFile.getAbsolutePath(), 0, true, 0, 0, 0), videoEditedInfo, notify, scheduleDate, false); if (scheduleDate != 0) { startAnimation(false); } MediaController.getInstance().requestAudioFocus(false); } else { cancelled = recordedTime < 800; recording = false; int reason; if (cancelled) { reason = 4; } else { reason = state == 3 ? 2 : 5; } if (cameraThread != null) { NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.recordStopped, recordingGuid, reason); int send; if (cancelled) { send = 0; } else if (state == 3) { send = 2; } else { send = 1; } saveLastCameraBitmap(); cameraThread.shutdown(send); cameraThread = null; } if (cancelled) { NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.audioRecordTooShort, recordingGuid, true, (int) recordedTime); startAnimation(false); MediaController.getInstance().requestAudioFocus(false); } } } private void saveLastCameraBitmap() { Bitmap bitmap = textureView.getBitmap(); if (bitmap != null && bitmap.getPixel(0, 0) != 0) { lastBitmap = Bitmap.createScaledBitmap(textureView.getBitmap(), 50, 50, true); if (lastBitmap != null) { Utilities.blurBitmap(lastBitmap, 7, 1, lastBitmap.getWidth(), lastBitmap.getHeight(), lastBitmap.getRowBytes()); try { File file = new File(ApplicationLoader.getFilesDirFixed(), "icthumb.jpg"); FileOutputStream stream = new FileOutputStream(file); lastBitmap.compress(Bitmap.CompressFormat.JPEG, 87, stream); stream.close(); } catch (Throwable ignore) { } } } } public void cancel(boolean byGesture) { stopProgressTimer(); if (videoPlayer != null) { videoPlayer.releasePlayer(true); videoPlayer = null; } if (textureView == null) { return; } cancelled = true; recording = false; NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.recordStopped, recordingGuid, byGesture ? 0 : 6); if (cameraThread != null) { saveLastCameraBitmap(); cameraThread.shutdown(0); cameraThread = null; } if (cameraFile != null) { if (BuildVars.LOGS_ENABLED) { FileLog.e("delete camera file by cancel"); } cameraFile.delete(); AutoDeleteMediaTask.unlockFile(cameraFile); cameraFile = null; } MediaController.getInstance().requestAudioFocus(false); startAnimation(false); blurBehindDrawable.show(false); invalidate(); } public View getSwitchButtonView() { return switchCameraButton; } public View getMuteImageView() { return muteImageView; } public Paint getPaint() { return paint; } public void hideCamera(boolean async) { destroy(async, null); cameraContainer.setTranslationX(0); textureOverlayView.setTranslationX(0); animationTranslationY = 0; updateTranslationY(); MediaController.getInstance().playMessage(MediaController.getInstance().getPlayingMessageObject()); if (textureView != null) { ViewGroup parent = (ViewGroup) textureView.getParent(); if (parent != null) { parent.removeView(textureView); } } textureView = null; cameraContainer.setImageReceiver(null); } private void switchCamera() { saveLastCameraBitmap(); if (lastBitmap != null) { needDrawFlickerStub = false; textureOverlayView.setImageBitmap(lastBitmap); textureOverlayView.setAlpha(1f); } if (cameraSession != null) { cameraSession.destroy(); CameraController.getInstance().close(cameraSession, null, null); cameraSession = null; } isFrontface = !isFrontface; initCamera(); cameraReady = false; cameraThread.reinitForNewCamera(); } private boolean initCamera() { ArrayList<CameraInfo> cameraInfos = CameraController.getInstance().getCameras(); if (cameraInfos == null) { return false; } CameraInfo notFrontface = null; for (int a = 0; a < cameraInfos.size(); a++) { CameraInfo cameraInfo = cameraInfos.get(a); if (!cameraInfo.isFrontface()) { notFrontface = cameraInfo; } if (isFrontface && cameraInfo.isFrontface() || !isFrontface && !cameraInfo.isFrontface()) { selectedCamera = cameraInfo; break; } else { notFrontface = cameraInfo; } } if (selectedCamera == null) { selectedCamera = notFrontface; } if (selectedCamera == null) { return false; } ArrayList<Size> previewSizes = selectedCamera.getPreviewSizes(); ArrayList<Size> pictureSizes = selectedCamera.getPictureSizes(); previewSize = chooseOptimalSize(previewSizes); pictureSize = chooseOptimalSize(pictureSizes); if (previewSize.mWidth != pictureSize.mWidth) { boolean found = false; for (int a = previewSizes.size() - 1; a >= 0; a--) { Size preview = previewSizes.get(a); for (int b = pictureSizes.size() - 1; b >= 0; b--) { Size picture = pictureSizes.get(b); if (preview.mWidth >= pictureSize.mWidth && preview.mHeight >= pictureSize.mHeight && preview.mWidth == picture.mWidth && preview.mHeight == picture.mHeight) { previewSize = preview; pictureSize = picture; found = true; break; } } if (found) { break; } } if (!found) { for (int a = previewSizes.size() - 1; a >= 0; a--) { Size preview = previewSizes.get(a); for (int b = pictureSizes.size() - 1; b >= 0; b--) { Size picture = pictureSizes.get(b); if (preview.mWidth >= 360 && preview.mHeight >= 360 && preview.mWidth == picture.mWidth && preview.mHeight == picture.mHeight) { previewSize = preview; pictureSize = picture; found = true; break; } } if (found) { break; } } } } if (BuildVars.LOGS_ENABLED) { FileLog.d("preview w = " + previewSize.mWidth + " h = " + previewSize.mHeight); } return true; } private Size chooseOptimalSize(ArrayList<Size> previewSizes) { ArrayList<Size> sortedSizes = new ArrayList<>(); for (int i = 0; i < previewSizes.size(); i++) { if (Math.max(previewSizes.get(i).mHeight, previewSizes.get(i).mWidth) <= 1440 && Math.min(previewSizes.get(i).mHeight, previewSizes.get(i).mWidth) >= 320) { sortedSizes.add(previewSizes.get(i)); } } if (sortedSizes.isEmpty() || !allowBigSizeCamera()) { ArrayList<Size> sizes = sortedSizes; if (!sortedSizes.isEmpty()) { sizes = sortedSizes; } else { sizes = previewSizes; } if (Build.MANUFACTURER.equalsIgnoreCase("Xiaomi")) { return CameraController.chooseOptimalSize(sizes, 640, 480, aspectRatio); } else { return CameraController.chooseOptimalSize(sizes, 480, 270, aspectRatio); } } Collections.sort(sortedSizes, (o1, o2) -> { float a1 = Math.abs(1f - Math.min(o1.mHeight, o1.mWidth) / (float) Math.max(o1.mHeight, o1.mWidth)); float a2 = Math.abs(1f - Math.min(o2.mHeight, o2.mWidth) / (float) Math.max(o2.mHeight, o2.mWidth)); if (a1 < a2) { return -1; } else if (a1 > a2) { return 1; } return 0; }); return sortedSizes.get(0); } private boolean allowBigSizeCamera() { int devicePerformanceClass = Math.max(SharedConfig.getDevicePerformanceClass(), SharedConfig.getLegacyDevicePerformanceClass()); if (devicePerformanceClass == SharedConfig.PERFORMANCE_CLASS_HIGH) { return true; } int hash = (Build.MANUFACTURER + " " + Build.DEVICE).toUpperCase().hashCode(); for (int i = 0; i < ALLOW_BIG_CAMERA_WHITELIST.length; ++i) { if (ALLOW_BIG_CAMERA_WHITELIST[i] == hash) { return true; } } return false; } private void createCamera(final SurfaceTexture surfaceTexture) { AndroidUtilities.runOnUIThread(() -> { if (cameraThread == null) { return; } if (BuildVars.LOGS_ENABLED) { FileLog.d("create camera session"); } surfaceTexture.setDefaultBufferSize(previewSize.getWidth(), previewSize.getHeight()); cameraSession = new CameraSession(selectedCamera, previewSize, pictureSize, ImageFormat.JPEG, true); cameraThread.setCurrentSession(cameraSession); CameraController.getInstance().openRound(cameraSession, surfaceTexture, () -> { if (cameraSession != null) { boolean updateScale = false; try { Camera.Size size = cameraSession.getCurrentPreviewSize(); if (size.width != previewSize.getWidth() || size.height != previewSize.getHeight()) { previewSize = new Size(size.width, size.height); FileLog.d("change preview size to w = " + previewSize.getWidth() + " h = " + previewSize.getHeight()); } } catch (Exception e) { FileLog.e(e); } try { Camera.Size size = cameraSession.getCurrentPictureSize(); if (size.width != pictureSize.getWidth() || size.height != pictureSize.getHeight()) { pictureSize = new Size(size.width, size.height); FileLog.d("change picture size to w = " + pictureSize.getWidth() + " h = " + pictureSize.getHeight()); updateScale = true; } } catch (Exception e) { FileLog.e(e); } if (BuildVars.LOGS_ENABLED) { FileLog.d("camera initied"); } cameraSession.setInitied(); if (updateScale) { if (cameraThread != null) { cameraThread.reinitForNewCamera(); } } } }, () -> { if (cameraThread != null) { cameraThread.setCurrentSession(cameraSession); } }); }); } private int loadShader(int type, String shaderCode) { int shader = GLES20.glCreateShader(type); GLES20.glShaderSource(shader, shaderCode); GLES20.glCompileShader(shader); int[] compileStatus = new int[1]; GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compileStatus, 0); if (compileStatus[0] == 0) { if (BuildVars.LOGS_ENABLED) { FileLog.e(GLES20.glGetShaderInfoLog(shader)); } GLES20.glDeleteShader(shader); shader = 0; } return shader; } private Timer progressTimer; private void startProgressTimer() { if (progressTimer != null) { try { progressTimer.cancel(); progressTimer = null; } catch (Exception e) { FileLog.e(e); } } progressTimer = new Timer(); progressTimer.schedule(new TimerTask() { @Override public void run() { AndroidUtilities.runOnUIThread(() -> { try { if (videoPlayer != null && videoEditedInfo != null && videoEditedInfo.endTime > 0 && videoPlayer.getCurrentPosition() >= videoEditedInfo.endTime) { videoPlayer.seekTo(videoEditedInfo.startTime > 0 ? videoEditedInfo.startTime : 0); } } catch (Exception e) { FileLog.e(e); } }); } }, 0, 17); } private void stopProgressTimer() { if (progressTimer != null) { try { progressTimer.cancel(); progressTimer = null; } catch (Exception e) { FileLog.e(e); } } } public boolean blurFullyDrawing() { return blurBehindDrawable != null && blurBehindDrawable.isFullyDrawing() && opened; } public void invalidateBlur() { if (blurBehindDrawable != null) { blurBehindDrawable.invalidate(); } } public void cancelBlur() { blurBehindDrawable.show(false); invalidate(); } public void onPanTranslationUpdate(float y) { panTranslationY = y / 2f; updateTranslationY(); blurBehindDrawable.onPanTranslationUpdate(y); } public TextureView getTextureView() { return textureView; } public void setIsMessageTransition(boolean isMessageTransition) { this.isMessageTransition = isMessageTransition; } public class CameraGLThread extends DispatchQueue { private final static int EGL_CONTEXT_CLIENT_VERSION = 0x3098; private final static int EGL_OPENGL_ES2_BIT = 4; private SurfaceTexture surfaceTexture; private EGL10 egl10; private EGLDisplay eglDisplay; private EGLContext eglContext; private EGLSurface eglSurface; private boolean initied; private CameraSession currentSession; private SurfaceTexture cameraSurface; private final int DO_RENDER_MESSAGE = 0; private final int DO_SHUTDOWN_MESSAGE = 1; private final int DO_REINIT_MESSAGE = 2; private final int DO_SETSESSION_MESSAGE = 3; private int drawProgram; private int vertexMatrixHandle; private int textureMatrixHandle; private int positionHandle; private int textureHandle; private boolean recording; private Integer cameraId = 0; private VideoRecorder videoEncoder; private int surfaceWidth; private int surfaceHeight; public CameraGLThread(SurfaceTexture surface, int surfaceWidth, int surfaceHeight) { super("CameraGLThread"); surfaceTexture = surface; this.surfaceWidth = surfaceWidth; this.surfaceHeight = surfaceHeight; updateScale(); } private void updateScale() { int width = previewSize.getWidth(); int height = previewSize.getHeight(); float scale = surfaceWidth / (float) Math.min(width, height); width *= scale; height *= scale; if (width == height) { scaleX = 1f; scaleY = 1f; } else if (width > height) { scaleX = 1.0f; scaleY = width / (float) surfaceHeight; } else { scaleX = height / (float) surfaceWidth; scaleY = 1.0f; } FileLog.d("camera scaleX = " + scaleX + " scaleY = " + scaleY); } private boolean initGL() { if (BuildVars.LOGS_ENABLED) { FileLog.d("start init gl"); } egl10 = (EGL10) EGLContext.getEGL(); eglDisplay = egl10.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); if (eglDisplay == EGL10.EGL_NO_DISPLAY) { if (BuildVars.LOGS_ENABLED) { FileLog.e("eglGetDisplay failed " + GLUtils.getEGLErrorString(egl10.eglGetError())); } finish(); return false; } int[] version = new int[2]; if (!egl10.eglInitialize(eglDisplay, version)) { if (BuildVars.LOGS_ENABLED) { FileLog.e("eglInitialize failed " + GLUtils.getEGLErrorString(egl10.eglGetError())); } finish(); return false; } int[] configsCount = new int[1]; EGLConfig[] configs = new EGLConfig[1]; int[] configSpec = new int[]{ EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL10.EGL_RED_SIZE, 8, EGL10.EGL_GREEN_SIZE, 8, EGL10.EGL_BLUE_SIZE, 8, EGL10.EGL_ALPHA_SIZE, 0, EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_STENCIL_SIZE, 0, EGL10.EGL_NONE }; EGLConfig eglConfig; if (!egl10.eglChooseConfig(eglDisplay, configSpec, configs, 1, configsCount)) { if (BuildVars.LOGS_ENABLED) { FileLog.e("eglChooseConfig failed " + GLUtils.getEGLErrorString(egl10.eglGetError())); } finish(); return false; } else if (configsCount[0] > 0) { eglConfig = configs[0]; } else { if (BuildVars.LOGS_ENABLED) { FileLog.e("eglConfig not initialized"); } finish(); return false; } int[] attrib_list = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE}; eglContext = egl10.eglCreateContext(eglDisplay, eglConfig, EGL10.EGL_NO_CONTEXT, attrib_list); if (eglContext == null) { if (BuildVars.LOGS_ENABLED) { FileLog.e("eglCreateContext failed " + GLUtils.getEGLErrorString(egl10.eglGetError())); } finish(); return false; } if (surfaceTexture instanceof SurfaceTexture) { eglSurface = egl10.eglCreateWindowSurface(eglDisplay, eglConfig, surfaceTexture, null); } else { finish(); return false; } if (eglSurface == null || eglSurface == EGL10.EGL_NO_SURFACE) { if (BuildVars.LOGS_ENABLED) { FileLog.e("createWindowSurface failed " + GLUtils.getEGLErrorString(egl10.eglGetError())); } finish(); return false; } if (!egl10.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)) { if (BuildVars.LOGS_ENABLED) { FileLog.e("eglMakeCurrent failed " + GLUtils.getEGLErrorString(egl10.eglGetError())); } finish(); return false; } GL gl = eglContext.getGL(); float tX = 1.0f / scaleX / 2.0f; float tY = 1.0f / scaleY / 2.0f; float[] verticesData = { -1.0f, -1.0f, 0, 1.0f, -1.0f, 0, -1.0f, 1.0f, 0, 1.0f, 1.0f, 0 }; float[] texData = { 0.5f - tX, 0.5f - tY, 0.5f + tX, 0.5f - tY, 0.5f - tX, 0.5f + tY, 0.5f + tX, 0.5f + tY }; videoEncoder = new VideoRecorder(); vertexBuffer = ByteBuffer.allocateDirect(verticesData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer(); vertexBuffer.put(verticesData).position(0); textureBuffer = ByteBuffer.allocateDirect(texData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer(); textureBuffer.put(texData).position(0); android.opengl.Matrix.setIdentityM(mSTMatrix, 0); int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, VERTEX_SHADER); int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, FRAGMENT_SCREEN_SHADER); if (vertexShader != 0 && fragmentShader != 0) { drawProgram = GLES20.glCreateProgram(); GLES20.glAttachShader(drawProgram, vertexShader); GLES20.glAttachShader(drawProgram, fragmentShader); GLES20.glLinkProgram(drawProgram); int[] linkStatus = new int[1]; GLES20.glGetProgramiv(drawProgram, GLES20.GL_LINK_STATUS, linkStatus, 0); if (linkStatus[0] == 0) { if (BuildVars.LOGS_ENABLED) { FileLog.e("failed link shader"); } GLES20.glDeleteProgram(drawProgram); drawProgram = 0; } else { positionHandle = GLES20.glGetAttribLocation(drawProgram, "aPosition"); textureHandle = GLES20.glGetAttribLocation(drawProgram, "aTextureCoord"); vertexMatrixHandle = GLES20.glGetUniformLocation(drawProgram, "uMVPMatrix"); textureMatrixHandle = GLES20.glGetUniformLocation(drawProgram, "uSTMatrix"); } } else { if (BuildVars.LOGS_ENABLED) { FileLog.e("failed creating shader"); } finish(); return false; } GLES20.glGenTextures(1, cameraTexture, 0); GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, cameraTexture[0]); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); android.opengl.Matrix.setIdentityM(mMVPMatrix, 0); cameraSurface = new SurfaceTexture(cameraTexture[0]); cameraSurface.setOnFrameAvailableListener(surfaceTexture -> requestRender()); createCamera(cameraSurface); if (BuildVars.LOGS_ENABLED) { FileLog.e("gl initied"); } return true; } public void reinitForNewCamera() { Handler handler = getHandler(); if (handler != null) { sendMessage(handler.obtainMessage(DO_REINIT_MESSAGE), 0); } updateScale(); } public void finish() { if (eglSurface != null) { egl10.eglMakeCurrent(eglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); egl10.eglDestroySurface(eglDisplay, eglSurface); eglSurface = null; } if (eglContext != null) { egl10.eglDestroyContext(eglDisplay, eglContext); eglContext = null; } if (eglDisplay != null) { egl10.eglTerminate(eglDisplay); eglDisplay = null; } } public void setCurrentSession(CameraSession session) { Handler handler = getHandler(); if (handler != null) { sendMessage(handler.obtainMessage(DO_SETSESSION_MESSAGE, session), 0); } } private void onDraw(Integer cameraId) { if (!initied) { return; } if (!eglContext.equals(egl10.eglGetCurrentContext()) || !eglSurface.equals(egl10.eglGetCurrentSurface(EGL10.EGL_DRAW))) { if (!egl10.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)) { if (BuildVars.LOGS_ENABLED) { FileLog.e("eglMakeCurrent failed " + GLUtils.getEGLErrorString(egl10.eglGetError())); } return; } } cameraSurface.updateTexImage(); if (!recording) { videoEncoder.startRecording(cameraFile, EGL14.eglGetCurrentContext()); recording = true; int orientation = currentSession.getCurrentOrientation(); if (orientation == 90 || orientation == 270) { float temp = scaleX; scaleX = scaleY; scaleY = temp; } } videoEncoder.frameAvailable(cameraSurface, cameraId, System.nanoTime()); cameraSurface.getTransformMatrix(mSTMatrix); GLES20.glUseProgram(drawProgram); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, cameraTexture[0]); GLES20.glVertexAttribPointer(positionHandle, 3, GLES20.GL_FLOAT, false, 12, vertexBuffer); GLES20.glEnableVertexAttribArray(positionHandle); GLES20.glVertexAttribPointer(textureHandle, 2, GLES20.GL_FLOAT, false, 8, textureBuffer); GLES20.glEnableVertexAttribArray(textureHandle); GLES20.glUniformMatrix4fv(textureMatrixHandle, 1, false, mSTMatrix, 0); GLES20.glUniformMatrix4fv(vertexMatrixHandle, 1, false, mMVPMatrix, 0); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); GLES20.glDisableVertexAttribArray(positionHandle); GLES20.glDisableVertexAttribArray(textureHandle); GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0); GLES20.glUseProgram(0); egl10.eglSwapBuffers(eglDisplay, eglSurface); } @Override public void run() { initied = initGL(); super.run(); } @Override public void handleMessage(Message inputMessage) { int what = inputMessage.what; switch (what) { case DO_RENDER_MESSAGE: onDraw((Integer) inputMessage.obj); break; case DO_SHUTDOWN_MESSAGE: finish(); if (recording) { videoEncoder.stopRecording(inputMessage.arg1); } Looper looper = Looper.myLooper(); if (looper != null) { looper.quit(); } break; case DO_REINIT_MESSAGE: { if (!egl10.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)) { if (BuildVars.LOGS_ENABLED) { FileLog.d("eglMakeCurrent failed " + GLUtils.getEGLErrorString(egl10.eglGetError())); } return; } if (cameraSurface != null) { cameraSurface.getTransformMatrix(moldSTMatrix); cameraSurface.setOnFrameAvailableListener(null); cameraSurface.release(); oldCameraTexture[0] = cameraTexture[0]; cameraTextureAlpha = 0.0f; cameraTexture[0] = 0; oldTextureTextureBuffer = textureBuffer.duplicate(); oldTexturePreviewSize = previewSize; } cameraId++; cameraReady = false; GLES20.glGenTextures(1, cameraTexture, 0); GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, cameraTexture[0]); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); cameraSurface = new SurfaceTexture(cameraTexture[0]); cameraSurface.setOnFrameAvailableListener(surfaceTexture -> requestRender()); createCamera(cameraSurface); cameraThread.updateScale(); float tX = 1.0f / scaleX / 2.0f; float tY = 1.0f / scaleY / 2.0f; float[] texData = { 0.5f - tX, 0.5f - tY, 0.5f + tX, 0.5f - tY, 0.5f - tX, 0.5f + tY, 0.5f + tX, 0.5f + tY }; textureBuffer = ByteBuffer.allocateDirect(texData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer(); textureBuffer.put(texData).position(0); break; } case DO_SETSESSION_MESSAGE: { if (BuildVars.LOGS_ENABLED) { FileLog.d("set gl rednderer session"); } CameraSession newSession = (CameraSession) inputMessage.obj; if (currentSession == newSession) { int rotationAngle = currentSession.getWorldAngle(); android.opengl.Matrix.setIdentityM(mMVPMatrix, 0); if (rotationAngle != 0) { android.opengl.Matrix.rotateM(mMVPMatrix, 0, rotationAngle, 0, 0, 1); } } else { currentSession = newSession; } break; } } } public void shutdown(int send) { Handler handler = getHandler(); if (handler != null) { sendMessage(handler.obtainMessage(DO_SHUTDOWN_MESSAGE, send, 0), 0); } } public void requestRender() { Handler handler = getHandler(); if (handler != null) { sendMessage(handler.obtainMessage(DO_RENDER_MESSAGE, cameraId), 0); } } } private static final int MSG_START_RECORDING = 0; private static final int MSG_STOP_RECORDING = 1; private static final int MSG_VIDEOFRAME_AVAILABLE = 2; private static final int MSG_AUDIOFRAME_AVAILABLE = 3; private static class EncoderHandler extends Handler { private WeakReference<VideoRecorder> mWeakEncoder; public EncoderHandler(VideoRecorder encoder) { mWeakEncoder = new WeakReference<>(encoder); } @Override public void handleMessage(Message inputMessage) { int what = inputMessage.what; Object obj = inputMessage.obj; VideoRecorder encoder = mWeakEncoder.get(); if (encoder == null) { return; } switch (what) { case MSG_START_RECORDING: { try { if (BuildVars.LOGS_ENABLED) { FileLog.e("start encoder"); } encoder.prepareEncoder(); } catch (Exception e) { FileLog.e(e); encoder.handleStopRecording(0); Looper.myLooper().quit(); } break; } case MSG_STOP_RECORDING: { if (BuildVars.LOGS_ENABLED) { FileLog.e("stop encoder"); } encoder.handleStopRecording(inputMessage.arg1); break; } case MSG_VIDEOFRAME_AVAILABLE: { long timestamp = (((long) inputMessage.arg1) << 32) | (((long) inputMessage.arg2) & 0xffffffffL); Integer cameraId = (Integer) inputMessage.obj; encoder.handleVideoFrameAvailable(timestamp, cameraId); break; } case MSG_AUDIOFRAME_AVAILABLE: { encoder.handleAudioFrameAvailable((AudioBufferInfo) inputMessage.obj); break; } } } public void exit() { Looper.myLooper().quit(); } } public static class AudioBufferInfo { public final static int MAX_SAMPLES = 10; public ByteBuffer[] buffer = new ByteBuffer[MAX_SAMPLES]; public long[] offset = new long[MAX_SAMPLES]; public int[] read = new int[MAX_SAMPLES]; public int results; public int lastWroteBuffer; public boolean last; public AudioBufferInfo() { for (int i = 0; i < MAX_SAMPLES; i++) { buffer[i] = ByteBuffer.allocateDirect(2048); buffer[i].order(ByteOrder.nativeOrder()); } } } private class VideoRecorder implements Runnable { private static final String VIDEO_MIME_TYPE = "video/avc"; private static final String AUDIO_MIME_TYPE = "audio/mp4a-latm"; private static final int FRAME_RATE = 30; private static final int IFRAME_INTERVAL = 1; private File videoFile; private int videoWidth; private int videoHeight; private int videoBitrate; private boolean videoConvertFirstWrite = true; private boolean blendEnabled; private Surface surface; private android.opengl.EGLDisplay eglDisplay = EGL14.EGL_NO_DISPLAY; private android.opengl.EGLContext eglContext = EGL14.EGL_NO_CONTEXT; private android.opengl.EGLContext sharedEglContext; private android.opengl.EGLConfig eglConfig; private android.opengl.EGLSurface eglSurface = EGL14.EGL_NO_SURFACE; private MediaCodec videoEncoder; private MediaCodec audioEncoder; private int prependHeaderSize; private boolean firstEncode; private MediaCodec.BufferInfo videoBufferInfo; private MediaCodec.BufferInfo audioBufferInfo; private MP4Builder mediaMuxer; private ArrayList<AudioBufferInfo> buffersToWrite = new ArrayList<>(); private int videoTrackIndex = -5; private int audioTrackIndex = -5; private long lastCommitedFrameTime; private long audioStartTime = -1; private long currentTimestamp = 0; private long lastTimestamp = -1; private volatile EncoderHandler handler; private final Object sync = new Object(); private boolean ready; private volatile boolean running; private volatile int sendWhenDone; private long skippedTime; private boolean skippedFirst; private long desyncTime; private long videoFirst = -1; private long videoLast; private long audioFirst = -1; private boolean audioStopedByTime; private int drawProgram; private int vertexMatrixHandle; private int textureMatrixHandle; private int positionHandle; private int textureHandle; private int resolutionHandle; private int previewSizeHandle; private int alphaHandle; private int zeroTimeStamps; private Integer lastCameraId = 0; private AudioRecord audioRecorder; private ArrayBlockingQueue<AudioBufferInfo> buffers = new ArrayBlockingQueue<>(10); private ArrayList<Bitmap> keyframeThumbs = new ArrayList<>(); private DispatchQueue generateKeyframeThumbsQueue; private int frameCount; private Runnable recorderRunnable = new Runnable() { @RequiresApi(api = Build.VERSION_CODES.N) @Override public void run() { long audioPresentationTimeUs = -1; int readResult; boolean done = false; AudioTimestamp audioTimestamp = new AudioTimestamp(); boolean shouldUseTimestamp = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N; while (!done) { if (!running && audioRecorder.getRecordingState() != AudioRecord.RECORDSTATE_STOPPED) { try { audioRecorder.stop(); } catch (Exception e) { done = true; } if (sendWhenDone == 0) { break; } } AudioBufferInfo buffer; if (buffers.isEmpty()) { buffer = new AudioBufferInfo(); } else { buffer = buffers.poll(); } buffer.lastWroteBuffer = 0; buffer.results = AudioBufferInfo.MAX_SAMPLES; for (int a = 0; a < AudioBufferInfo.MAX_SAMPLES; a++) { if (audioPresentationTimeUs == -1 && !shouldUseTimestamp) { audioPresentationTimeUs = System.nanoTime() / 1000; } ByteBuffer byteBuffer = buffer.buffer[a]; byteBuffer.rewind(); readResult = audioRecorder.read(byteBuffer, 2048); if (readResult > 0 && a % 2 == 0) { byteBuffer.limit(readResult); double s = 0; for (int i = 0; i < readResult / 2; i++) { short p = byteBuffer.getShort(); s += p * p; } double amplitude = Math.sqrt(s / readResult / 2); AndroidUtilities.runOnUIThread(() -> NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.recordProgressChanged, recordingGuid, amplitude)); byteBuffer.position(0); } if (readResult <= 0) { buffer.results = a; if (!running) { buffer.last = true; } break; } if (shouldUseTimestamp) { audioRecorder.getTimestamp(audioTimestamp, AudioTimestamp.TIMEBASE_MONOTONIC); buffer.offset[a] = audioTimestamp.nanoTime / 1000; } else { buffer.offset[a] = audioPresentationTimeUs; } buffer.read[a] = readResult; int bufferDurationUs = 1000000 * readResult / audioSampleRate / 2; if (!shouldUseTimestamp) { audioPresentationTimeUs += bufferDurationUs; } } if (buffer.results >= 0 || buffer.last) { if (!running && buffer.results < AudioBufferInfo.MAX_SAMPLES) { done = true; } handler.sendMessage(handler.obtainMessage(MSG_AUDIOFRAME_AVAILABLE, buffer)); } else { if (!running) { done = true; } else { try { buffers.put(buffer); } catch (Exception ignore) { } } } } try { audioRecorder.release(); } catch (Exception e) { FileLog.e(e); } handler.sendMessage(handler.obtainMessage(MSG_STOP_RECORDING, sendWhenDone, 0)); } }; public void startRecording(File outputFile, android.opengl.EGLContext sharedContext) { int resolution = MessagesController.getInstance(currentAccount).roundVideoSize; int bitrate = MessagesController.getInstance(currentAccount).roundVideoBitrate * 1024; videoFile = outputFile; videoWidth = resolution; videoHeight = resolution; videoBitrate = bitrate; sharedEglContext = sharedContext; synchronized (sync) { if (running) { return; } running = true; Thread thread = new Thread(this, "TextureMovieEncoder"); thread.setPriority(Thread.MAX_PRIORITY); thread.start(); while (!ready) { try { sync.wait(); } catch (InterruptedException ie) { // ignore } } } keyframeThumbs.clear(); frameCount = 0; if (generateKeyframeThumbsQueue != null) { generateKeyframeThumbsQueue.cleanupQueue(); generateKeyframeThumbsQueue.recycle(); } generateKeyframeThumbsQueue = new DispatchQueue("keyframes_thumb_queque"); handler.sendMessage(handler.obtainMessage(MSG_START_RECORDING)); } public void stopRecording(int send) { handler.sendMessage(handler.obtainMessage(MSG_STOP_RECORDING, send, 0)); } public void frameAvailable(SurfaceTexture st, Integer cameraId, long timestampInternal) { synchronized (sync) { if (!ready) { return; } } long timestamp = st.getTimestamp(); if (timestamp == 0) { zeroTimeStamps++; if (zeroTimeStamps > 1) { if (BuildVars.LOGS_ENABLED) { FileLog.d("fix timestamp enabled"); } timestamp = timestampInternal; } else { return; } } else { zeroTimeStamps = 0; } handler.sendMessage(handler.obtainMessage(MSG_VIDEOFRAME_AVAILABLE, (int) (timestamp >> 32), (int) timestamp, cameraId)); } @Override public void run() { Looper.prepare(); synchronized (sync) { handler = new EncoderHandler(this); ready = true; sync.notify(); } Looper.loop(); synchronized (sync) { ready = false; } } private void handleAudioFrameAvailable(AudioBufferInfo input) { if (audioStopedByTime) { return; } buffersToWrite.add(input); if (audioFirst == -1) { if (videoFirst == -1) { if (BuildVars.LOGS_ENABLED) { FileLog.d("video record not yet started"); } return; } while (true) { boolean ok = false; for (int a = 0; a < input.results; a++) { if (a == 0 && Math.abs(videoFirst - input.offset[a]) > 10000000L) { desyncTime = videoFirst - input.offset[a]; audioFirst = input.offset[a]; ok = true; if (BuildVars.LOGS_ENABLED) { FileLog.d("detected desync between audio and video " + desyncTime); } break; } if (input.offset[a] >= videoFirst) { input.lastWroteBuffer = a; audioFirst = input.offset[a]; ok = true; if (BuildVars.LOGS_ENABLED) { FileLog.d("found first audio frame at " + a + " timestamp = " + input.offset[a]); } break; } else { if (BuildVars.LOGS_ENABLED) { FileLog.d("ignore first audio frame at " + a + " timestamp = " + input.offset[a]); } } } if (!ok) { if (BuildVars.LOGS_ENABLED) { FileLog.d("first audio frame not found, removing buffers " + input.results); } buffersToWrite.remove(input); } else { break; } if (!buffersToWrite.isEmpty()) { input = buffersToWrite.get(0); } else { return; } } } if (audioStartTime == -1) { audioStartTime = input.offset[input.lastWroteBuffer]; } if (buffersToWrite.size() > 1) { input = buffersToWrite.get(0); } try { drainEncoder(false); } catch (Exception e) { FileLog.e(e); } try { boolean isLast = false; while (input != null) { int inputBufferIndex = audioEncoder.dequeueInputBuffer(0); if (inputBufferIndex >= 0) { ByteBuffer inputBuffer; if (Build.VERSION.SDK_INT >= 21) { inputBuffer = audioEncoder.getInputBuffer(inputBufferIndex); } else { ByteBuffer[] inputBuffers = audioEncoder.getInputBuffers(); inputBuffer = inputBuffers[inputBufferIndex]; inputBuffer.clear(); } long startWriteTime = input.offset[input.lastWroteBuffer]; for (int a = input.lastWroteBuffer; a <= input.results; a++) { if (a < input.results) { if (!running && input.offset[a] >= videoLast - desyncTime) { if (BuildVars.LOGS_ENABLED) { FileLog.d("stop audio encoding because of stoped video recording at " + input.offset[a] + " last video " + videoLast); } audioStopedByTime = true; isLast = true; input = null; buffersToWrite.clear(); break; } if (inputBuffer.remaining() < input.read[a]) { input.lastWroteBuffer = a; input = null; break; } inputBuffer.put(input.buffer[a]); } if (a >= input.results - 1) { buffersToWrite.remove(input); if (running) { buffers.put(input); } if (!buffersToWrite.isEmpty()) { input = buffersToWrite.get(0); } else { isLast = input.last; input = null; break; } } } audioEncoder.queueInputBuffer(inputBufferIndex, 0, inputBuffer.position(), startWriteTime == 0 ? 0 : startWriteTime - audioStartTime, isLast ? MediaCodec.BUFFER_FLAG_END_OF_STREAM : 0); } } } catch (Throwable e) { FileLog.e(e); } } private void handleVideoFrameAvailable(long timestampNanos, Integer cameraId) { try { drainEncoder(false); } catch (Exception e) { FileLog.e(e); } long dt, alphaDt; if (!lastCameraId.equals(cameraId)) { lastTimestamp = -1; lastCameraId = cameraId; } if (lastTimestamp == -1) { lastTimestamp = timestampNanos; if (currentTimestamp != 0) { dt = (System.currentTimeMillis() - lastCommitedFrameTime) * 1000000; alphaDt = 0; } else { alphaDt = dt = 0; } } else { alphaDt = dt = (timestampNanos - lastTimestamp); lastTimestamp = timestampNanos; } lastCommitedFrameTime = System.currentTimeMillis(); if (!skippedFirst) { skippedTime += dt; if (skippedTime < 200000000) { return; } skippedFirst = true; } currentTimestamp += dt; if (videoFirst == -1) { videoFirst = timestampNanos / 1000; if (BuildVars.LOGS_ENABLED) { FileLog.d("first video frame was at " + videoFirst); } } videoLast = timestampNanos; GLES20.glUseProgram(drawProgram); GLES20.glUniformMatrix4fv(vertexMatrixHandle, 1, false, mMVPMatrix, 0); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glEnableVertexAttribArray(positionHandle); GLES20.glEnableVertexAttribArray(textureHandle); GLES20.glUniform2f(resolutionHandle, videoWidth, videoHeight); if (oldCameraTexture[0] != 0 && oldTextureTextureBuffer != null) { if (!blendEnabled) { GLES20.glEnable(GLES20.GL_BLEND); blendEnabled = true; } if (oldTexturePreviewSize != null) { GLES20.glUniform2f(previewSizeHandle, oldTexturePreviewSize.getWidth(), oldTexturePreviewSize.getHeight()); } GLES20.glVertexAttribPointer(textureHandle, 2, GLES20.GL_FLOAT, false, 8, oldTextureTextureBuffer); GLES20.glUniformMatrix4fv(textureMatrixHandle, 1, false, moldSTMatrix, 0); GLES20.glUniform1f(alphaHandle, 1.0f); GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, oldCameraTexture[0]); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); } if (previewSize != null) { GLES20.glUniform2f(previewSizeHandle, previewSize.getWidth(), previewSize.getHeight()); } GLES20.glVertexAttribPointer(positionHandle, 3, GLES20.GL_FLOAT, false, 12, vertexBuffer); GLES20.glVertexAttribPointer(textureHandle, 2, GLES20.GL_FLOAT, false, 8, textureBuffer); GLES20.glUniformMatrix4fv(textureMatrixHandle, 1, false, mSTMatrix, 0); GLES20.glUniform1f(alphaHandle, cameraTextureAlpha); GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, cameraTexture[0]); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); GLES20.glDisableVertexAttribArray(positionHandle); GLES20.glDisableVertexAttribArray(textureHandle); GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0); GLES20.glUseProgram(0); EGLExt.eglPresentationTimeANDROID(eglDisplay, eglSurface, currentTimestamp); EGL14.eglSwapBuffers(eglDisplay, eglSurface); createKeyframeThumb(); frameCount++; if (oldCameraTexture[0] != 0 && cameraTextureAlpha < 1.0f) { cameraTextureAlpha += alphaDt / 200000000.0f; if (cameraTextureAlpha > 1) { GLES20.glDisable(GLES20.GL_BLEND); blendEnabled = false; cameraTextureAlpha = 1; GLES20.glDeleteTextures(1, oldCameraTexture, 0); oldCameraTexture[0] = 0; if (!cameraReady) { cameraReady = true; AndroidUtilities.runOnUIThread(() -> textureOverlayView.animate().setDuration(120).alpha(0.0f).setInterpolator(new DecelerateInterpolator()).start()); } } } else if (!cameraReady) { cameraReady = true; AndroidUtilities.runOnUIThread(() -> textureOverlayView.animate().setDuration(120).alpha(0.0f).setInterpolator(new DecelerateInterpolator()).start()); } } private void createKeyframeThumb() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && SharedConfig.getDevicePerformanceClass() == SharedConfig.PERFORMANCE_CLASS_HIGH && frameCount % 33 == 0) { GenerateKeyframeThumbTask task = new GenerateKeyframeThumbTask(); generateKeyframeThumbsQueue.postRunnable(task); } } private class GenerateKeyframeThumbTask implements Runnable { @Override public void run() { final TextureView textureView = InstantCameraView.this.textureView; if (textureView != null) { try { final Bitmap bitmap = textureView.getBitmap(AndroidUtilities.dp(56), AndroidUtilities.dp(56)); AndroidUtilities.runOnUIThread(() -> { if ((bitmap == null || bitmap.getPixel(0, 0) == 0) && keyframeThumbs.size() > 1) { keyframeThumbs.add(keyframeThumbs.get(keyframeThumbs.size() - 1)); } else { keyframeThumbs.add(bitmap); } }); } catch (Exception e) { FileLog.e(e); } } } } private void handleStopRecording(final int send) { if (running) { sendWhenDone = send; running = false; return; } try { drainEncoder(true); } catch (Exception e) { FileLog.e(e); } if (videoEncoder != null) { try { videoEncoder.stop(); videoEncoder.release(); videoEncoder = null; } catch (Exception e) { FileLog.e(e); } } if (audioEncoder != null) { try { audioEncoder.stop(); audioEncoder.release(); audioEncoder = null; setBluetoothScoOn(false); } catch (Exception e) { FileLog.e(e); } } if (mediaMuxer != null) { try { mediaMuxer.finishMovie(); } catch (Exception e) { FileLog.e(e); } } if (generateKeyframeThumbsQueue != null) { generateKeyframeThumbsQueue.cleanupQueue(); generateKeyframeThumbsQueue.recycle(); generateKeyframeThumbsQueue = null; } if (send != 0) { AndroidUtilities.runOnUIThread(() -> { videoEditedInfo = new VideoEditedInfo(); videoEditedInfo.roundVideo = true; videoEditedInfo.startTime = -1; videoEditedInfo.endTime = -1; videoEditedInfo.file = file; videoEditedInfo.encryptedFile = encryptedFile; videoEditedInfo.key = key; videoEditedInfo.iv = iv; videoEditedInfo.estimatedSize = Math.max(1, size); videoEditedInfo.framerate = 25; videoEditedInfo.resultWidth = videoEditedInfo.originalWidth = 360; videoEditedInfo.resultHeight = videoEditedInfo.originalHeight = 360; videoEditedInfo.originalPath = videoFile.getAbsolutePath(); if (send == 1) { if (baseFragment.isInScheduleMode()) { AlertsCreator.createScheduleDatePickerDialog(baseFragment.getParentActivity(), baseFragment.getDialogId(), (notify, scheduleDate) -> { baseFragment.sendMedia(new MediaController.PhotoEntry(0, 0, 0, videoFile.getAbsolutePath(), 0, true, 0, 0, 0), videoEditedInfo, notify, scheduleDate, false); startAnimation(false); }, () -> { startAnimation(false); }, resourcesProvider); } else { baseFragment.sendMedia(new MediaController.PhotoEntry(0, 0, 0, videoFile.getAbsolutePath(), 0, true, 0, 0, 0), videoEditedInfo, true, 0, false); } } else { videoPlayer = new VideoPlayer(); videoPlayer.setDelegate(new VideoPlayer.VideoPlayerDelegate() { @Override public void onStateChanged(boolean playWhenReady, int playbackState) { if (videoPlayer == null) { return; } if (videoPlayer.isPlaying() && playbackState == ExoPlayer.STATE_ENDED) { videoPlayer.seekTo(videoEditedInfo.startTime > 0 ? videoEditedInfo.startTime : 0); } } @Override public void onError(VideoPlayer player, Exception e) { FileLog.e(e); } @Override public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) { } @Override public void onRenderedFirstFrame() { } @Override public boolean onSurfaceDestroyed(SurfaceTexture surfaceTexture) { return false; } @Override public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) { } }); videoPlayer.setTextureView(textureView); videoPlayer.preparePlayer(Uri.fromFile(videoFile), "other"); videoPlayer.play(); videoPlayer.setMute(true); startProgressTimer(); AnimatorSet animatorSet = new AnimatorSet(); animatorSet.playTogether( ObjectAnimator.ofFloat(switchCameraButton, View.ALPHA, 0.0f), ObjectAnimator.ofInt(paint, AnimationProperties.PAINT_ALPHA, 0), ObjectAnimator.ofFloat(muteImageView, View.ALPHA, 1.0f)); animatorSet.setDuration(180); animatorSet.setInterpolator(new DecelerateInterpolator()); animatorSet.start(); videoEditedInfo.estimatedDuration = recordedTime; NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.audioDidSent, recordingGuid, videoEditedInfo, videoFile.getAbsolutePath(), keyframeThumbs); } didWriteData(videoFile, 0, true); MediaController.getInstance().requestAudioFocus(false); }); } else { FileLoader.getInstance(currentAccount).cancelFileUpload(videoFile.getAbsolutePath(), false); videoFile.delete(); } EGL14.eglDestroySurface(eglDisplay, eglSurface); eglSurface = EGL14.EGL_NO_SURFACE; if (surface != null) { surface.release(); surface = null; } if (eglDisplay != EGL14.EGL_NO_DISPLAY) { EGL14.eglMakeCurrent(eglDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT); EGL14.eglDestroyContext(eglDisplay, eglContext); EGL14.eglReleaseThread(); EGL14.eglTerminate(eglDisplay); } eglDisplay = EGL14.EGL_NO_DISPLAY; eglContext = EGL14.EGL_NO_CONTEXT; eglConfig = null; handler.exit(); } private void setBluetoothScoOn(boolean scoOn) { AudioManager am = (AudioManager) ApplicationLoader.applicationContext.getSystemService(Context.AUDIO_SERVICE); if (am.isBluetoothScoAvailableOffCall() && SharedConfig.recordViaSco || !scoOn) { BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); try { if (btAdapter != null && btAdapter.getProfileConnectionState(BluetoothProfile.HEADSET) == BluetoothProfile.STATE_CONNECTED || !scoOn) { if (scoOn && !am.isBluetoothScoOn()) { am.startBluetoothSco(); } else if (!scoOn && am.isBluetoothScoOn()) { am.stopBluetoothSco(); } } } catch (SecurityException ignored) { } catch (Throwable e) { FileLog.e(e); } } } private void prepareEncoder() { setBluetoothScoOn(true); try { int recordBufferSize = AudioRecord.getMinBufferSize(audioSampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT); if (recordBufferSize <= 0) { recordBufferSize = 3584; } int bufferSize = 2048 * 24; if (bufferSize < recordBufferSize) { bufferSize = ((recordBufferSize / 2048) + 1) * 2048 * 2; } for (int a = 0; a < 3; a++) { buffers.add(new AudioBufferInfo()); } audioRecorder = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, audioSampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize); audioRecorder.startRecording(); if (BuildVars.LOGS_ENABLED) { FileLog.d("initied audio record with channels " + audioRecorder.getChannelCount() + " sample rate = " + audioRecorder.getSampleRate() + " bufferSize = " + bufferSize); } Thread thread = new Thread(recorderRunnable); thread.setPriority(Thread.MAX_PRIORITY); thread.start(); audioBufferInfo = new MediaCodec.BufferInfo(); videoBufferInfo = new MediaCodec.BufferInfo(); MediaFormat audioFormat = new MediaFormat(); audioFormat.setString(MediaFormat.KEY_MIME, AUDIO_MIME_TYPE); audioFormat.setInteger(MediaFormat.KEY_SAMPLE_RATE, audioSampleRate); audioFormat.setInteger(MediaFormat.KEY_CHANNEL_COUNT, 1); audioFormat.setInteger(MediaFormat.KEY_BIT_RATE, MessagesController.getInstance(currentAccount).roundAudioBitrate * 1024); audioFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 2048 * AudioBufferInfo.MAX_SAMPLES); audioEncoder = MediaCodec.createEncoderByType(AUDIO_MIME_TYPE); audioEncoder.configure(audioFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); audioEncoder.start(); videoEncoder = MediaCodec.createEncoderByType(VIDEO_MIME_TYPE); firstEncode = true; MediaFormat format = MediaFormat.createVideoFormat(VIDEO_MIME_TYPE, videoWidth, videoHeight); format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface); format.setInteger(MediaFormat.KEY_BIT_RATE, videoBitrate); format.setInteger(MediaFormat.KEY_FRAME_RATE, FRAME_RATE); format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, IFRAME_INTERVAL); /*if (Build.VERSION.SDK_INT >= 21) { format.setInteger(MediaFormat.KEY_PROFILE, MediaCodecInfo.CodecProfileLevel.AVCProfileHigh); if (Build.VERSION.SDK_INT >= 23) { format.setInteger(MediaFormat.KEY_LEVEL, MediaCodecInfo.CodecProfileLevel.AVCLevel5); } }*/ videoEncoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); surface = videoEncoder.createInputSurface(); videoEncoder.start(); Mp4Movie movie = new Mp4Movie(); movie.setCacheFile(videoFile); movie.setRotation(0); movie.setSize(videoWidth, videoHeight); mediaMuxer = new MP4Builder().createMovie(movie, isSecretChat); AndroidUtilities.runOnUIThread(() -> { if (cancelled) { return; } try { performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING); } catch (Exception ignore) { } AndroidUtilities.lockOrientation(baseFragment.getParentActivity()); recording = true; recordStartTime = System.currentTimeMillis(); invalidate(); NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.recordStarted, recordingGuid, false); }); } catch (Exception ioe) { throw new RuntimeException(ioe); } if (eglDisplay != EGL14.EGL_NO_DISPLAY) { throw new RuntimeException("EGL already set up"); } eglDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY); if (eglDisplay == EGL14.EGL_NO_DISPLAY) { throw new RuntimeException("unable to get EGL14 display"); } int[] version = new int[2]; if (!EGL14.eglInitialize(eglDisplay, version, 0, version, 1)) { eglDisplay = null; throw new RuntimeException("unable to initialize EGL14"); } if (eglContext == EGL14.EGL_NO_CONTEXT) { int renderableType = EGL14.EGL_OPENGL_ES2_BIT; int[] attribList = { EGL14.EGL_RED_SIZE, 8, EGL14.EGL_GREEN_SIZE, 8, EGL14.EGL_BLUE_SIZE, 8, EGL14.EGL_ALPHA_SIZE, 8, EGL14.EGL_RENDERABLE_TYPE, renderableType, 0x3142, 1, EGL14.EGL_NONE }; android.opengl.EGLConfig[] configs = new android.opengl.EGLConfig[1]; int[] numConfigs = new int[1]; if (!EGL14.eglChooseConfig(eglDisplay, attribList, 0, configs, 0, configs.length, numConfigs, 0)) { throw new RuntimeException("Unable to find a suitable EGLConfig"); } int[] attrib2_list = { EGL14.EGL_CONTEXT_CLIENT_VERSION, 2, EGL14.EGL_NONE }; eglContext = EGL14.eglCreateContext(eglDisplay, configs[0], sharedEglContext, attrib2_list, 0); eglConfig = configs[0]; } int[] values = new int[1]; EGL14.eglQueryContext(eglDisplay, eglContext, EGL14.EGL_CONTEXT_CLIENT_VERSION, values, 0); if (eglSurface != EGL14.EGL_NO_SURFACE) { throw new IllegalStateException("surface already created"); } int[] surfaceAttribs = { EGL14.EGL_NONE }; eglSurface = EGL14.eglCreateWindowSurface(eglDisplay, eglConfig, surface, surfaceAttribs, 0); if (eglSurface == null) { throw new RuntimeException("surface was null"); } if (!EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)) { if (BuildVars.LOGS_ENABLED) { FileLog.e("eglMakeCurrent failed " + GLUtils.getEGLErrorString(EGL14.eglGetError())); } throw new RuntimeException("eglMakeCurrent failed"); } GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, VERTEX_SHADER); int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, createFragmentShader(previewSize)); if (vertexShader != 0 && fragmentShader != 0) { drawProgram = GLES20.glCreateProgram(); GLES20.glAttachShader(drawProgram, vertexShader); GLES20.glAttachShader(drawProgram, fragmentShader); GLES20.glLinkProgram(drawProgram); int[] linkStatus = new int[1]; GLES20.glGetProgramiv(drawProgram, GLES20.GL_LINK_STATUS, linkStatus, 0); if (linkStatus[0] == 0) { GLES20.glDeleteProgram(drawProgram); drawProgram = 0; } else { positionHandle = GLES20.glGetAttribLocation(drawProgram, "aPosition"); textureHandle = GLES20.glGetAttribLocation(drawProgram, "aTextureCoord"); previewSizeHandle = GLES20.glGetUniformLocation(drawProgram, "preview"); resolutionHandle = GLES20.glGetUniformLocation(drawProgram, "resolution"); alphaHandle = GLES20.glGetUniformLocation(drawProgram, "alpha"); vertexMatrixHandle = GLES20.glGetUniformLocation(drawProgram, "uMVPMatrix"); textureMatrixHandle = GLES20.glGetUniformLocation(drawProgram, "uSTMatrix"); } } } public Surface getInputSurface() { return surface; } private void didWriteData(File file, long availableSize, boolean last) { if (videoConvertFirstWrite) { FileLoader.getInstance(currentAccount).uploadFile(file.toString(), isSecretChat, false, 1, ConnectionsManager.FileTypeVideo, false); videoConvertFirstWrite = false; if (last) { FileLoader.getInstance(currentAccount).checkUploadNewDataAvailable(file.toString(), isSecretChat, availableSize, last ? file.length() : 0); } } else { FileLoader.getInstance(currentAccount).checkUploadNewDataAvailable(file.toString(), isSecretChat, availableSize, last ? file.length() : 0); } } public void drainEncoder(boolean endOfStream) throws Exception { if (endOfStream) { videoEncoder.signalEndOfInputStream(); } ByteBuffer[] encoderOutputBuffers = null; if (Build.VERSION.SDK_INT < 21) { encoderOutputBuffers = videoEncoder.getOutputBuffers(); } while (true) { int encoderStatus = videoEncoder.dequeueOutputBuffer(videoBufferInfo, 10000); if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) { if (!endOfStream) { break; } } else if (encoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) { if (Build.VERSION.SDK_INT < 21) { encoderOutputBuffers = videoEncoder.getOutputBuffers(); } } else if (encoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { MediaFormat newFormat = videoEncoder.getOutputFormat(); if (videoTrackIndex == -5) { videoTrackIndex = mediaMuxer.addTrack(newFormat, false); if (newFormat.containsKey(MediaFormat.KEY_PREPEND_HEADER_TO_SYNC_FRAMES) && newFormat.getInteger(MediaFormat.KEY_PREPEND_HEADER_TO_SYNC_FRAMES) == 1) { ByteBuffer spsBuff = newFormat.getByteBuffer("csd-0"); ByteBuffer ppsBuff = newFormat.getByteBuffer("csd-1"); prependHeaderSize = spsBuff.limit() + ppsBuff.limit(); } } } else if (encoderStatus >= 0) { ByteBuffer encodedData; if (Build.VERSION.SDK_INT < 21) { encodedData = encoderOutputBuffers[encoderStatus]; } else { encodedData = videoEncoder.getOutputBuffer(encoderStatus); } if (encodedData == null) { throw new RuntimeException("encoderOutputBuffer " + encoderStatus + " was null"); } if (videoBufferInfo.size > 1) { if ((videoBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) == 0) { if (prependHeaderSize != 0 && (videoBufferInfo.flags & MediaCodec.BUFFER_FLAG_KEY_FRAME) != 0) { videoBufferInfo.offset += prependHeaderSize; videoBufferInfo.size -= prependHeaderSize; } if (firstEncode && (videoBufferInfo.flags & MediaCodec.BUFFER_FLAG_KEY_FRAME) != 0) { if (videoBufferInfo.size > 100) { encodedData.position(videoBufferInfo.offset); byte[] temp = new byte[100]; encodedData.get(temp); int nalCount = 0; for (int a = 0; a < temp.length - 4; a++) { if (temp[a] == 0 && temp[a + 1] == 0 && temp[a + 2] == 0 && temp[a + 3] == 1) { nalCount++; if (nalCount > 1) { videoBufferInfo.offset += a; videoBufferInfo.size -= a; break; } } } } firstEncode = false; } long availableSize = mediaMuxer.writeSampleData(videoTrackIndex, encodedData, videoBufferInfo, true); if (availableSize != 0) { didWriteData(videoFile, availableSize, false); } } else if (videoTrackIndex == -5) { byte[] csd = new byte[videoBufferInfo.size]; encodedData.limit(videoBufferInfo.offset + videoBufferInfo.size); encodedData.position(videoBufferInfo.offset); encodedData.get(csd); ByteBuffer sps = null; ByteBuffer pps = null; for (int a = videoBufferInfo.size - 1; a >= 0; a--) { if (a > 3) { if (csd[a] == 1 && csd[a - 1] == 0 && csd[a - 2] == 0 && csd[a - 3] == 0) { sps = ByteBuffer.allocate(a - 3); pps = ByteBuffer.allocate(videoBufferInfo.size - (a - 3)); sps.put(csd, 0, a - 3).position(0); pps.put(csd, a - 3, videoBufferInfo.size - (a - 3)).position(0); break; } } else { break; } } MediaFormat newFormat = MediaFormat.createVideoFormat("video/avc", videoWidth, videoHeight); if (sps != null && pps != null) { newFormat.setByteBuffer("csd-0", sps); newFormat.setByteBuffer("csd-1", pps); } videoTrackIndex = mediaMuxer.addTrack(newFormat, false); } } videoEncoder.releaseOutputBuffer(encoderStatus, false); if ((videoBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { break; } } } if (Build.VERSION.SDK_INT < 21) { encoderOutputBuffers = audioEncoder.getOutputBuffers(); } boolean encoderOutputAvailable = true; while (true) { int encoderStatus = audioEncoder.dequeueOutputBuffer(audioBufferInfo, 0); if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) { if (!endOfStream || !running && sendWhenDone == 0) { break; } } else if (encoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) { if (Build.VERSION.SDK_INT < 21) { encoderOutputBuffers = audioEncoder.getOutputBuffers(); } } else if (encoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { MediaFormat newFormat = audioEncoder.getOutputFormat(); if (audioTrackIndex == -5) { audioTrackIndex = mediaMuxer.addTrack(newFormat, true); } } else if (encoderStatus >= 0) { ByteBuffer encodedData; if (Build.VERSION.SDK_INT < 21) { encodedData = encoderOutputBuffers[encoderStatus]; } else { encodedData = audioEncoder.getOutputBuffer(encoderStatus); } if (encodedData == null) { throw new RuntimeException("encoderOutputBuffer " + encoderStatus + " was null"); } if ((audioBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) { audioBufferInfo.size = 0; } if (audioBufferInfo.size != 0) { long availableSize = mediaMuxer.writeSampleData(audioTrackIndex, encodedData, audioBufferInfo, false); if (availableSize != 0) { didWriteData(videoFile, availableSize, false); } } audioEncoder.releaseOutputBuffer(encoderStatus, false); if ((audioBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { break; } } } } @Override protected void finalize() throws Throwable { try { if (eglDisplay != EGL14.EGL_NO_DISPLAY) { EGL14.eglMakeCurrent(eglDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT); EGL14.eglDestroyContext(eglDisplay, eglContext); EGL14.eglReleaseThread(); EGL14.eglTerminate(eglDisplay); eglDisplay = EGL14.EGL_NO_DISPLAY; eglContext = EGL14.EGL_NO_CONTEXT; eglConfig = null; } } finally { super.finalize(); } } } private String createFragmentShader(Size previewSize) { if (!allowBigSizeCamera() || Math.max(previewSize.getHeight(), previewSize.getWidth()) * 0.7f < MessagesController.getInstance(currentAccount).roundVideoSize) { return "#extension GL_OES_EGL_image_external : require\n" + "precision highp float;\n" + "varying vec2 vTextureCoord;\n" + "uniform float alpha;\n" + "uniform vec2 preview;\n" + "uniform vec2 resolution;\n" + "uniform samplerExternalOES sTexture;\n" + "void main() {\n" + " vec4 textColor = texture2D(sTexture, vTextureCoord);\n" + " vec2 coord = resolution * 0.5;\n" + " float radius = 0.51 * resolution.x;\n" + " float d = length(coord - gl_FragCoord.xy) - radius;\n" + " float t = clamp(d, 0.0, 1.0);\n" + " vec3 color = mix(textColor.rgb, vec3(1, 1, 1), t);\n" + " gl_FragColor = vec4(color * alpha, alpha);\n" + "}\n"; } //apply box blur return "#extension GL_OES_EGL_image_external : require\n" + "precision highp float;\n" + "varying vec2 vTextureCoord;\n" + "uniform vec2 resolution;\n" + "uniform vec2 preview;\n" + "uniform float alpha;\n" + "uniform samplerExternalOES sTexture;\n" + "void main() {\n" + " vec2 coord = resolution * 0.5;\n" + " float radius = 0.51 * resolution.x;\n" + " float d = length(coord - gl_FragCoord.xy) - radius;\n" + " float t = clamp(d, 0.0, 1.0);\n" + " if (t == 0.0) {\n" + " float pixelSizeX = 1.0 / preview.x;\n" + " float pixelSizeY = 1.0 / preview.y;\n" + " vec3 accumulation = vec3(0);\n" + " for (float x = 0.0; x < 2.0; x++){\n" + " for (float y = 0.0; y < 2.0; y++){\n" + " accumulation += texture2D(sTexture, vTextureCoord + vec2(x * pixelSizeX, y * pixelSizeY)).xyz;\n" + " }\n" + " }\n" + " vec4 textColor = vec4(accumulation / vec3(4, 4, 4), 1);\n" + " gl_FragColor = textColor * alpha;\n" + " } else {\n" + " gl_FragColor = vec4(1, 1, 1, alpha);\n" + " }\n" + "}\n"; } public class InstantViewCameraContainer extends FrameLayout { ImageReceiver imageReceiver; float imageProgress; public InstantViewCameraContainer(Context context) { super(context); InstantCameraView.this.setWillNotDraw(false); } public void setImageReceiver(ImageReceiver imageReceiver) { if (this.imageReceiver == null) { imageProgress = 0; } this.imageReceiver = imageReceiver; invalidate(); } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); if (imageProgress != 1f) { imageProgress += 16 / 250.0f; if (imageProgress > 1f) { imageProgress = 1f; } invalidate(); } if (imageReceiver != null) { canvas.save(); if (imageReceiver.getImageWidth() != textureViewSize) { float s = textureViewSize / imageReceiver.getImageWidth(); canvas.scale(s, s); } canvas.translate(-imageReceiver.getImageX(), -imageReceiver.getImageY()); float oldAlpha = imageReceiver.getAlpha(); imageReceiver.setAlpha(imageProgress); imageReceiver.draw(canvas); imageReceiver.setAlpha(oldAlpha); canvas.restore(); } } } @Override public boolean onTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN && baseFragment != null) { if (videoPlayer != null) { boolean mute = !videoPlayer.isMuted(); videoPlayer.setMute(mute); if (muteAnimation != null) { muteAnimation.cancel(); } muteAnimation = new AnimatorSet(); muteAnimation.playTogether( ObjectAnimator.ofFloat(muteImageView, View.ALPHA, mute ? 1.0f : 0.0f), ObjectAnimator.ofFloat(muteImageView, View.SCALE_X, mute ? 1.0f : 0.5f), ObjectAnimator.ofFloat(muteImageView, View.SCALE_Y, mute ? 1.0f : 0.5f)); muteAnimation.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (animation.equals(muteAnimation)) { muteAnimation = null; } } }); muteAnimation.setDuration(180); muteAnimation.setInterpolator(new DecelerateInterpolator()); muteAnimation.start(); } else { //baseFragment.checkRecordLocked(false); } } if (ev.getActionMasked() == MotionEvent.ACTION_DOWN || ev.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN) { if (maybePinchToZoomTouchMode && !isInPinchToZoomTouchMode && ev.getPointerCount() == 2 && finishZoomTransition == null && recording) { pinchStartDistance = (float) Math.hypot(ev.getX(1) - ev.getX(0), ev.getY(1) - ev.getY(0)); pinchScale = 1f; pointerId1 = ev.getPointerId(0); pointerId2 = ev.getPointerId(1); isInPinchToZoomTouchMode = true; } if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) { AndroidUtilities.rectTmp.set(cameraContainer.getX(), cameraContainer.getY(), cameraContainer.getX() + cameraContainer.getMeasuredWidth(), cameraContainer.getY() + cameraContainer.getMeasuredHeight()); maybePinchToZoomTouchMode = AndroidUtilities.rectTmp.contains(ev.getX(), ev.getY()); } return true; } else if (ev.getActionMasked() == MotionEvent.ACTION_MOVE && isInPinchToZoomTouchMode) { int index1 = -1; int index2 = -1; for (int i = 0; i < ev.getPointerCount(); i++) { if (pointerId1 == ev.getPointerId(i)) { index1 = i; } if (pointerId2 == ev.getPointerId(i)) { index2 = i; } } if (index1 == -1 || index2 == -1) { isInPinchToZoomTouchMode = false; finishZoom(); return false; } pinchScale = (float) Math.hypot(ev.getX(index2) - ev.getX(index1), ev.getY(index2) - ev.getY(index1)) / pinchStartDistance; float zoom = Math.min(1f, Math.max(0, pinchScale - 1f)); cameraSession.setZoom(zoom); } else if ((ev.getActionMasked() == MotionEvent.ACTION_UP || (ev.getActionMasked() == MotionEvent.ACTION_POINTER_UP && checkPointerIds(ev)) || ev.getActionMasked() == MotionEvent.ACTION_CANCEL) && isInPinchToZoomTouchMode) { isInPinchToZoomTouchMode = false; finishZoom(); } return true; } ValueAnimator finishZoomTransition; public void finishZoom() { if (finishZoomTransition != null) { return; } float zoom = Math.min(1f, Math.max(0, pinchScale - 1f)); if (zoom > 0f) { finishZoomTransition = ValueAnimator.ofFloat(zoom, 0); finishZoomTransition.addUpdateListener(valueAnimator -> { if (cameraSession != null) { cameraSession.setZoom((float) valueAnimator.getAnimatedValue()); } }); finishZoomTransition.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (finishZoomTransition != null) { finishZoomTransition = null; } } }); finishZoomTransition.setDuration(350); finishZoomTransition.setInterpolator(CubicBezierInterpolator.DEFAULT); finishZoomTransition.start(); } } }
flyun/chatAir
TMessagesProj/src/main/java/org/telegram/ui/Components/InstantCameraView.java
41,649
/* * Copyright 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ package org.webrtc; import androidx.annotation.Nullable; /** * Java wrapper of native AndroidVideoTrackSource. */ public class VideoSource extends MediaSource { /** Simple aspect ratio clas for use in constraining output format. */ public static class AspectRatio { public static final AspectRatio UNDEFINED = new AspectRatio(/* width= */ 0, /* height= */ 0); public final int width; public final int height; public AspectRatio(int width, int height) { this.width = width; this.height = height; } } private final NativeAndroidVideoTrackSource nativeAndroidVideoTrackSource; private final Object videoProcessorLock = new Object(); @Nullable private VideoProcessor videoProcessor; private boolean isCapturerRunning; private final CapturerObserver capturerObserver = new CapturerObserver() { @Override public void onCapturerStarted(boolean success) { nativeAndroidVideoTrackSource.setState(success); synchronized (videoProcessorLock) { isCapturerRunning = success; if (videoProcessor != null) { videoProcessor.onCapturerStarted(success); } } } @Override public void onCapturerStopped() { nativeAndroidVideoTrackSource.setState(/* isLive= */ false); synchronized (videoProcessorLock) { isCapturerRunning = false; if (videoProcessor != null) { videoProcessor.onCapturerStopped(); } } } @Override public void onFrameCaptured(VideoFrame frame) { final VideoProcessor.FrameAdaptationParameters parameters = nativeAndroidVideoTrackSource.adaptFrame(frame); synchronized (videoProcessorLock) { if (videoProcessor != null) { videoProcessor.onFrameCaptured(frame, parameters); return; } } VideoFrame adaptedFrame = VideoProcessor.applyFrameAdaptationParameters(frame, parameters); if (adaptedFrame != null) { nativeAndroidVideoTrackSource.onFrameCaptured(adaptedFrame); adaptedFrame.release(); } } }; public VideoSource(long nativeSource) { super(nativeSource); this.nativeAndroidVideoTrackSource = new NativeAndroidVideoTrackSource(nativeSource); } /** * Calling this function will cause frames to be scaled down to the requested resolution. Also, * frames will be cropped to match the requested aspect ratio, and frames will be dropped to match * the requested fps. The requested aspect ratio is orientation agnostic and will be adjusted to * maintain the input orientation, so it doesn't matter if e.g. 1280x720 or 720x1280 is requested. */ public void adaptOutputFormat(int width, int height, int fps) { final int maxSide = Math.max(width, height); final int minSide = Math.min(width, height); adaptOutputFormat(maxSide, minSide, minSide, maxSide, fps); } /** * Same as above, but allows setting two different target resolutions depending on incoming * frame orientation. This gives more fine-grained control and can e.g. be used to force landscape * video to be cropped to portrait video. */ public void adaptOutputFormat( int landscapeWidth, int landscapeHeight, int portraitWidth, int portraitHeight, int fps) { adaptOutputFormat(new AspectRatio(landscapeWidth, landscapeHeight), /* maxLandscapePixelCount= */ landscapeWidth * landscapeHeight, new AspectRatio(portraitWidth, portraitHeight), /* maxPortraitPixelCount= */ portraitWidth * portraitHeight, fps); } /** Same as above, with even more control as each constraint is optional. */ public void adaptOutputFormat(AspectRatio targetLandscapeAspectRatio, @Nullable Integer maxLandscapePixelCount, AspectRatio targetPortraitAspectRatio, @Nullable Integer maxPortraitPixelCount, @Nullable Integer maxFps) { nativeAndroidVideoTrackSource.adaptOutputFormat(targetLandscapeAspectRatio, maxLandscapePixelCount, targetPortraitAspectRatio, maxPortraitPixelCount, maxFps); } public void setIsScreencast(boolean isScreencast) { nativeAndroidVideoTrackSource.setIsScreencast(isScreencast); } /** * Hook for injecting a custom video processor before frames are passed onto WebRTC. The frames * will be cropped and scaled depending on CPU and network conditions before they are passed to * the video processor. Frames will be delivered to the video processor on the same thread they * are passed to this object. The video processor is allowed to deliver the processed frames * back on any thread. */ public void setVideoProcessor(@Nullable VideoProcessor newVideoProcessor) { synchronized (videoProcessorLock) { if (videoProcessor != null) { videoProcessor.setSink(/* sink= */ null); if (isCapturerRunning) { videoProcessor.onCapturerStopped(); } } videoProcessor = newVideoProcessor; if (newVideoProcessor != null) { newVideoProcessor.setSink( (frame) -> runWithReference(() -> nativeAndroidVideoTrackSource.onFrameCaptured(frame))); if (isCapturerRunning) { newVideoProcessor.onCapturerStarted(/* success= */ true); } } } } public CapturerObserver getCapturerObserver() { return capturerObserver; } /** Returns a pointer to webrtc::VideoTrackSourceInterface. */ long getNativeVideoTrackSource() { return getNativeMediaSource(); } @Override public void dispose() { setVideoProcessor(/* newVideoProcessor= */ null); super.dispose(); } }
NekoX-Dev/NekoX
TMessagesProj/src/main/java/org/webrtc/VideoSource.java
41,650
// Copyright 2019 The MediaPipe Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.mediapipe.framework; import com.google.common.base.Preconditions; import com.google.common.flogger.FluentLogger; import com.google.mediapipe.framework.ProtoUtil.SerializedMessage; import com.google.protobuf.Internal; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.MessageLite; import com.google.protobuf.Parser; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; /** * Converts the {@link Packet} to java accessible data types. * * <p>{@link Packet} is a thin java wrapper for the native MediaPipe packet. This class provides the * extendable conversion needed to access the data in the packet. * * <p>Note that it is still the developer's responsibility to interpret the data correctly. */ public final class PacketGetter { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** Helper class for a list of exactly two Packets. */ public static class PacketPair { public PacketPair(Packet first, Packet second) { this.first = first; this.second = second; } final Packet first; final Packet second; } /** * Returns the {@link Packet} that held in the reference packet. * * <p>Note: release the returned packet after use. */ public static Packet getPacketFromReference(final Packet referencePacket) { return Packet.create(nativeGetPacketFromReference(referencePacket.getNativeHandle())); } /** * The {@link Packet} contains a pair of packets, return both of them. * * <p>Note: release the packets in the pair after use. * * @param packet A MediaPipe packet that contains a pair of packets. */ public static PacketPair getPairOfPackets(final Packet packet) { long[] handles = nativeGetPairPackets(packet.getNativeHandle()); return new PacketPair(Packet.create(handles[0]), Packet.create(handles[1])); } /** * Returns a list of packets that are contained in The {@link Packet}. * * <p>Note: release the packets in the list after use. * * @param packet A MediaPipe packet that contains a vector of packets. */ public static List<Packet> getVectorOfPackets(final Packet packet) { long[] handles = nativeGetVectorPackets(packet.getNativeHandle()); List<Packet> packets = new ArrayList<>(handles.length); for (long handle : handles) { packets.add(Packet.create(handle)); } return packets; } public static short getInt16(final Packet packet) { return nativeGetInt16(packet.getNativeHandle()); } public static int getInt32(final Packet packet) { return nativeGetInt32(packet.getNativeHandle()); } public static long getInt64(final Packet packet) { return nativeGetInt64(packet.getNativeHandle()); } public static float getFloat32(final Packet packet) { return nativeGetFloat32(packet.getNativeHandle()); } public static double getFloat64(final Packet packet) { return nativeGetFloat64(packet.getNativeHandle()); } public static boolean getBool(final Packet packet) { return nativeGetBool(packet.getNativeHandle()); } public static String getString(final Packet packet) { return nativeGetString(packet.getNativeHandle()); } public static byte[] getBytes(final Packet packet) { return nativeGetBytes(packet.getNativeHandle()); } public static byte[] getProtoBytes(final Packet packet) { return nativeGetProtoBytes(packet.getNativeHandle()); } public static <T extends MessageLite> T getProto(final Packet packet, T defaultInstance) throws InvalidProtocolBufferException { SerializedMessage result = new SerializedMessage(); nativeGetProto(packet.getNativeHandle(), result); return ProtoUtil.unpack(result, defaultInstance); } public static <T extends MessageLite> T getProto(final Packet packet, Parser<T> messageParser) { SerializedMessage result = new SerializedMessage(); nativeGetProto(packet.getNativeHandle(), result); try { return messageParser.parseFrom(result.value); } catch (InvalidProtocolBufferException e) { throw new IllegalArgumentException(e); } } /** * @deprecated {@link #getProto(Packet, MessageLite)} is safer to use in obfuscated builds. */ @Deprecated public static <T extends MessageLite> T getProto(final Packet packet, Class<T> clazz) throws InvalidProtocolBufferException { return getProto(packet, Internal.getDefaultInstance(clazz)); } public static short[] getInt16Vector(final Packet packet) { return nativeGetInt16Vector(packet.getNativeHandle()); } public static int[] getInt32Vector(final Packet packet) { return nativeGetInt32Vector(packet.getNativeHandle()); } public static long[] getInt64Vector(final Packet packet) { return nativeGetInt64Vector(packet.getNativeHandle()); } public static float[] getFloat32Vector(final Packet packet) { return nativeGetFloat32Vector(packet.getNativeHandle()); } public static double[] getFloat64Vector(final Packet packet) { return nativeGetFloat64Vector(packet.getNativeHandle()); } public static <T> List<T> getProtoVector(final Packet packet, Parser<T> messageParser) { byte[][] protoVector = nativeGetProtoVector(packet.getNativeHandle()); Preconditions.checkNotNull( protoVector, "Vector of protocol buffer objects should not be null!"); try { List<T> parsedMessageList = new ArrayList<>(); for (byte[] message : protoVector) { T parsedMessage = messageParser.parseFrom(message); parsedMessageList.add(parsedMessage); } return parsedMessageList; } catch (InvalidProtocolBufferException e) { throw new IllegalArgumentException(e); } } public static <T extends MessageLite> List<T> getProtoVector( final Packet packet, T defaultInstance) { @SuppressWarnings("unchecked") Parser<T> parser = (Parser<T>) defaultInstance.getParserForType(); return getProtoVector(packet, parser); } public static int getImageWidth(final Packet packet) { return nativeGetImageWidth(packet.getNativeHandle()); } public static int getImageHeight(final Packet packet) { return nativeGetImageHeight(packet.getNativeHandle()); } public static int getImageNumChannels(final Packet packet) { return nativeGetImageNumChannels(packet.getNativeHandle()); } /** * Returns the native image buffer in ByteBuffer. It assumes the output buffer stores pixels * contiguously. It returns false if this assumption does not hold. * * <p>Note: this function does not assume the pixel format. * * <p>Use {@link ByteBuffer#allocateDirect} when allocating the buffer. */ public static boolean getImageData(final Packet packet, ByteBuffer buffer) { return nativeGetImageData(packet.getNativeHandle(), buffer); } /** * Returns a read-only view of the native image buffer as a ByteBuffer. As this method does not * copy the data, the result only remains valid while the backing MediaPipe image is on the stack. * The image must store contiguous pixels, otherwise the method returns {@code null}. * * <p>Note: this function does not assume the pixel format. */ @Nullable public static ByteBuffer getImageDataDirectly(final Packet packet) { return nativeGetImageDataDirect(packet.getNativeHandle()).asReadOnlyBuffer(); } /** Returns the size of Image list. This helps to determine size of allocated ByteBuffer array. */ public static int getImageListSize(final Packet packet) { return nativeGetImageListSize(packet.getNativeHandle()); } /** * Returns the width of first image in an image list. This helps to determine size of allocated * ByteBuffer array. */ public static int getImageWidthFromImageList(final Packet packet) { return nativeGetImageWidthFromImageList(packet.getNativeHandle()); } /** * Returns the height of first image in an image list. This helps to determine size of allocated * ByteBuffer array. */ public static int getImageHeightFromImageList(final Packet packet) { return nativeGetImageHeightFromImageList(packet.getNativeHandle()); } /** * Assign the native image buffer array in given ByteBuffer array. It assumes given ByteBuffer * array has the same size of image list packet, and assumes the output buffer stores pixels * contiguously. It returns false if this assumption does not hold. * * <p>If deepCopy is true, it assumes the given buffersArray has allocated the required size of * ByteBuffer to copy image data to. If false, the ByteBuffer will wrap the memory address of * MediaPipe ImageFrame of graph output, and the ByteBuffer data is available only when MediaPipe * graph is alive. * * <p>Note: this function does not assume the pixel format. */ public static boolean getImageList( final Packet packet, ByteBuffer[] buffersArray, boolean deepCopy) { return nativeGetImageList(packet.getNativeHandle(), buffersArray, deepCopy); } /** * Converts an RGB mediapipe image frame packet to an RGBA Byte buffer. * * <p>Use {@link ByteBuffer#allocateDirect} when allocating the buffer. */ public static boolean getRgbaFromRgb(final Packet packet, ByteBuffer buffer) { return nativeGetRgbaFromRgb(packet.getNativeHandle(), buffer); } /** * Converts the audio matrix data back into byte data. * * <p>The matrix is in column major order. */ public static byte[] getAudioByteData(final Packet packet) { return nativeGetAudioData(packet.getNativeHandle()); } /** * Audio data is in MediaPipe Matrix format. * * @return the number of channels in the data. */ public static int getAudioDataNumChannels(final Packet packet) { return nativeGetMatrixRows(packet.getNativeHandle()); } /** * Audio data is in MediaPipe Matrix format. * * @return the number of samples in the data. */ public static int getAudioDataNumSamples(final Packet packet) { return nativeGetMatrixCols(packet.getNativeHandle()); } /** * In addition to the data packet, mediapipe currently also has a separate audio header: {@code * mediapipe::TimeSeriesHeader}. * * @return the number of channel in the header packet. */ public static int getTimeSeriesHeaderNumChannels(final Packet packet) { return nativeGetTimeSeriesHeaderNumChannels(packet.getNativeHandle()); } /** * In addition to the data packet, mediapipe currently also has a separate audio header: {@code * mediapipe::TimeSeriesHeader}. * * @return the sampling rate in the header packet. */ public static double getTimeSeriesHeaderSampleRate(final Packet packet) { return nativeGetTimeSeriesHeaderSampleRate(packet.getNativeHandle()); } /** Gets the width in video header packet. */ public static int getVideoHeaderWidth(final Packet packet) { return nativeGetVideoHeaderWidth(packet.getNativeHandle()); } /** Gets the height in video header packet. */ public static int getVideoHeaderHeight(final Packet packet) { return nativeGetVideoHeaderHeight(packet.getNativeHandle()); } /** * Returns the float array data of the mediapipe Matrix. * * <p>Underlying packet stores the matrix as {@code ::mediapipe::Matrix}. */ public static float[] getMatrixData(final Packet packet) { return nativeGetMatrixData(packet.getNativeHandle()); } public static int getMatrixRows(final Packet packet) { return nativeGetMatrixRows(packet.getNativeHandle()); } public static int getMatrixCols(final Packet packet) { return nativeGetMatrixCols(packet.getNativeHandle()); } /** * Returns the GL texture name of the mediapipe::GpuBuffer. * * @deprecated use {@link #getTextureFrame} instead. */ @Deprecated public static int getGpuBufferName(final Packet packet) { return nativeGetGpuBufferName(packet.getNativeHandle()); } /** * Returns a {@link GraphTextureFrame} referencing a C++ mediapipe::GpuBuffer. * * <p>Note: in order for the application to be able to use the texture, its GL context must be * linked with MediaPipe's. This is ensured by calling {@link Graph#createGlRunner(String,long)} * with the native handle to the application's GL context as the second argument. * * <p>The returned GraphTextureFrame must be released by the caller. If this method is called * multiple times, each returned GraphTextureFrame is an independent reference to the underlying * texture data, and must be released individually. */ public static GraphTextureFrame getTextureFrame(final Packet packet) { return new GraphTextureFrame( nativeGetGpuBuffer(packet.getNativeHandle(), /* waitOnCpu= */ true), packet.getTimestamp()); } /** * Works like {@link #getTextureFrame(Packet)}, but does not insert a CPU wait for the texture's * producer before returning. Instead, a GPU wait will automatically occur when * GraphTextureFrame#getTextureName is called. */ public static GraphTextureFrame getTextureFrameDeferredSync(final Packet packet) { return new GraphTextureFrame( nativeGetGpuBuffer(packet.getNativeHandle(), /* waitOnCpu= */ false), packet.getTimestamp(), /* deferredSync= */ true); } private static native long nativeGetPacketFromReference(long nativePacketHandle); private static native long[] nativeGetPairPackets(long nativePacketHandle); private static native long[] nativeGetVectorPackets(long nativePacketHandle); private static native short nativeGetInt16(long nativePacketHandle); private static native int nativeGetInt32(long nativePacketHandle); private static native long nativeGetInt64(long nativePacketHandle); private static native float nativeGetFloat32(long nativePacketHandle); private static native double nativeGetFloat64(long nativePacketHandle); private static native boolean nativeGetBool(long nativePacketHandle); private static native String nativeGetString(long nativePacketHandle); private static native byte[] nativeGetBytes(long nativePacketHandle); private static native byte[] nativeGetProtoBytes(long nativePacketHandle); private static native void nativeGetProto(long nativePacketHandle, SerializedMessage result); private static native short[] nativeGetInt16Vector(long nativePacketHandle); private static native int[] nativeGetInt32Vector(long nativePacketHandle); private static native long[] nativeGetInt64Vector(long nativePacketHandle); private static native float[] nativeGetFloat32Vector(long nativePacketHandle); private static native double[] nativeGetFloat64Vector(long nativePacketHandle); private static native byte[][] nativeGetProtoVector(long nativePacketHandle); private static native int nativeGetImageWidth(long nativePacketHandle); private static native int nativeGetImageHeight(long nativePacketHandle); private static native int nativeGetImageNumChannels(long nativePacketHandle); private static native boolean nativeGetImageData(long nativePacketHandle, ByteBuffer buffer); private static native ByteBuffer nativeGetImageDataDirect(long nativePacketHandle); private static native int nativeGetImageListSize(long nativePacketHandle); private static native int nativeGetImageWidthFromImageList(long nativePacketHandle); private static native int nativeGetImageHeightFromImageList(long nativePacketHandle); private static native boolean nativeGetImageList( long nativePacketHandle, ByteBuffer[] bufferArray, boolean deepCopy); private static native boolean nativeGetRgbaFromRgb(long nativePacketHandle, ByteBuffer buffer); // Retrieves the values that are in the VideoHeader. private static native int nativeGetVideoHeaderWidth(long nativepackethandle); private static native int nativeGetVideoHeaderHeight(long nativepackethandle); // Retrieves the values that are in the mediapipe::TimeSeriesHeader. private static native int nativeGetTimeSeriesHeaderNumChannels(long nativepackethandle); private static native double nativeGetTimeSeriesHeaderSampleRate(long nativepackethandle); // Audio data in MediaPipe current uses MediaPipe Matrix format type. private static native byte[] nativeGetAudioData(long nativePacketHandle); // Native helper functions to access the MediaPipe Matrix data. private static native float[] nativeGetMatrixData(long nativePacketHandle); private static native int nativeGetMatrixRows(long nativePacketHandle); private static native int nativeGetMatrixCols(long nativePacketHandle); private static native int nativeGetGpuBufferName(long nativePacketHandle); private static native long nativeGetGpuBuffer(long nativePacketHandle, boolean waitOnCpu); private PacketGetter() {} }
google/mediapipe
mediapipe/java/com/google/mediapipe/framework/PacketGetter.java
41,651
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Processing project - http://processing.org Copyright (c) 2013-15 The Processing Foundation Copyright (c) 2010-13 Ben Fry and Casey Reas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package processing.app; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.awt.image.WritableRaster; import java.io.*; import java.util.*; import java.util.List; import javax.swing.*; import javax.swing.tree.*; import processing.app.contrib.ContributionManager; import processing.app.syntax.*; import processing.app.ui.Editor; import processing.app.ui.EditorException; import processing.app.ui.EditorState; import processing.app.ui.ExamplesFrame; import processing.app.ui.Recent; import processing.app.ui.SketchbookFrame; import processing.app.ui.Toolkit; import processing.core.PApplet; import processing.core.PConstants; public abstract class Mode { protected Base base; protected File folder; protected TokenMarker tokenMarker; protected Map<String, String> keywordToReference = new HashMap<>(); protected Settings theme; // protected Formatter formatter; // protected Tool formatter; // maps imported packages to their library folder protected Map<String, List<Library>> importToLibraryTable; // these menus are shared so that they needn't be rebuilt for all windows // each time a sketch is created, renamed, or moved. protected JMenu examplesMenu; // this is for the menubar, not the toolbar protected JMenu importMenu; protected ExamplesFrame examplesFrame; protected SketchbookFrame sketchbookFrame; // popup menu used for the toolbar protected JMenu toolbarMenu; protected File examplesFolder; protected File librariesFolder; protected File referenceFolder; // protected File examplesContribFolder; public List<Library> coreLibraries; public List<Library> contribLibraries; /** Library folder for core. (Used for OpenGL in particular.) */ protected Library coreLibrary; /** * ClassLoader used to retrieve classes for this mode. Useful if you want * to grab any additional classes that subclass what's in the mode folder. */ protected ClassLoader classLoader; static final int BACKGROUND_WIDTH = 1025; static final int BACKGROUND_HEIGHT = 65; protected Image backgroundImage; // public Mode(Base base, File folder) { // this(base, folder, base.getSketchbookLibrariesFolder()); // } public Mode(Base base, File folder) { this.base = base; this.folder = folder; tokenMarker = createTokenMarker(); // Get paths for the libraries and examples in the mode folder examplesFolder = new File(folder, "examples"); librariesFolder = new File(folder, "libraries"); referenceFolder = new File(folder, "reference"); // rebuildToolbarMenu(); rebuildLibraryList(); // rebuildExamplesMenu(); try { for (File file : getKeywordFiles()) { loadKeywords(file); } } catch (IOException e) { Messages.showWarning("Problem loading keywords", "Could not load keywords file for " + getTitle() + " mode.", e); } } /** * To add additional keywords, or to grab them from another mode, override * this function. If your mode has no keywords, return a zero length array. */ public File[] getKeywordFiles() { return new File[] { new File(folder, "keywords.txt") }; } protected void loadKeywords(File keywordFile) throws IOException { // overridden for Python, where # is an actual keyword loadKeywords(keywordFile, "#"); } protected void loadKeywords(File keywordFile, String commentPrefix) throws IOException { BufferedReader reader = PApplet.createReader(keywordFile); String line = null; while ((line = reader.readLine()) != null) { if (!line.trim().startsWith(commentPrefix)) { // Was difficult to make sure that mode authors were properly doing // tab-separated values. By definition, there can't be additional // spaces inside a keyword (or filename), so just splitting on tokens. String[] pieces = PApplet.splitTokens(line); if (pieces.length >= 2) { String keyword = pieces[0]; String coloring = pieces[1]; if (coloring.length() > 0) { tokenMarker.addColoring(keyword, coloring); } if (pieces.length == 3) { String htmlFilename = pieces[2]; if (htmlFilename.length() > 0) { // if the file is for the version with parens, // add a paren to the keyword if (htmlFilename.endsWith("_")) { keyword += "_"; } // Allow the bare size() command to override the lookup // for StringList.size() and others, but not vice-versa. // https://github.com/processing/processing/issues/4224 boolean seen = keywordToReference.containsKey(keyword); if (!seen || (seen && keyword.equals(htmlFilename))) { keywordToReference.put(keyword, htmlFilename); } } } } } } reader.close(); } public void setClassLoader(ClassLoader loader) { this.classLoader = loader; } public ClassLoader getClassLoader() { return classLoader; } /** * Setup additional elements that are only required when running with a GUI, * rather than from the command-line. Note that this will not be called when * the Mode is used from the command line (because Base will be null). */ public void setupGUI() { try { // First load the default theme data for the whole PDE. theme = new Settings(Platform.getContentFile("lib/theme.txt")); // The mode-specific theme.txt file should only contain additions, // and in extremely rare cases, it might override entries from the // main theme. Do not override for style changes unless they are // objectively necessary for your Mode. File modeTheme = new File(folder, "theme/theme.txt"); if (modeTheme.exists()) { // Override the built-in settings with what the theme provides theme.load(modeTheme); } // Against my better judgment, adding the ability to override themes // https://github.com/processing/processing/issues/5445 File sketchbookTheme = new File(Base.getSketchbookFolder(), "theme.txt"); if (sketchbookTheme.exists()) { theme.load(sketchbookTheme); } // other things that have to be set explicitly for the defaults theme.setColor("run.window.bgcolor", SystemColor.control); } catch (IOException e) { Messages.showError("Problem loading theme.txt", "Could not load theme.txt, please re-install Processing", e); } } public File getContentFile(String path) { return new File(folder, path); } public InputStream getContentStream(String path) throws FileNotFoundException { return new FileInputStream(getContentFile(path)); } /** * Add files to a folder to create an empty sketch. This can be overridden * to add template files to a sketch for Modes that need them. * * @param sketchFolder the directory where the new sketch should live * @param sketchName the name of the new sketch * @return the main file for the sketch to be opened via handleOpen() * @throws IOException if the file somehow already exists */ public File addTemplateFiles(File sketchFolder, String sketchName) throws IOException { // Make an empty .pde file File newbieFile = new File(sketchFolder, sketchName + "." + getDefaultExtension()); try { // First see if the user has overridden the default template File templateFolder = checkSketchbookTemplate(); // Next see if the Mode has its own template if (templateFolder == null) { templateFolder = getTemplateFolder(); } if (templateFolder.exists()) { Util.copyDir(templateFolder, sketchFolder); File templateFile = new File(sketchFolder, "sketch." + getDefaultExtension()); if (!templateFile.renameTo(newbieFile)) { System.err.println("Error while assigning the sketch template."); } } else { if (!newbieFile.createNewFile()) { System.err.println(newbieFile + " already exists."); } } } catch (Exception e) { // just spew out this error and try to recover below e.printStackTrace(); } return newbieFile; } /** * See if the user has their own template for this Mode. If the default * extension is "pde", this will look for a file called sketch.pde to use * as the template for all sketches. */ protected File checkSketchbookTemplate() { File user = new File(Base.getSketchbookTemplatesFolder(), getTitle()); if (user.exists()) { File template = new File(user, "sketch." + getDefaultExtension()); if (template.exists() && template.canRead()) { return user; } } return null; } public File getTemplateFolder() { return getContentFile("template"); } /** * Return the pretty/printable/menu name for this mode. This is separate from * the single word name of the folder that contains this mode. It could even * have spaces, though that might result in sheer madness or total mayhem. */ abstract public String getTitle(); /** * Get an identifier that can be used to resurrect this mode and connect it * to a sketch. Using this instead of getTitle() because there might be name * clashes with the titles, but there should not be once the actual package, * et al. is included. * @return full name (package + class name) for this mode. */ public String getIdentifier() { return getClass().getCanonicalName(); } /** * Create a new editor associated with this mode. */ abstract public Editor createEditor(Base base, String path, EditorState state) throws EditorException; /** * Get the folder where this mode is stored. * @since 3.0a3 */ public File getFolder() { return folder; } public File getExamplesFolder() { return examplesFolder; } public File getLibrariesFolder() { return librariesFolder; } public File getReferenceFolder() { return referenceFolder; } public void rebuildLibraryList() { //new Exception("Rebuilding library list").printStackTrace(System.out); // reset the table mapping imports to libraries Map<String, List<Library>> newTable = new HashMap<>(); Library core = getCoreLibrary(); if (core != null) { core.addPackageList(newTable); } coreLibraries = Library.list(librariesFolder); File contribLibrariesFolder = Base.getSketchbookLibrariesFolder(); contribLibraries = Library.list(contribLibrariesFolder); // Check to see if video and sound are installed and move them // from the contributed list to the core list. List<Library> foundationLibraries = new ArrayList<>(); for (Library lib : contribLibraries) { if (lib.isFoundation()) { foundationLibraries.add(lib); } } coreLibraries.addAll(foundationLibraries); contribLibraries.removeAll(foundationLibraries); for (Library lib : coreLibraries) { lib.addPackageList(newTable); } for (Library lib : contribLibraries) { lib.addPackageList(newTable); } // Make this Map thread-safe importToLibraryTable = Collections.unmodifiableMap(newTable); if (base != null) { base.getEditors().forEach(Editor::librariesChanged); } } public Library getCoreLibrary() { return null; } public Library getLibrary(String pkgName) throws SketchException { List<Library> libraries = importToLibraryTable.get(pkgName); if (libraries == null) { return null; } else if (libraries.size() > 1) { String primary = "More than one library is competing for this sketch."; String secondary = "The import " + pkgName + " points to multiple libraries:<br>"; for (Library library : libraries) { String location = library.getPath(); if (location.startsWith(getLibrariesFolder().getAbsolutePath())) { location = "part of Processing"; } secondary += "<b>" + library.getName() + "</b> (" + location + ")<br>"; } secondary += "Extra libraries need to be removed before this sketch can be used."; Messages.showWarningTiered("Duplicate Library Problem", primary, secondary, null); throw new SketchException("Duplicate libraries found for " + pkgName + "."); } else { return libraries.get(0); } } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . // abstract public EditorToolbar createToolbar(Editor editor); public JMenu getToolbarMenu() { if (toolbarMenu == null) { // toolbarMenu = new JMenu(); rebuildToolbarMenu(); } return toolbarMenu; } public void insertToolbarRecentMenu() { if (toolbarMenu == null) { rebuildToolbarMenu(); } else { toolbarMenu.insert(Recent.getToolbarMenu(), 1); } } public void removeToolbarRecentMenu() { toolbarMenu.remove(Recent.getToolbarMenu()); } protected void rebuildToolbarMenu() { //JMenu menu) { JMenuItem item; if (toolbarMenu == null) { toolbarMenu = new JMenu(); } else { toolbarMenu.removeAll(); } //System.out.println("rebuilding toolbar menu"); // Add the single "Open" item item = Toolkit.newJMenuItem("Open...", 'O'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleOpenPrompt(); } }); toolbarMenu.add(item); insertToolbarRecentMenu(); item = Toolkit.newJMenuItemShift("Examples...", 'O'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showExamplesFrame(); } }); toolbarMenu.add(item); item = new JMenuItem(Language.text("examples.add_examples")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ContributionManager.openExamples(); } }); toolbarMenu.add(item); // Add a list of all sketches and subfolders toolbarMenu.addSeparator(); base.populateSketchbookMenu(toolbarMenu); // boolean found = false; // try { // found = base.addSketches(toolbarMenu, base.getSketchbookFolder(), true); // } catch (IOException e) { // Base.showWarning("Sketchbook Toolbar Error", // "An error occurred while trying to list the sketchbook.", e); // } // if (!found) { // JMenuItem empty = new JMenuItem("(empty)"); // empty.setEnabled(false); // toolbarMenu.add(empty); // } } protected int importMenuIndex = -1; /** * Rather than re-building the library menu for every open sketch (very slow * and prone to bugs when updating libs, particularly with the contribs mgr), * share a single instance across all windows. * @since 3.0a6 * @param sketchMenu the Sketch menu that's currently active */ public void removeImportMenu(JMenu sketchMenu) { JMenu importMenu = getImportMenu(); //importMenuIndex = sketchMenu.getComponentZOrder(importMenu); importMenuIndex = Toolkit.getMenuItemIndex(sketchMenu, importMenu); sketchMenu.remove(importMenu); } /** * Re-insert the Import Library menu. Added function so that other modes * need not have an 'import' menu. * @since 3.0a6 * @param sketchMenu the Sketch menu that's currently active */ public void insertImportMenu(JMenu sketchMenu) { // hard-coded as 4 in 3.0a5, change to 5 for 3.0a6, but... yuck //sketchMenu.insert(mode.getImportMenu(), 4); // This is -1 on when the editor window is first shown, but that's fine // because the import menu has just been added in the Editor constructor. if (importMenuIndex != -1) { sketchMenu.insert(getImportMenu(), importMenuIndex); } } public JMenu getImportMenu() { if (importMenu == null) { rebuildImportMenu(); } return importMenu; } public void rebuildImportMenu() { //JMenu importMenu) { if (importMenu == null) { importMenu = new JMenu(Language.text("menu.library")); } else { //System.out.println("rebuilding import menu"); importMenu.removeAll(); } JMenuItem addLib = new JMenuItem(Language.text("menu.library.add_library")); addLib.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ContributionManager.openLibraries(); } }); importMenu.add(addLib); importMenu.addSeparator(); rebuildLibraryList(); ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { base.activeEditor.handleImportLibrary(e.getActionCommand()); } }; // try { // pw = new PrintWriter(new FileWriter(System.getProperty("user.home") + "/Desktop/libs.csv")); // } catch (IOException e1) { // e1.printStackTrace(); // } if (coreLibraries.size() == 0) { JMenuItem item = new JMenuItem(getTitle() + " " + Language.text("menu.library.no_core_libraries")); item.setEnabled(false); importMenu.add(item); } else { for (Library library : coreLibraries) { JMenuItem item = new JMenuItem(library.getName()); item.addActionListener(listener); // changed to library-name to facilitate specification of imports from properties file item.setActionCommand(library.getName()); importMenu.add(item); } } if (contribLibraries.size() != 0) { importMenu.addSeparator(); JMenuItem contrib = new JMenuItem(Language.text("menu.library.contributed")); contrib.setEnabled(false); importMenu.add(contrib); HashMap<String, JMenu> subfolders = new HashMap<>(); for (Library library : contribLibraries) { JMenuItem item = new JMenuItem(library.getName()); item.addActionListener(listener); // changed to library-name to facilitate specification if imports from properties file item.setActionCommand(library.getName()); String group = library.getGroup(); if (group != null) { JMenu subMenu = subfolders.get(group); if (subMenu == null) { subMenu = new JMenu(group); importMenu.add(subMenu); subfolders.put(group, subMenu); } subMenu.add(item); } else { importMenu.add(item); } } } } /** * Require examples to explicitly state that they're compatible with this * Mode before they're included. Helpful for Modes like p5js or Python * where the .java examples cannot be used. * @since 3.2 * @return true if an examples package must list this Mode's identifier */ public boolean requireExampleCompatibility() { return false; } /** * Override this to control the order of the first set of example folders * and how they appear in the examples window. */ public File[] getExampleCategoryFolders() { return examplesFolder.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return dir.isDirectory() && name.charAt(0) != '.'; } }); } public void rebuildExamplesFrame() { if (examplesFrame != null) { boolean visible = examplesFrame.isVisible(); Rectangle bounds = null; if (visible) { bounds = examplesFrame.getBounds(); examplesFrame.setVisible(false); examplesFrame.dispose(); } examplesFrame = null; if (visible) { showExamplesFrame(); examplesFrame.setBounds(bounds); } } } public void showExamplesFrame() { if (examplesFrame == null) { examplesFrame = new ExamplesFrame(base, this); } examplesFrame.setVisible(); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . public DefaultMutableTreeNode buildSketchbookTree() { DefaultMutableTreeNode sbNode = new DefaultMutableTreeNode(Language.text("sketchbook.tree")); try { base.addSketches(sbNode, Base.getSketchbookFolder(), false); } catch (IOException e) { e.printStackTrace(); } return sbNode; } /** Sketchbook has changed, update it on next viewing. */ public void rebuildSketchbookFrame() { if (sketchbookFrame != null) { boolean visible = sketchbookFrame.isVisible(); Rectangle bounds = null; if (visible) { bounds = sketchbookFrame.getBounds(); sketchbookFrame.setVisible(false); sketchbookFrame.dispose(); } sketchbookFrame = null; if (visible) { showSketchbookFrame(); sketchbookFrame.setBounds(bounds); } } } public void showSketchbookFrame() { if (sketchbookFrame == null) { sketchbookFrame = new SketchbookFrame(base, this); } sketchbookFrame.setVisible(); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /** * Get an ImageIcon object from the Mode folder. * Or when prefixed with /lib, load it from the main /lib folder. * @since 3.0a6 */ public ImageIcon loadIcon(String filename) { if (filename.startsWith("/lib/")) { return Toolkit.getLibIcon(filename.substring(5)); } File file = new File(folder, filename); if (!file.exists()) { // EditorConsole.systemErr.println("file does not exist: " + file.getAbsolutePath()); return null; } // EditorConsole.systemErr.println("found: " + file.getAbsolutePath()); return new ImageIcon(file.getAbsolutePath()); } /** * Get an image object from the mode folder. * Or when prefixed with /lib, load it from the main /lib folder. */ public Image loadImage(String filename) { ImageIcon icon = loadIcon(filename); if (icon != null) { return icon.getImage(); } return null; } public Image loadImageX(String filename) { final int res = Toolkit.highResImages() ? 2 : 1; return loadImage(filename + "-" + res + "x.png"); } // public EditorButton loadButton(String name) { // return new EditorButton(this, name); // } //public Settings getTheme() { // return theme; //} /** * Returns the HTML filename (including path prefix if necessary) * for this keyword, or null if it doesn't exist. */ public String lookupReference(String keyword) { return keywordToReference.get(keyword); } /** * Specialized version of getTokenMarker() that can be overridden to * provide different TokenMarker objects for different file types. * @since 3.2 * @param code the code for which we need a TokenMarker */ public TokenMarker getTokenMarker(SketchCode code) { return getTokenMarker(); } public TokenMarker getTokenMarker() { return tokenMarker; } protected TokenMarker createTokenMarker() { return new PdeTokenMarker(); } // abstract public Formatter createFormatter(); // public Formatter getFormatter() { // return formatter; // } // public Tool getFormatter() { // return formatter; // } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . // Get attributes/values from the theme.txt file. To discourage burying this // kind of information in code where it doesn't belong (and is difficult to // track down), these don't have a "default" option as a second parameter. /** @since 3.0a6 */ public String getString(String attribute) { return theme.get(attribute); } public boolean getBoolean(String attribute) { return theme.getBoolean(attribute); } public int getInteger(String attribute) { return theme.getInteger(attribute); } public Color getColor(String attribute) { return theme.getColor(attribute); } public Font getFont(String attribute) { return theme.getFont(attribute); } public SyntaxStyle getStyle(String attribute) { String str = Preferences.get("editor.token." + attribute + ".style"); if (str == null) { throw new IllegalArgumentException("No style found for " + attribute); } StringTokenizer st = new StringTokenizer(str, ","); String s = st.nextToken(); if (s.indexOf("#") == 0) s = s.substring(1); Color color = new Color(Integer.parseInt(s, 16)); s = st.nextToken(); boolean bold = (s.indexOf("bold") != -1); // boolean italic = (s.indexOf("italic") != -1); // return new SyntaxStyle(color, italic, bold); return new SyntaxStyle(color, bold); } public Image makeGradient(String attribute, int wide, int high) { int top = getColor(attribute + ".gradient.top").getRGB(); int bot = getColor(attribute + ".gradient.bottom").getRGB(); // float r1 = (top >> 16) & 0xff; // float g1 = (top >> 8) & 0xff; // float b1 = top & 0xff; // float r2 = (bot >> 16) & 0xff; // float g2 = (bot >> 8) & 0xff; // float b2 = bot & 0xff; BufferedImage outgoing = new BufferedImage(wide, high, BufferedImage.TYPE_INT_RGB); int[] row = new int[wide]; WritableRaster wr = outgoing.getRaster(); for (int i = 0; i < high; i++) { // Arrays.fill(row, (255 - (i + GRADIENT_TOP)) << 24); // int r = (int) PApplet.map(i, 0, high-1, r1, r2); int rgb = PApplet.lerpColor(top, bot, i / (float)(high-1), PConstants.RGB); Arrays.fill(row, rgb); // System.out.println(PApplet.hex(row[0])); wr.setDataElements(0, i, wide, 1, row); } // Graphics g = outgoing.getGraphics(); // for (int i = 0; i < steps; i++) { // g.setColor(new Color(1, 1, 1, 255 - (i + GRADIENT_TOP))); // //g.fillRect(0, i, EditorButton.DIM, 10); // g.drawLine(0, i, EditorButton.DIM, i); // } return outgoing; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . // Breaking out extension types in order to clean up the code, and make it // easier for other environments (like Arduino) to incorporate changes. /** * True if the specified extension should be hidden when shown on a tab. * For Processing, this is true for .pde files. (Broken out for subclasses.) * You can override this in your Mode subclass to handle it differently. */ public boolean hideExtension(String what) { return what.equals(getDefaultExtension()); } /** * True if the specified code has the default file extension. */ public boolean isDefaultExtension(SketchCode code) { return code.getExtension().equals(getDefaultExtension()); } /** * True if the specified extension is the default file extension. */ public boolean isDefaultExtension(String what) { return what.equals(getDefaultExtension()); } /** * @param f File to be checked against this mode's accepted extensions. * @return Whether or not the given file name features an extension supported by this mode. */ public boolean canEdit(final File f) { final int dot = f.getName().lastIndexOf('.'); if (dot < 0) { return false; } return validExtension(f.getName().substring(dot + 1)); } /** * Check this extension (no dots, please) against the list of valid * extensions. */ public boolean validExtension(String what) { String[] ext = getExtensions(); for (int i = 0; i < ext.length; i++) { if (ext[i].equals(what)) return true; } return false; } /** * Returns the default extension for this editor setup. */ abstract public String getDefaultExtension(); /** * Returns the appropriate file extension to use for auxilliary source files in a sketch. * For example, in a Java-mode sketch, auxilliary files should be name "Foo.java"; in * Python mode, they should be named "foo.py". * * <p>Modes that do not override this function will get the default behavior of returning the * default extension. */ public String getModuleExtension() { return getDefaultExtension(); } /** * Returns a String[] array of proper extensions. */ abstract public String[] getExtensions(); /** * Get array of file/directory names that needn't be copied during "Save As". */ abstract public String[] getIgnorable(); // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /** * Checks coreLibraries and contribLibraries for a library with the specified name * @param libName the name of the library to find * @return the Library or null if not found */ public Library findLibraryByName(String libName) { for (Library lib : this.coreLibraries) { if (libName.equals(lib.getName())) return lib; } for (Library lib : this.contribLibraries) { if (libName.equals(lib.getName())) return lib; } return null; } /** * Create a fresh applet/application folder if the 'delete target folder' * pref has been set in the preferences. */ public void prepareExportFolder(File targetFolder) { if (targetFolder != null) { // Nuke the old applet/application folder because it can cause trouble if (Preferences.getBoolean("export.delete_target_folder")) { if (targetFolder.exists()) { try { Platform.deleteFile(targetFolder); } catch (IOException e) { // ignore errors/continue; likely to be ok e.printStackTrace(); } } } // Create a fresh output folder (needed before preproc is run next) targetFolder.mkdirs(); } } // public void handleNew() { // base.handleNew(); // } // // // public void handleNewReplace() { // base.handleNewReplace(); // } // this is Java-specific, so keeping it in JavaMode // public String getSearchPath() { // return null; // } @Override public String toString() { return getTitle(); } }
processing/processing
app/src/processing/app/Mode.java
41,652
package processing.app; import java.io.*; import java.util.*; import processing.app.contrib.*; import processing.core.*; import processing.data.StringDict; import processing.data.StringList; public class Library extends LocalContribution { static final String[] platformNames = PConstants.platformNames; //protected File folder; // /path/to/shortname protected File libraryFolder; // shortname/library protected File examplesFolder; // shortname/examples protected File referenceFile; // shortname/reference/index.html /** * Subfolder for grouping libraries in a menu. Basic subfolder support * is provided so that some organization can be done in the import menu. * (This is the replacement for the "library compilation" type.) */ protected String group; /** Packages provided by this library. */ StringList packageList; /** Per-platform exports for this library. */ HashMap<String, String[]> exportList; /** Applet exports (cross-platform by definition). */ String[] appletExportList; /** Android exports (single platform for now, may not exist). */ String[] androidExportList; /** True if there are separate 32/64 bit for the specified platform index. */ boolean[] multipleArch = new boolean[platformNames.length]; /** * For runtime, the native library path for this platform. e.g. on Windows 64, * this might be the windows64 subfolder with the library. */ String nativeLibraryPath; static public final String propertiesFileName = "library.properties"; /** * Filter to pull out just files and none of the platform-specific * directories, and to skip export.txt. As of 2.0a2, other directories are * included, because we need things like the 'plugins' subfolder w/ video. */ static FilenameFilter standardFilter = new FilenameFilter() { public boolean accept(File dir, String name) { // skip .DS_Store files, .svn folders, etc if (name.charAt(0) == '.') return false; if (name.equals("CVS")) return false; if (name.equals("export.txt")) return false; File file = new File(dir, name); // return (!file.isDirectory()); if (file.isDirectory()) { if (name.equals("macosx")) return false; if (name.equals("macosx32")) return false; if (name.equals("macosx64")) return false; if (name.equals("windows")) return false; if (name.equals("windows32")) return false; if (name.equals("windows64")) return false; if (name.equals("linux")) return false; if (name.equals("linux32")) return false; if (name.equals("linux64")) return false; if (name.equals("linux-armv6hf")) return false; if (name.equals("linux-arm64")) return false; if (name.equals("android")) return false; } return true; } }; static FilenameFilter jarFilter = new FilenameFilter() { public boolean accept(File dir, String name) { if (name.charAt(0) == '.') return false; // skip ._blah.jar crap on OS X if (new File(dir, name).isDirectory()) return false; String lc = name.toLowerCase(); return lc.endsWith(".jar") || lc.endsWith(".zip"); } }; static public Library load(File folder) { try { return new Library(folder); // } catch (IgnorableException ig) { // Base.log(ig.getMessage()); } catch (Error err) { // Handles UnsupportedClassVersionError and others err.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } return null; } public Library(File folder) { this(folder, null); } private Library(File folder, String groupName) { super(folder); this.group = groupName; libraryFolder = new File(folder, "library"); examplesFolder = new File(folder, "examples"); referenceFile = new File(folder, "reference/index.html"); handle(); } /** * Handles all the Java-specific parsing for library handling. */ protected void handle() { File exportSettings = new File(libraryFolder, "export.txt"); StringDict exportTable = exportSettings.exists() ? Util.readSettings(exportSettings) : new StringDict(); exportList = new HashMap<>(); // get the list of files just in the library root String[] baseList = libraryFolder.list(standardFilter); // System.out.println("Loading " + name + "..."); // PApplet.println(baseList); String appletExportStr = exportTable.get("applet"); if (appletExportStr != null) { appletExportList = PApplet.splitTokens(appletExportStr, ", "); } else { appletExportList = baseList; } String androidExportStr = exportTable.get("android"); if (androidExportStr != null) { androidExportList = PApplet.splitTokens(androidExportStr, ", "); } else { androidExportList = baseList; } // for the host platform, need to figure out what's available File nativeLibraryFolder = libraryFolder; String hostPlatform = Platform.getName(); // System.out.println("1 native lib folder now " + nativeLibraryFolder); // see if there's a 'windows', 'macosx', or 'linux' folder File hostLibrary = new File(libraryFolder, hostPlatform); if (hostLibrary.exists()) { nativeLibraryFolder = hostLibrary; } // System.out.println("2 native lib folder now " + nativeLibraryFolder); // check for bit-specific version, e.g. on windows, check if there // is a window32 or windows64 folder (on windows) hostLibrary = new File(libraryFolder, hostPlatform + Platform.getNativeBits()); if (hostLibrary.exists()) { nativeLibraryFolder = hostLibrary; } // System.out.println("3 native lib folder now " + nativeLibraryFolder); if (hostPlatform.equals("linux") && System.getProperty("os.arch").equals("arm")) { hostLibrary = new File(libraryFolder, "linux-armv6hf"); if (hostLibrary.exists()) { nativeLibraryFolder = hostLibrary; } } if (hostPlatform.equals("linux") && System.getProperty("os.arch").equals("aarch64")) { hostLibrary = new File(libraryFolder, "linux-arm64"); if (hostLibrary.exists()) { nativeLibraryFolder = hostLibrary; } } // save that folder for later use nativeLibraryPath = nativeLibraryFolder.getAbsolutePath(); // for each individual platform that this library supports, figure out what's around for (int i = 1; i < platformNames.length; i++) { String platformName = platformNames[i]; String platformName32 = platformName + "32"; String platformName64 = platformName + "64"; String platformNameArmv6hf = platformName + "-armv6hf"; String platformNameArm64 = platformName + "-arm64"; // First check for things like 'application.macosx=' or 'application.windows32' in the export.txt file. // These will override anything in the platform-specific subfolders. String platformAll = exportTable.get("application." + platformName); String[] platformList = platformAll == null ? null : PApplet.splitTokens(platformAll, ", "); String platform32 = exportTable.get("application." + platformName + "32"); String[] platformList32 = platform32 == null ? null : PApplet.splitTokens(platform32, ", "); String platform64 = exportTable.get("application." + platformName + "64"); String[] platformList64 = platform64 == null ? null : PApplet.splitTokens(platform64, ", "); String platformArmv6hf = exportTable.get("application." + platformName + "-armv6hf"); String[] platformListArmv6hf = platformArmv6hf == null ? null : PApplet.splitTokens(platformArmv6hf, ", "); String platformArm64 = exportTable.get("application." + platformName + "-arm64"); String[] platformListArm64 = platformArm64 == null ? null : PApplet.splitTokens(platformArm64, ", "); // If nothing specified in the export.txt entries, look for the platform-specific folders. if (platformAll == null) { platformList = listPlatformEntries(libraryFolder, platformName, baseList); } if (platform32 == null) { platformList32 = listPlatformEntries(libraryFolder, platformName32, baseList); } if (platform64 == null) { platformList64 = listPlatformEntries(libraryFolder, platformName64, baseList); } if (platformListArmv6hf == null) { platformListArmv6hf = listPlatformEntries(libraryFolder, platformNameArmv6hf, baseList); } if (platformListArm64 == null) { platformListArm64 = listPlatformEntries(libraryFolder, platformNameArm64, baseList); } if (platformList32 != null || platformList64 != null || platformListArmv6hf != null || platformListArm64 != null) { multipleArch[i] = true; } // if there aren't any relevant imports specified or in their own folders, // then use the baseList (root of the library folder) as the default. if (platformList == null && platformList32 == null && platformList64 == null && platformListArmv6hf == null && platformListArm64 == null) { exportList.put(platformName, baseList); } else { // once we've figured out which side our bread is buttered on, save it. // (also concatenate the list of files in the root folder as well if (platformList != null) { exportList.put(platformName, platformList); } if (platformList32 != null) { exportList.put(platformName32, platformList32); } if (platformList64 != null) { exportList.put(platformName64, platformList64); } if (platformListArmv6hf != null) { exportList.put(platformNameArmv6hf, platformListArmv6hf); } if (platformListArm64 != null) { exportList.put(platformNameArm64, platformListArm64); } } } // for (String p : exportList.keySet()) { // System.out.println(p + " -> "); // PApplet.println(exportList.get(p)); // } // get the path for all .jar files in this code folder packageList = Util.packageListFromClassPath(getClassPath()); } /** * List who's inside a windows64, macosx, linux32, etc folder. */ static String[] listPlatformEntries(File libraryFolder, String folderName, String[] baseList) { File folder = new File(libraryFolder, folderName); if (folder.exists()) { String[] entries = folder.list(standardFilter); if (entries != null) { String[] outgoing = new String[entries.length + baseList.length]; for (int i = 0; i < entries.length; i++) { outgoing[i] = folderName + "/" + entries[i]; } // Copy the base libraries in there as well System.arraycopy(baseList, 0, outgoing, entries.length, baseList.length); return outgoing; } } return null; } static protected HashMap<String, Object> packageWarningMap = new HashMap<>(); /** * Add the packages provided by this library to the master list that maps * imports to specific libraries. * @param importToLibraryTable mapping from package names to Library objects */ // public void addPackageList(HashMap<String,Library> importToLibraryTable) { public void addPackageList(Map<String, List<Library>> importToLibraryTable) { // PApplet.println(packages); for (String pkg : packageList) { // pw.println(pkg + "\t" + libraryFolder.getAbsolutePath()); // PApplet.println(pkg + "\t" + getName()); // Library library = importToLibraryTable.get(pkg); List<Library> libraries = importToLibraryTable.get(pkg); if (libraries == null) { libraries = new ArrayList<>(); importToLibraryTable.put(pkg, libraries); } else { if (Base.DEBUG) { System.err.println("The library found in"); System.err.println(getPath()); System.err.println("conflicts with"); for (Library library : libraries) { System.err.println(library.getPath()); } System.err.println("which already define(s) the package " + pkg); System.err.println("If you have a line in your sketch that reads"); System.err.println("import " + pkg + ".*;"); System.err.println("Then you'll need to first remove one of those libraries."); System.err.println(); } } libraries.add(this); } } public boolean hasExamples() { return examplesFolder.exists(); } public File getExamplesFolder() { return examplesFolder; } public String getGroup() { return group; } public String getPath() { return folder.getAbsolutePath(); } public String getLibraryPath() { return libraryFolder.getAbsolutePath(); } public String getJarPath() { //return new File(folder, "library/" + name + ".jar").getAbsolutePath(); return new File(libraryFolder, folder.getName() + ".jar").getAbsolutePath(); } // this prepends a colon so that it can be appended to other paths safely public String getClassPath() { StringBuilder cp = new StringBuilder(); // PApplet.println(libraryFolder.getAbsolutePath()); // PApplet.println(libraryFolder.list()); String[] jarHeads = libraryFolder.list(jarFilter); for (String jar : jarHeads) { cp.append(File.pathSeparatorChar); cp.append(new File(libraryFolder, jar).getAbsolutePath()); } File nativeLibraryFolder = new File(nativeLibraryPath); if (!libraryFolder.equals(nativeLibraryFolder)) { jarHeads = new File(nativeLibraryPath).list(jarFilter); for (String jar : jarHeads) { cp.append(File.pathSeparatorChar); cp.append(new File(nativeLibraryPath, jar).getAbsolutePath()); } } //cp.setLength(cp.length() - 1); // remove the last separator return cp.toString(); } public String getNativePath() { // PApplet.println("native lib folder " + nativeLibraryPath); return nativeLibraryPath; } // public String[] getAppletExports() { // return appletExportList; // } protected File[] wrapFiles(String[] list) { File[] outgoing = new File[list.length]; for (int i = 0; i < list.length; i++) { outgoing[i] = new File(libraryFolder, list[i]); } return outgoing; } /** * Applet exports don't go by platform, since by their nature applets are * meant to be cross-platform. Technically, you could have a situation where * you want to export applet code for different platforms, but it's too * obscure a case that we're not interested in supporting it. */ public File[] getAppletExports() { return wrapFiles(appletExportList); } public File[] getApplicationExports(int platform, String variant) { String[] list = getApplicationExportList(platform, variant); return wrapFiles(list); } /** * Returns the necessary exports for the specified platform. * If no 32 or 64-bit version of the exports exists, it returns the version * that doesn't specify bit depth. */ public String[] getApplicationExportList(int platform, String variant) { String platformName = PConstants.platformNames[platform]; if (variant.equals("32")) { String[] pieces = exportList.get(platformName + "32"); if (pieces != null) return pieces; } else if (variant.equals("64")) { String[] pieces = exportList.get(platformName + "64"); if (pieces != null) return pieces; } else if (variant.equals("armv6hf")) { String[] pieces = exportList.get(platformName + "-armv6hf"); if (pieces != null) return pieces; } else if (variant.equals("arm64")) { String[] pieces = exportList.get(platformName + "-arm64"); if (pieces != null) return pieces; } return exportList.get(platformName); } public File[] getAndroidExports() { return wrapFiles(androidExportList); } // public boolean hasMultiplePlatforms() { // return false; // } public boolean hasMultipleArch(int platform) { return multipleArch[platform]; } public boolean supportsArch(int platform, String variant) { // If this is a universal library, or has no natives, then we're good. if (multipleArch[platform] == false) { return true; } return getApplicationExportList(platform, variant) != null; } static public boolean hasMultipleArch(int platform, List<Library> libraries) { return libraries.stream().anyMatch(library -> library.hasMultipleArch(platform)); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static protected FilenameFilter junkFolderFilter = new FilenameFilter() { public boolean accept(File dir, String name) { // skip .DS_Store files, .svn and .git folders, etc if (name.charAt(0) == '.') return false; if (name.equals("CVS")) return false; // old skool return new File(dir, name).isDirectory(); } }; static public List<File> discover(File folder) { List<File> libraries = new ArrayList<>(); String[] folderNames = folder.list(junkFolderFilter); // if a bad folder or unreadable, folderNames might be null if (folderNames != null) { // alphabetize list, since it's not always alpha order // replaced hella slow bubble sort with this feller for 0093 Arrays.sort(folderNames, String.CASE_INSENSITIVE_ORDER); // TODO some weirdness because ContributionType.LIBRARY.isCandidate() // handles some, but not all, of this [fry 200116] for (String potentialName : folderNames) { File baseFolder = new File(folder, potentialName); File libraryFolder = new File(baseFolder, "library"); File libraryJar = new File(libraryFolder, potentialName + ".jar"); // If a .jar file of the same prefix as the folder exists // inside the 'library' subfolder of the sketch if (libraryJar.exists()) { String sanityCheck = Sketch.sanitizeName(potentialName); if (sanityCheck.equals(potentialName)) { libraries.add(baseFolder); } else { final String mess = "The library \"" + potentialName + "\" cannot be used.\n" + "Library names must contain only basic letters and numbers.\n" + "(ASCII only and no spaces, and it cannot start with a number)"; Messages.showMessage("Ignoring bad library name", mess); continue; } } } } return libraries; } static public List<Library> list(File folder) { List<Library> libraries = new ArrayList<>(); List<File> librariesFolders = new ArrayList<>(); librariesFolders.addAll(discover(folder)); for (File baseFolder : librariesFolders) { libraries.add(new Library(baseFolder)); } /* // Support libraries inside of one level of subfolders? I believe this was // the compromise for supporting library groups, but probably a bad idea // because it's not compatible with the Manager. String[] folderNames = folder.list(junkFolderFilter); if (folderNames != null) { for (String subfolderName : folderNames) { File subfolder = new File(folder, subfolderName); if (!librariesFolders.contains(subfolder)) { List<File> discoveredLibFolders = discover(subfolder); for (File discoveredFolder : discoveredLibFolders) { libraries.add(new Library(discoveredFolder, subfolderName)); } } } } */ return libraries; } public ContributionType getType() { return ContributionType.LIBRARY; } /** * Returns the object stored in the referenceFile field, which contains an * instance of the file object representing the index file of the reference * * @return referenceFile */ public File getReferenceIndexFile() { return referenceFile; } /** * Tests whether the reference's index file indicated by referenceFile exists. * * @return true if and only if the file denoted by referenceFile exists; false * otherwise. */ public boolean hasReference() { return referenceFile.exists(); } }
processing/processing
app/src/processing/app/Library.java
41,653
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.messenger; import android.graphics.Bitmap; import android.os.SystemClock; import android.text.TextUtils; import android.util.SparseArray; import androidx.annotation.IntDef; import androidx.collection.LongSparseArray; import com.google.android.exoplayer2.util.Log; import org.telegram.messenger.voip.Instance; import org.telegram.messenger.voip.VoIPService; import org.telegram.tgnet.TLRPC; import org.telegram.ui.GroupCallActivity; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; public class ChatObject { public static final int CHAT_TYPE_CHAT = 0; public static final int CHAT_TYPE_CHANNEL = 2; public static final int CHAT_TYPE_USER = 3; public static final int CHAT_TYPE_MEGAGROUP = 4; public static final int CHAT_TYPE_FORUM = 5; public static final int ACTION_PIN = 0; public static final int ACTION_CHANGE_INFO = 1; public static final int ACTION_BLOCK_USERS = 2; public static final int ACTION_INVITE = 3; public static final int ACTION_ADD_ADMINS = 4; public static final int ACTION_POST = 5; public static final int ACTION_SEND = 6; public static final int ACTION_SEND_TEXT = 22; public static final int ACTION_SEND_MEDIA = 7; public static final int ACTION_SEND_STICKERS = 8; public static final int ACTION_EMBED_LINKS = 9; public static final int ACTION_SEND_POLLS = 10; public static final int ACTION_VIEW = 11; public static final int ACTION_EDIT_MESSAGES = 12; public static final int ACTION_DELETE_MESSAGES = 13; public static final int ACTION_MANAGE_CALLS = 14; public static final int ACTION_MANAGE_TOPICS = 15; public static final int ACTION_SEND_PHOTO = 16; public static final int ACTION_SEND_VIDEO = 17; public static final int ACTION_SEND_MUSIC = 18; public static final int ACTION_SEND_DOCUMENTS = 19; public static final int ACTION_SEND_VOICE = 20; public static final int ACTION_SEND_ROUND = 21; public static final int ACTION_SEND_PLAIN = 22; public static final int ACTION_SEND_GIFS = 23; public final static int VIDEO_FRAME_NO_FRAME = 0; public final static int VIDEO_FRAME_REQUESTING = 1; public final static int VIDEO_FRAME_HAS_FRAME = 2; private static final int MAX_PARTICIPANTS_COUNT = 5000; public static boolean reactionIsAvailable(TLRPC.ChatFull chatInfo, String reaction) { if (chatInfo.available_reactions instanceof TLRPC.TL_chatReactionsAll) { return true; } if (chatInfo.available_reactions instanceof TLRPC.TL_chatReactionsSome) { TLRPC.TL_chatReactionsSome someReactions = (TLRPC.TL_chatReactionsSome) chatInfo.available_reactions; for (int i = 0; i < someReactions.reactions.size(); i++) { if (someReactions.reactions.get(i) instanceof TLRPC.TL_reactionEmoji && TextUtils.equals(((TLRPC.TL_reactionEmoji) someReactions.reactions.get(i)).emoticon, reaction)) { return true; } } } return false; } public static boolean isForum(int currentAccount, long dialogId) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); if (chat != null) { return chat.forum; } return false; } public static boolean canSendAnyMedia(TLRPC.Chat currentChat) { return canSendPhoto(currentChat) || canSendVideo(currentChat) || canSendRoundVideo(currentChat) || canSendVoice(currentChat) || canSendDocument(currentChat) || canSendMusic(currentChat) || canSendStickers(currentChat); } public static boolean isIgnoredChatRestrictionsForBoosters(TLRPC.ChatFull chatFull) { return chatFull != null && chatFull.boosts_unrestrict > 0 && (chatFull.boosts_applied - chatFull.boosts_unrestrict) >= 0; } public static boolean isIgnoredChatRestrictionsForBoosters(TLRPC.Chat chat) { if (chat != null) { TLRPC.ChatFull chatFull = MessagesController.getInstance(UserConfig.selectedAccount).getChatFull(chat.id); return isIgnoredChatRestrictionsForBoosters(chatFull); } return false; } public static boolean isPossibleRemoveChatRestrictionsByBoosts(TLRPC.Chat chat) { if (chat != null) { TLRPC.ChatFull chatFull = MessagesController.getInstance(UserConfig.selectedAccount).getChatFull(chat.id); return isPossibleRemoveChatRestrictionsByBoosts(chatFull); } return false; } public static boolean isPossibleRemoveChatRestrictionsByBoosts(TLRPC.ChatFull chatFull) { return chatFull != null && chatFull.boosts_unrestrict > 0; } public static String getAllowedSendString(TLRPC.Chat chat) { StringBuilder stringBuilder = new StringBuilder(); if (ChatObject.canSendPhoto(chat)) { stringBuilder.append(LocaleController.getString("SendMediaPermissionPhotos", R.string.SendMediaPermissionPhotos)); } if (ChatObject.canSendVideo(chat)) { if (stringBuilder.length() > 0) { stringBuilder.append(", "); } stringBuilder.append(LocaleController.getString("SendMediaPermissionVideos", R.string.SendMediaPermissionVideos)); } if (ChatObject.canSendStickers(chat)) { if (stringBuilder.length() > 0) { stringBuilder.append(", "); } stringBuilder.append(LocaleController.getString("SendMediaPermissionStickersGifs", R.string.SendMediaPermissionStickersGifs)); } if (ChatObject.canSendMusic(chat)) { if (stringBuilder.length() > 0) { stringBuilder.append(", "); } stringBuilder.append(LocaleController.getString("SendMediaPermissionMusic", R.string.SendMediaPermissionMusic)); } if (ChatObject.canSendDocument(chat)) { if (stringBuilder.length() > 0) { stringBuilder.append(", "); } stringBuilder.append(LocaleController.getString("SendMediaPermissionFiles", R.string.SendMediaPermissionFiles)); } if (ChatObject.canSendVoice(chat)) { if (stringBuilder.length() > 0) { stringBuilder.append(", "); } stringBuilder.append(LocaleController.getString("SendMediaPermissionVoice", R.string.SendMediaPermissionVoice)); } if (ChatObject.canSendRoundVideo(chat)) { if (stringBuilder.length() > 0) { stringBuilder.append(", "); } stringBuilder.append(LocaleController.getString("SendMediaPermissionRound", R.string.SendMediaPermissionRound)); } if (ChatObject.canSendEmbed(chat)) { if (stringBuilder.length() > 0) { stringBuilder.append(", "); } stringBuilder.append(LocaleController.getString("SendMediaEmbededLinks", R.string.SendMediaEmbededLinks)); } return stringBuilder.toString(); } public static class Call { public final static int RECORD_TYPE_AUDIO = 0, RECORD_TYPE_VIDEO_PORTAIT = 1, RECORD_TYPE_VIDEO_LANDSCAPE = 2; @Retention(RetentionPolicy.SOURCE) @IntDef({ RECORD_TYPE_AUDIO, RECORD_TYPE_VIDEO_PORTAIT, RECORD_TYPE_VIDEO_LANDSCAPE }) public @interface RecordType {} public TLRPC.GroupCall call; public long chatId; public LongSparseArray<TLRPC.TL_groupCallParticipant> participants = new LongSparseArray<>(); public final ArrayList<TLRPC.TL_groupCallParticipant> sortedParticipants = new ArrayList<>(); public final ArrayList<VideoParticipant> visibleVideoParticipants = new ArrayList<>(); public final ArrayList<TLRPC.TL_groupCallParticipant> visibleParticipants = new ArrayList<>(); public final HashMap<String, Bitmap> thumbs = new HashMap<>(); private final HashMap<String, VideoParticipant> videoParticipantsCache = new HashMap<>(); public ArrayList<Long> invitedUsers = new ArrayList<>(); public HashSet<Long> invitedUsersMap = new HashSet<>(); public SparseArray<TLRPC.TL_groupCallParticipant> participantsBySources = new SparseArray<>(); public SparseArray<TLRPC.TL_groupCallParticipant> participantsByVideoSources = new SparseArray<>(); public SparseArray<TLRPC.TL_groupCallParticipant> participantsByPresentationSources = new SparseArray<>(); private String nextLoadOffset; public boolean membersLoadEndReached; public boolean loadingMembers; public boolean reloadingMembers; public boolean recording; public boolean canStreamVideo; public int activeVideos; public VideoParticipant videoNotAvailableParticipant; public VideoParticipant rtmpStreamParticipant; public boolean loadedRtmpStreamParticipant; public AccountInstance currentAccount; public int speakingMembersCount; private Runnable typingUpdateRunnable = () -> { typingUpdateRunnableScheduled = false; checkOnlineParticipants(); currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.groupCallTypingsUpdated); }; private boolean typingUpdateRunnableScheduled; private int lastLoadGuid; private HashSet<Integer> loadingGuids = new HashSet<>(); private ArrayList<TLRPC.TL_updateGroupCallParticipants> updatesQueue = new ArrayList<>(); private long updatesStartWaitTime; public TLRPC.Peer selfPeer; private HashSet<Long> loadingUids = new HashSet<>(); private HashSet<Long> loadingSsrcs = new HashSet<>(); private Runnable checkQueueRunnable; private long lastGroupCallReloadTime; private boolean loadingGroupCall; private static int videoPointer; public final LongSparseArray<TLRPC.TL_groupCallParticipant> currentSpeakingPeers = new LongSparseArray<>(); private final Runnable updateCurrentSpeakingRunnable = new Runnable() { @Override public void run() { long uptime = SystemClock.uptimeMillis(); boolean update = false; for(int i = 0; i < currentSpeakingPeers.size(); i++) { long key = currentSpeakingPeers.keyAt(i); TLRPC.TL_groupCallParticipant participant = currentSpeakingPeers.get(key); if (uptime - participant.lastSpeakTime >= 500) { update = true; currentSpeakingPeers.remove(key); if (key > 0) { TLRPC.User user = MessagesController.getInstance(currentAccount.getCurrentAccount()).getUser(key); Log.d("GroupCall", "remove from speaking " + key + " " + (user == null ? null : user.first_name)); } else { TLRPC.Chat user = MessagesController.getInstance(currentAccount.getCurrentAccount()).getChat(-key); Log.d("GroupCall", "remove from speaking " + key + " " + (user == null ? null : user.title)); } i--; } } if (currentSpeakingPeers.size() > 0) { AndroidUtilities.runOnUIThread(updateCurrentSpeakingRunnable, 550); } if (update) { currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.groupCallSpeakingUsersUpdated, chatId, call.id, false); } } }; public void setCall(AccountInstance account, long chatId, TLRPC.TL_phone_groupCall groupCall) { this.chatId = chatId; currentAccount = account; call = groupCall.call; recording = call.record_start_date != 0; int date = Integer.MAX_VALUE; for (int a = 0, N = groupCall.participants.size(); a < N; a++) { TLRPC.TL_groupCallParticipant participant = groupCall.participants.get(a); participants.put(MessageObject.getPeerId(participant.peer), participant); sortedParticipants.add(participant); processAllSources(participant, true); date = Math.min(date, participant.date); } sortParticipants(); nextLoadOffset = groupCall.participants_next_offset; loadMembers(true); createNoVideoParticipant(); if (call.rtmp_stream) { createRtmpStreamParticipant(Collections.emptyList()); } } // public void loadRtmpStreamChannels() { // if (call == null || loadedRtmpStreamParticipant) { // return; // } // TLRPC.TL_phone_getGroupCallStreamChannels getGroupCallStreamChannels = new TLRPC.TL_phone_getGroupCallStreamChannels(); // getGroupCallStreamChannels.call = getInputGroupCall(); // currentAccount.getConnectionsManager().sendRequest(getGroupCallStreamChannels, (response, error, timestamp) -> { // if (response instanceof TLRPC.TL_phone_groupCallStreamChannels) { // TLRPC.TL_phone_groupCallStreamChannels streamChannels = (TLRPC.TL_phone_groupCallStreamChannels) response; // createRtmpStreamParticipant(streamChannels.channels); // loadedRtmpStreamParticipant = true; // } // }, ConnectionsManager.RequestFlagFailOnServerErrors, ConnectionsManager.ConnectionTypeDownload, call.stream_dc_id); // } public void createRtmpStreamParticipant(List<TLRPC.TL_groupCallStreamChannel> channels) { if (loadedRtmpStreamParticipant && rtmpStreamParticipant != null) { return; } TLRPC.TL_groupCallParticipant participant = rtmpStreamParticipant != null ? rtmpStreamParticipant.participant : new TLRPC.TL_groupCallParticipant(); participant.peer = new TLRPC.TL_peerChat(); participant.peer.channel_id = chatId; participant.video = new TLRPC.TL_groupCallParticipantVideo(); TLRPC.TL_groupCallParticipantVideoSourceGroup sourceGroup = new TLRPC.TL_groupCallParticipantVideoSourceGroup(); sourceGroup.semantics = "SIM"; for (TLRPC.TL_groupCallStreamChannel channel : channels) { sourceGroup.sources.add(channel.channel); } participant.video.source_groups.add(sourceGroup); participant.video.endpoint = "unified"; participant.videoEndpoint = "unified"; rtmpStreamParticipant = new VideoParticipant(participant, false, false); sortParticipants(); AndroidUtilities.runOnUIThread(()-> currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.groupCallUpdated, chatId, call.id, false)); } public void createNoVideoParticipant() { if (videoNotAvailableParticipant != null) { return; } TLRPC.TL_groupCallParticipant noVideoParticipant = new TLRPC.TL_groupCallParticipant(); noVideoParticipant.peer = new TLRPC.TL_peerChannel(); noVideoParticipant.peer.channel_id = chatId; noVideoParticipant.muted = true; noVideoParticipant.video = new TLRPC.TL_groupCallParticipantVideo(); noVideoParticipant.video.paused = true; noVideoParticipant.video.endpoint = ""; videoNotAvailableParticipant = new VideoParticipant(noVideoParticipant, false, false); } public void addSelfDummyParticipant(boolean notify) { long selfId = getSelfId(); if (participants.indexOfKey(selfId) >= 0) { return; } TLRPC.TL_groupCallParticipant selfDummyParticipant = new TLRPC.TL_groupCallParticipant(); selfDummyParticipant.peer = selfPeer; selfDummyParticipant.muted = true; selfDummyParticipant.self = true; selfDummyParticipant.video_joined = call.can_start_video; TLRPC.Chat chat = currentAccount.getMessagesController().getChat(chatId); selfDummyParticipant.can_self_unmute = !call.join_muted || ChatObject.canManageCalls(chat); selfDummyParticipant.date = currentAccount.getConnectionsManager().getCurrentTime(); if (ChatObject.canManageCalls(chat) || !ChatObject.isChannel(chat) || chat.megagroup || selfDummyParticipant.can_self_unmute) { selfDummyParticipant.active_date = currentAccount.getConnectionsManager().getCurrentTime(); } if (selfId > 0) { TLRPC.UserFull userFull = MessagesController.getInstance(currentAccount.getCurrentAccount()).getUserFull(selfId); if (userFull != null) { selfDummyParticipant.about = userFull.about; } } else { TLRPC.ChatFull chatFull = MessagesController.getInstance(currentAccount.getCurrentAccount()).getChatFull(-selfId); if (chatFull != null) { selfDummyParticipant.about = chatFull.about; } } participants.put(selfId, selfDummyParticipant); sortedParticipants.add(selfDummyParticipant); sortParticipants(); if (notify) { currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.groupCallUpdated, chatId, call.id, false); } } public void migrateToChat(TLRPC.Chat chat) { chatId = chat.id; VoIPService voIPService = VoIPService.getSharedInstance(); if (voIPService != null && voIPService.getAccount() == currentAccount.getCurrentAccount() && voIPService.getChat() != null && voIPService.getChat().id == -chatId) { voIPService.migrateToChat(chat); } } public boolean shouldShowPanel() { return call.participants_count > 0 || call.rtmp_stream || isScheduled(); } public boolean isScheduled() { return (call.flags & 128) != 0; } private long getSelfId() { long selfId; if (selfPeer != null) { return MessageObject.getPeerId(selfPeer); } else { return currentAccount.getUserConfig().getClientUserId(); } } private void onParticipantsLoad(ArrayList<TLRPC.TL_groupCallParticipant> loadedParticipants, boolean fromBegin, String reqOffset, String nextOffset, int version, int participantCount) { LongSparseArray<TLRPC.TL_groupCallParticipant> old = null; long selfId = getSelfId(); TLRPC.TL_groupCallParticipant oldSelf = participants.get(selfId); if (TextUtils.isEmpty(reqOffset)) { if (participants.size() != 0) { old = participants; participants = new LongSparseArray<>(); } else { participants.clear(); } sortedParticipants.clear(); participantsBySources.clear(); participantsByVideoSources.clear(); participantsByPresentationSources.clear(); loadingGuids.clear(); } nextLoadOffset = nextOffset; if (loadedParticipants.isEmpty() || TextUtils.isEmpty(nextLoadOffset)) { membersLoadEndReached = true; } if (TextUtils.isEmpty(reqOffset)) { call.version = version; call.participants_count = participantCount; if (BuildVars.LOGS_ENABLED) { FileLog.d("new participants count " + call.participants_count); } } long time = SystemClock.elapsedRealtime(); currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.applyGroupCallVisibleParticipants, time); boolean hasSelf = false; for (int a = 0, N = loadedParticipants.size(); a <= N; a++) { TLRPC.TL_groupCallParticipant participant; if (a == N) { if (fromBegin && oldSelf != null && !hasSelf) { participant = oldSelf; } else { continue; } } else { participant = loadedParticipants.get(a); if (participant.self) { hasSelf = true; } } TLRPC.TL_groupCallParticipant oldParticipant = participants.get(MessageObject.getPeerId(participant.peer)); if (oldParticipant != null) { sortedParticipants.remove(oldParticipant); processAllSources(oldParticipant, false); if (oldParticipant.self) { participant.lastTypingDate = oldParticipant.active_date; } else { participant.lastTypingDate = Math.max(participant.active_date, oldParticipant.active_date); } if (time != participant.lastVisibleDate) { participant.active_date = participant.lastTypingDate; } } else if (old != null) { oldParticipant = old.get(MessageObject.getPeerId(participant.peer)); if (oldParticipant != null) { if (oldParticipant.self) { participant.lastTypingDate = oldParticipant.active_date; } else { participant.lastTypingDate = Math.max(participant.active_date, oldParticipant.active_date); } if (time != participant.lastVisibleDate) { participant.active_date = participant.lastTypingDate; } else { participant.active_date = oldParticipant.active_date; } } } participants.put(MessageObject.getPeerId(participant.peer), participant); sortedParticipants.add(participant); processAllSources(participant, true); } if (call.participants_count < participants.size()) { call.participants_count = participants.size(); } sortParticipants(); currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.groupCallUpdated, chatId, call.id, false); setParticiapantsVolume(); } public void loadMembers(boolean fromBegin) { if (fromBegin) { if (reloadingMembers) { return; } membersLoadEndReached = false; nextLoadOffset = null; } if (membersLoadEndReached || sortedParticipants.size() > MAX_PARTICIPANTS_COUNT) { return; } if (fromBegin) { reloadingMembers = true; } loadingMembers = true; TLRPC.TL_phone_getGroupParticipants req = new TLRPC.TL_phone_getGroupParticipants(); req.call = getInputGroupCall(); req.offset = nextLoadOffset != null ? nextLoadOffset : ""; req.limit = 20; currentAccount.getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { loadingMembers = false; if (fromBegin) { reloadingMembers = false; } if (response != null) { TLRPC.TL_phone_groupParticipants groupParticipants = (TLRPC.TL_phone_groupParticipants) response; currentAccount.getMessagesController().putUsers(groupParticipants.users, false); currentAccount.getMessagesController().putChats(groupParticipants.chats, false); onParticipantsLoad(groupParticipants.participants, fromBegin, req.offset, groupParticipants.next_offset, groupParticipants.version, groupParticipants.count); } })); } private void setParticiapantsVolume() { VoIPService voIPService = VoIPService.getSharedInstance(); if (voIPService != null && voIPService.getAccount() == currentAccount.getCurrentAccount() && voIPService.getChat() != null && voIPService.getChat().id == -chatId) { voIPService.setParticipantsVolume(); } } public void setTitle(String title) { TLRPC.TL_phone_editGroupCallTitle req = new TLRPC.TL_phone_editGroupCallTitle(); req.call = getInputGroupCall(); req.title = title; currentAccount.getConnectionsManager().sendRequest(req, (response, error) -> { if (response != null) { final TLRPC.Updates res = (TLRPC.Updates) response; currentAccount.getMessagesController().processUpdates(res, false); } }); } public void addInvitedUser(long uid) { if (participants.get(uid) != null || invitedUsersMap.contains(uid)) { return; } invitedUsersMap.add(uid); invitedUsers.add(uid); } public void processTypingsUpdate(AccountInstance accountInstance, ArrayList<Long> uids, int date) { boolean updated = false; ArrayList<Long> participantsToLoad = null; long time = SystemClock.elapsedRealtime(); currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.applyGroupCallVisibleParticipants, time); for (int a = 0, N = uids.size(); a < N; a++) { Long id = uids.get(a); TLRPC.TL_groupCallParticipant participant = participants.get(id); if (participant != null) { if (date - participant.lastTypingDate > 10) { if (participant.lastVisibleDate != date) { participant.active_date = date; } participant.lastTypingDate = date; updated = true; } } else { if (participantsToLoad == null) { participantsToLoad = new ArrayList<>(); } participantsToLoad.add(id); } } if (participantsToLoad != null) { loadUnknownParticipants(participantsToLoad, true, null); } if (updated) { sortParticipants(); currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.groupCallUpdated, chatId, call.id, false); } } private void loadUnknownParticipants(ArrayList<Long> participantsToLoad, boolean isIds, OnParticipantsLoad onLoad) { HashSet<Long> set = isIds ? loadingUids : loadingSsrcs; for (int a = 0, N = participantsToLoad.size(); a < N; a++) { if (set.contains(participantsToLoad.get(a))) { participantsToLoad.remove(a); a--; N--; } } if (participantsToLoad.isEmpty()) { return; } int guid = ++lastLoadGuid; loadingGuids.add(guid); set.addAll(participantsToLoad); TLRPC.TL_phone_getGroupParticipants req = new TLRPC.TL_phone_getGroupParticipants(); req.call = getInputGroupCall(); for (int a = 0, N = participantsToLoad.size(); a < N; a++) { long uid = participantsToLoad.get(a); if (isIds) { if (uid > 0) { TLRPC.TL_inputPeerUser peerUser = new TLRPC.TL_inputPeerUser(); peerUser.user_id = uid; req.ids.add(peerUser); } else { TLRPC.Chat chat = currentAccount.getMessagesController().getChat(-uid); TLRPC.InputPeer inputPeer; if (chat == null || ChatObject.isChannel(chat)) { inputPeer = new TLRPC.TL_inputPeerChannel(); inputPeer.channel_id = -uid; } else { inputPeer = new TLRPC.TL_inputPeerChat(); inputPeer.chat_id = -uid; } req.ids.add(inputPeer); } } else { req.sources.add((int) uid); } } req.offset = ""; req.limit = 100; currentAccount.getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { if (!loadingGuids.remove(guid)) { return; } if (response != null) { TLRPC.TL_phone_groupParticipants groupParticipants = (TLRPC.TL_phone_groupParticipants) response; currentAccount.getMessagesController().putUsers(groupParticipants.users, false); currentAccount.getMessagesController().putChats(groupParticipants.chats, false); for (int a = 0, N = groupParticipants.participants.size(); a < N; a++) { TLRPC.TL_groupCallParticipant participant = groupParticipants.participants.get(a); long pid = MessageObject.getPeerId(participant.peer); TLRPC.TL_groupCallParticipant oldParticipant = participants.get(pid); if (oldParticipant != null) { sortedParticipants.remove(oldParticipant); processAllSources(oldParticipant, false); } participants.put(pid, participant); sortedParticipants.add(participant); processAllSources(participant, true); if (invitedUsersMap.contains(pid)) { Long id = pid; invitedUsersMap.remove(id); invitedUsers.remove(id); } } if (call.participants_count < participants.size()) { call.participants_count = participants.size(); } sortParticipants(); currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.groupCallUpdated, chatId, call.id, false); if (onLoad != null) { onLoad.onLoad(participantsToLoad); } else { setParticiapantsVolume(); } } set.removeAll(participantsToLoad); })); } private void processAllSources(TLRPC.TL_groupCallParticipant participant, boolean add) { if (participant.source != 0) { if (add) { participantsBySources.put(participant.source, participant); } else { participantsBySources.remove(participant.source); } } for (int c = 0; c < 2; c++) { TLRPC.TL_groupCallParticipantVideo data = c == 0 ? participant.video : participant.presentation; if (data != null) { if ((data.flags & 2) != 0 && data.audio_source != 0) { if (add) { participantsBySources.put(data.audio_source, participant); } else { participantsBySources.remove(data.audio_source); } } SparseArray<TLRPC.TL_groupCallParticipant> sourcesArray = c == 0 ? participantsByVideoSources : participantsByPresentationSources; for (int a = 0, N = data.source_groups.size(); a < N; a++) { TLRPC.TL_groupCallParticipantVideoSourceGroup sourceGroup = data.source_groups.get(a); for (int b = 0, N2 = sourceGroup.sources.size(); b < N2; b++) { int source = sourceGroup.sources.get(b); if (add) { sourcesArray.put(source, participant); } else { sourcesArray.remove(source); } } } if (add) { if (c == 0) { participant.videoEndpoint = data.endpoint; } else { participant.presentationEndpoint = data.endpoint; } } else { if (c == 0) { participant.videoEndpoint = null; } else { participant.presentationEndpoint = null; } } } } } public void processVoiceLevelsUpdate(int[] ssrc, float[] levels, boolean[] voice) { boolean updated = false; boolean updateCurrentSpeakingList = false; int currentTime = currentAccount.getConnectionsManager().getCurrentTime(); ArrayList<Long> participantsToLoad = null; long time = SystemClock.elapsedRealtime(); long uptime = SystemClock.uptimeMillis(); currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.applyGroupCallVisibleParticipants, time); for (int a = 0; a < ssrc.length; a++) { TLRPC.TL_groupCallParticipant participant; if (ssrc[a] == 0) { participant = participants.get(getSelfId()); } else { participant = participantsBySources.get(ssrc[a]); } if (participant != null) { participant.hasVoice = voice[a]; if (voice[a] || time - participant.lastVoiceUpdateTime > 500) { participant.hasVoiceDelayed = voice[a]; participant.lastVoiceUpdateTime = time; } long peerId = MessageObject.getPeerId(participant.peer); if (levels[a] > 0.1f) { if (voice[a] && participant.lastTypingDate + 1 < currentTime) { if (time != participant.lastVisibleDate) { participant.active_date = currentTime; } participant.lastTypingDate = currentTime; updated = true; } participant.lastSpeakTime = uptime; participant.amplitude = levels[a]; if (currentSpeakingPeers.get(peerId, null) == null) { if (peerId > 0) { TLRPC.User user = MessagesController.getInstance(currentAccount.getCurrentAccount()).getUser(peerId); Log.d("GroupCall", "add to current speaking " + peerId + " " + (user == null ? null : user.first_name)); } else { TLRPC.Chat user = MessagesController.getInstance(currentAccount.getCurrentAccount()).getChat(-peerId); Log.d("GroupCall", "add to current speaking " + peerId + " " + (user == null ? null : user.title)); } currentSpeakingPeers.put(peerId, participant); updateCurrentSpeakingList = true; } } else { if (uptime - participant.lastSpeakTime >= 500) { if (currentSpeakingPeers.get(peerId, null) != null) { currentSpeakingPeers.remove(peerId); if (peerId > 0) { TLRPC.User user = MessagesController.getInstance(currentAccount.getCurrentAccount()).getUser(peerId); Log.d("GroupCall", "remove from speaking " + peerId + " " + (user == null ? null : user.first_name)); } else { TLRPC.Chat user = MessagesController.getInstance(currentAccount.getCurrentAccount()).getChat(-peerId); Log.d("GroupCall", "remove from speaking " + peerId + " " + (user == null ? null : user.title)); } updateCurrentSpeakingList = true; } } participant.amplitude = 0; } } else if (ssrc[a] != 0) { if (participantsToLoad == null) { participantsToLoad = new ArrayList<>(); } participantsToLoad.add((long) ssrc[a]); } } if (participantsToLoad != null) { loadUnknownParticipants(participantsToLoad, false, null); } if (updated) { sortParticipants(); currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.groupCallUpdated, chatId, call.id, false); } if (updateCurrentSpeakingList) { if (currentSpeakingPeers.size() > 0) { AndroidUtilities.cancelRunOnUIThread(updateCurrentSpeakingRunnable); AndroidUtilities.runOnUIThread(updateCurrentSpeakingRunnable, 550); } currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.groupCallSpeakingUsersUpdated, chatId, call.id, false); } } public void updateVisibleParticipants() { sortParticipants(); currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.groupCallUpdated, chatId, call.id, false, 0L); } public void clearVideFramesInfo() { for (int i = 0; i < sortedParticipants.size(); i++) { sortedParticipants.get(i).hasCameraFrame = VIDEO_FRAME_NO_FRAME; sortedParticipants.get(i).hasPresentationFrame = VIDEO_FRAME_NO_FRAME; sortedParticipants.get(i).videoIndex = 0; } sortParticipants(); } public interface OnParticipantsLoad { void onLoad(ArrayList<Long> ssrcs); } public void processUnknownVideoParticipants(int[] ssrc, OnParticipantsLoad onLoad) { ArrayList<Long> participantsToLoad = null; for (int a = 0; a < ssrc.length; a++) { if (participantsBySources.get(ssrc[a]) != null || participantsByVideoSources.get(ssrc[a]) != null || participantsByPresentationSources.get(ssrc[a]) != null) { continue; } if (participantsToLoad == null) { participantsToLoad = new ArrayList<>(); } participantsToLoad.add((long) ssrc[a]); } if (participantsToLoad != null) { loadUnknownParticipants(participantsToLoad, false, onLoad); } else { onLoad.onLoad(null); } } private int isValidUpdate(TLRPC.TL_updateGroupCallParticipants update) { if (call.version + 1 == update.version || call.version == update.version) { return 0; } else if (call.version < update.version) { return 1; } else { return 2; } } public void setSelfPeer(TLRPC.InputPeer peer) { if (peer == null) { selfPeer = null; } else { if (peer instanceof TLRPC.TL_inputPeerUser) { selfPeer = new TLRPC.TL_peerUser(); selfPeer.user_id = peer.user_id; } else if (peer instanceof TLRPC.TL_inputPeerChat) { selfPeer = new TLRPC.TL_peerChat(); selfPeer.chat_id = peer.chat_id; } else { selfPeer = new TLRPC.TL_peerChannel(); selfPeer.channel_id = peer.channel_id; } } } private void processUpdatesQueue() { Collections.sort(updatesQueue, (updates, updates2) -> AndroidUtilities.compare(updates.version, updates2.version)); if (updatesQueue != null && !updatesQueue.isEmpty()) { boolean anyProceed = false; for (int a = 0; a < updatesQueue.size(); a++) { TLRPC.TL_updateGroupCallParticipants update = updatesQueue.get(a); int updateState = isValidUpdate(update); if (updateState == 0) { processParticipantsUpdate(update, true); anyProceed = true; updatesQueue.remove(a); a--; } else if (updateState == 1) { if (updatesStartWaitTime != 0 && (anyProceed || Math.abs(System.currentTimeMillis() - updatesStartWaitTime) <= 1500)) { if (BuildVars.LOGS_ENABLED) { FileLog.d("HOLE IN GROUP CALL UPDATES QUEUE - will wait more time"); } if (anyProceed) { updatesStartWaitTime = System.currentTimeMillis(); } } else { if (BuildVars.LOGS_ENABLED) { FileLog.d("HOLE IN GROUP CALL UPDATES QUEUE - reload participants"); } updatesStartWaitTime = 0; updatesQueue.clear(); nextLoadOffset = null; loadMembers(true); } return; } else { updatesQueue.remove(a); a--; } } updatesQueue.clear(); if (BuildVars.LOGS_ENABLED) { FileLog.d("GROUP CALL UPDATES QUEUE PROCEED - OK"); } } updatesStartWaitTime = 0; } private void checkQueue() { checkQueueRunnable = null; if (updatesStartWaitTime != 0 && (System.currentTimeMillis() - updatesStartWaitTime) >= 1500) { if (BuildVars.LOGS_ENABLED) { FileLog.d("QUEUE GROUP CALL UPDATES WAIT TIMEOUT - CHECK QUEUE"); } processUpdatesQueue(); } if (!updatesQueue.isEmpty()) { AndroidUtilities.runOnUIThread(checkQueueRunnable = this::checkQueue, 1000); } } public void reloadGroupCall() { TLRPC.TL_phone_getGroupCall req = new TLRPC.TL_phone_getGroupCall(); req.call = getInputGroupCall(); req.limit = 100; currentAccount.getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { if (response instanceof TLRPC.TL_phone_groupCall) { TLRPC.TL_phone_groupCall phoneGroupCall = (TLRPC.TL_phone_groupCall) response; call = phoneGroupCall.call; currentAccount.getMessagesController().putUsers(phoneGroupCall.users, false); currentAccount.getMessagesController().putChats(phoneGroupCall.chats, false); onParticipantsLoad(phoneGroupCall.participants, true, "", phoneGroupCall.participants_next_offset, phoneGroupCall.call.version, phoneGroupCall.call.participants_count); } })); } private void loadGroupCall() { if (loadingGroupCall || SystemClock.elapsedRealtime() - lastGroupCallReloadTime < 30000) { return; } loadingGroupCall = true; TLRPC.TL_phone_getGroupParticipants req = new TLRPC.TL_phone_getGroupParticipants(); req.call = getInputGroupCall(); req.offset = ""; req.limit = 1; currentAccount.getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { lastGroupCallReloadTime = SystemClock.elapsedRealtime(); loadingGroupCall = false; if (response != null) { TLRPC.TL_phone_groupParticipants res = (TLRPC.TL_phone_groupParticipants) response; currentAccount.getMessagesController().putUsers(res.users, false); currentAccount.getMessagesController().putChats(res.chats, false); if (call.participants_count != res.count) { call.participants_count = res.count; if (BuildVars.LOGS_ENABLED) { FileLog.d("new participants reload count " + call.participants_count); } currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.groupCallUpdated, chatId, call.id, false); } } })); } public void processParticipantsUpdate(TLRPC.TL_updateGroupCallParticipants update, boolean fromQueue) { if (!fromQueue) { boolean versioned = false; for (int a = 0, N = update.participants.size(); a < N; a++) { TLRPC.TL_groupCallParticipant participant = update.participants.get(a); if (participant.versioned) { versioned = true; break; } } if (versioned && call.version + 1 < update.version) { if (reloadingMembers || updatesStartWaitTime == 0 || Math.abs(System.currentTimeMillis() - updatesStartWaitTime) <= 1500) { if (updatesStartWaitTime == 0) { updatesStartWaitTime = System.currentTimeMillis(); } if (BuildVars.LOGS_ENABLED) { FileLog.d("add TL_updateGroupCallParticipants to queue " + update.version); } updatesQueue.add(update); if (checkQueueRunnable == null) { AndroidUtilities.runOnUIThread(checkQueueRunnable = this::checkQueue, 1500); } } else { nextLoadOffset = null; loadMembers(true); } return; } if (versioned && update.version < call.version) { if (BuildVars.LOGS_ENABLED) { FileLog.d("ignore processParticipantsUpdate because of version"); } return; } } boolean reloadCall = false; boolean updated = false; boolean selfUpdated = false; boolean changedOrAdded = false; boolean speakingUpdated = false; long selfId = getSelfId(); long time = SystemClock.elapsedRealtime(); long justJoinedId = 0; int lastParticipantDate; if (!sortedParticipants.isEmpty()) { lastParticipantDate = sortedParticipants.get(sortedParticipants.size() - 1).date; } else { lastParticipantDate = 0; } currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.applyGroupCallVisibleParticipants, time); for (int a = 0, N = update.participants.size(); a < N; a++) { TLRPC.TL_groupCallParticipant participant = update.participants.get(a); long pid = MessageObject.getPeerId(participant.peer); if (BuildVars.LOGS_ENABLED) { FileLog.d("process participant " + pid + " left = " + participant.left + " versioned " + participant.versioned + " flags = " + participant.flags + " self = " + selfId + " volume = " + participant.volume); } TLRPC.TL_groupCallParticipant oldParticipant = participants.get(pid); if (participant.left) { if (oldParticipant == null && update.version == call.version) { if (BuildVars.LOGS_ENABLED) { FileLog.d("unknowd participant left, reload call"); } reloadCall = true; } if (oldParticipant != null) { participants.remove(pid); processAllSources(oldParticipant, false); sortedParticipants.remove(oldParticipant); visibleParticipants.remove(oldParticipant); if (currentSpeakingPeers.get(pid, null) != null) { if (pid > 0) { TLRPC.User user = MessagesController.getInstance(currentAccount.getCurrentAccount()).getUser(pid); Log.d("GroupCall", "left remove from speaking " + pid + " " + (user == null ? null : user.first_name)); } else { TLRPC.Chat user = MessagesController.getInstance(currentAccount.getCurrentAccount()).getChat(-pid); Log.d("GroupCall", "left remove from speaking " + pid + " " + (user == null ? null : user.title)); } currentSpeakingPeers.remove(pid); speakingUpdated = true; } for (int i = 0; i < visibleVideoParticipants.size(); i++) { VideoParticipant videoParticipant = visibleVideoParticipants.get(i); if (MessageObject.getPeerId(videoParticipant.participant.peer) == MessageObject.getPeerId(oldParticipant.peer)) { visibleVideoParticipants.remove(i); i--; } } } call.participants_count--; if (call.participants_count < 0) { call.participants_count = 0; } updated = true; } else { if (invitedUsersMap.contains(pid)) { Long id = pid; invitedUsersMap.remove(id); invitedUsers.remove(id); } if (oldParticipant != null) { if (BuildVars.LOGS_ENABLED) { FileLog.d("new participant, update old"); } oldParticipant.muted = participant.muted; if (participant.muted && currentSpeakingPeers.get(pid, null) != null) { currentSpeakingPeers.remove(pid); if (pid > 0) { TLRPC.User user = MessagesController.getInstance(currentAccount.getCurrentAccount()).getUser(pid); Log.d("GroupCall", "muted remove from speaking " + pid + " " + (user == null ? null : user.first_name)); } else { TLRPC.Chat user = MessagesController.getInstance(currentAccount.getCurrentAccount()).getChat(-pid); Log.d("GroupCall", "muted remove from speaking " + pid + " " + (user == null ? null : user.title)); } speakingUpdated = true; } if (!participant.min) { oldParticipant.volume = participant.volume; oldParticipant.muted_by_you = participant.muted_by_you; } else { if ((participant.flags & 128) != 0 && (oldParticipant.flags & 128) == 0) { participant.flags &=~ 128; } if (participant.volume_by_admin && oldParticipant.volume_by_admin) { oldParticipant.volume = participant.volume; } } oldParticipant.flags = participant.flags; oldParticipant.can_self_unmute = participant.can_self_unmute; oldParticipant.video_joined = participant.video_joined; if (oldParticipant.raise_hand_rating == 0 && participant.raise_hand_rating != 0) { oldParticipant.lastRaiseHandDate = SystemClock.elapsedRealtime(); } oldParticipant.raise_hand_rating = participant.raise_hand_rating; oldParticipant.date = participant.date; oldParticipant.lastTypingDate = Math.max(oldParticipant.active_date, participant.active_date); if (time != oldParticipant.lastVisibleDate) { oldParticipant.active_date = oldParticipant.lastTypingDate; } if (oldParticipant.source != participant.source || !isSameVideo(oldParticipant.video, participant.video) || !isSameVideo(oldParticipant.presentation, participant.presentation)) { processAllSources(oldParticipant, false); oldParticipant.video = participant.video; oldParticipant.presentation = participant.presentation; oldParticipant.source = participant.source; processAllSources(oldParticipant, true); participant.presentationEndpoint = oldParticipant.presentationEndpoint; participant.videoEndpoint = oldParticipant.videoEndpoint; participant.videoIndex = oldParticipant.videoIndex; } else if (oldParticipant.video != null && participant.video != null) { oldParticipant.video.paused = participant.video.paused; } } else { if (participant.just_joined) { if (pid != selfId) { justJoinedId = pid; } call.participants_count++; if (update.version == call.version) { reloadCall = true; if (BuildVars.LOGS_ENABLED) { FileLog.d("new participant, just joined, reload call"); } } else { if (BuildVars.LOGS_ENABLED) { FileLog.d("new participant, just joined"); } } } if (participant.raise_hand_rating != 0) { participant.lastRaiseHandDate = SystemClock.elapsedRealtime(); } if (pid == selfId || sortedParticipants.size() < 20 || participant.date <= lastParticipantDate || participant.active_date != 0 || participant.can_self_unmute || !participant.muted || !participant.min || membersLoadEndReached) { sortedParticipants.add(participant); } participants.put(pid, participant); processAllSources(participant, true); } if (pid == selfId && participant.active_date == 0 && (participant.can_self_unmute || !participant.muted)) { participant.active_date = currentAccount.getConnectionsManager().getCurrentTime(); } changedOrAdded = true; updated = true; } if (pid == selfId) { selfUpdated = true; } } if (update.version > call.version) { call.version = update.version; if (!fromQueue) { processUpdatesQueue(); } } if (call.participants_count < participants.size()) { call.participants_count = participants.size(); } if (BuildVars.LOGS_ENABLED) { FileLog.d("new participants count after update " + call.participants_count); } if (reloadCall) { loadGroupCall(); } if (updated) { if (changedOrAdded) { sortParticipants(); } currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.groupCallUpdated, chatId, call.id, selfUpdated, justJoinedId); } if (speakingUpdated) { currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.groupCallSpeakingUsersUpdated, chatId, call.id, false); } } private boolean isSameVideo(TLRPC.TL_groupCallParticipantVideo oldVideo, TLRPC.TL_groupCallParticipantVideo newVideo) { if (oldVideo == null && newVideo != null || oldVideo != null && newVideo == null) { return false; } if (oldVideo == null || newVideo == null) { return true; } if (!TextUtils.equals(oldVideo.endpoint, newVideo.endpoint)) { return false; } if (oldVideo.source_groups.size() != newVideo.source_groups.size()) { return false; } for (int a = 0, N = oldVideo.source_groups.size(); a < N; a++) { TLRPC.TL_groupCallParticipantVideoSourceGroup oldGroup = oldVideo.source_groups.get(a); TLRPC.TL_groupCallParticipantVideoSourceGroup newGroup = newVideo.source_groups.get(a); if (!TextUtils.equals(oldGroup.semantics, newGroup.semantics)) { return false; } if (oldGroup.sources.size() != newGroup.sources.size()) { return false; } for (int b = 0, N2 = oldGroup.sources.size(); b < N2; b++) { if (!newGroup.sources.contains(oldGroup.sources.get(b))) { return false; } } } return true; } public void processGroupCallUpdate(TLRPC.TL_updateGroupCall update) { if (call.version < update.call.version) { nextLoadOffset = null; loadMembers(true); } call = update.call; TLRPC.TL_groupCallParticipant selfParticipant = participants.get(getSelfId()); recording = call.record_start_date != 0; currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.groupCallUpdated, chatId, call.id, false); } public TLRPC.TL_inputGroupCall getInputGroupCall() { TLRPC.TL_inputGroupCall inputGroupCall = new TLRPC.TL_inputGroupCall(); inputGroupCall.id = call.id; inputGroupCall.access_hash = call.access_hash; return inputGroupCall; } public static boolean videoIsActive(TLRPC.TL_groupCallParticipant participant, boolean presentation, ChatObject.Call call) { if (participant == null) { return false; } VoIPService service = VoIPService.getSharedInstance(); if (service == null) { return false; } if (participant.self) { return service.getVideoState(presentation) == Instance.VIDEO_STATE_ACTIVE; } else { if (call.rtmpStreamParticipant != null && call.rtmpStreamParticipant.participant == participant || call.videoNotAvailableParticipant != null && call.videoNotAvailableParticipant.participant == participant || call.participants.get(MessageObject.getPeerId(participant.peer)) != null) { if (presentation) { return participant.presentation != null;// && participant.hasPresentationFrame == 2; } else { return participant.video != null;// && participant.hasCameraFrame == 2; } } else { return false; } } } public void sortParticipants() { visibleVideoParticipants.clear(); visibleParticipants.clear(); TLRPC.Chat chat = currentAccount.getMessagesController().getChat(chatId); boolean isAdmin = ChatObject.canManageCalls(chat); if (rtmpStreamParticipant != null) { visibleVideoParticipants.add(rtmpStreamParticipant); } long selfId = getSelfId(); VoIPService service = VoIPService.getSharedInstance(); TLRPC.TL_groupCallParticipant selfParticipant = participants.get(selfId); canStreamVideo = true;//selfParticipant != null && selfParticipant.video_joined || BuildVars.DEBUG_PRIVATE_VERSION; boolean allowedVideoCount; boolean hasAnyVideo = false; activeVideos = 0; for (int i = 0, N = sortedParticipants.size(); i < N; i++) { TLRPC.TL_groupCallParticipant participant = sortedParticipants.get(i); boolean cameraActive = videoIsActive(participant, false, this); boolean screenActive = videoIsActive(participant, true, this); if (!participant.self && (cameraActive || screenActive)) { activeVideos++; } if (cameraActive || screenActive) { hasAnyVideo = true; if (canStreamVideo) { if (participant.videoIndex == 0) { if (participant.self) { participant.videoIndex = Integer.MAX_VALUE; } else { participant.videoIndex = ++videoPointer; } } } else { participant.videoIndex = 0; } } else if (participant.self || !canStreamVideo || (participant.video == null && participant.presentation == null)) { participant.videoIndex = 0; } } Comparator<TLRPC.TL_groupCallParticipant> comparator = (o1, o2) -> { boolean videoActive1 = o1.videoIndex > 0; boolean videoActive2 = o2.videoIndex > 0; if (videoActive1 && videoActive2) { return o2.videoIndex - o1.videoIndex; } else if (videoActive1) { return -1; } else if (videoActive2) { return 1; } if (o1.active_date != 0 && o2.active_date != 0) { return Integer.compare(o2.active_date, o1.active_date); } else if (o1.active_date != 0) { return -1; } else if (o2.active_date != 0) { return 1; } if (MessageObject.getPeerId(o1.peer) == selfId) { return -1; } else if (MessageObject.getPeerId(o2.peer) == selfId) { return 1; } if (isAdmin) { if (o1.raise_hand_rating != 0 && o2.raise_hand_rating != 0) { return Long.compare(o2.raise_hand_rating, o1.raise_hand_rating); } else if (o1.raise_hand_rating != 0) { return -1; } else if (o2.raise_hand_rating != 0) { return 1; } } if (call.join_date_asc) { return Integer.compare(o1.date, o2.date); } else { return Integer.compare(o2.date, o1.date); } }; try { Collections.sort(sortedParticipants, comparator); } catch (Exception e) { } TLRPC.TL_groupCallParticipant lastParticipant = sortedParticipants.isEmpty() ? null : sortedParticipants.get(sortedParticipants.size() - 1); if (videoIsActive(lastParticipant, false, this) || videoIsActive(lastParticipant, true, this)) { if (call.unmuted_video_count > activeVideos) { activeVideos = call.unmuted_video_count; VoIPService voIPService = VoIPService.getSharedInstance(); if (voIPService != null && voIPService.groupCall == this) { if (voIPService.getVideoState(false) == Instance.VIDEO_STATE_ACTIVE || voIPService.getVideoState(true) == Instance.VIDEO_STATE_ACTIVE) { activeVideos--; } } } } if (sortedParticipants.size() > MAX_PARTICIPANTS_COUNT && (!ChatObject.canManageCalls(chat) || lastParticipant.raise_hand_rating == 0)) { for (int a = MAX_PARTICIPANTS_COUNT, N = sortedParticipants.size(); a < N; a++) { TLRPC.TL_groupCallParticipant p = sortedParticipants.get(MAX_PARTICIPANTS_COUNT); if (p.raise_hand_rating != 0) { continue; } processAllSources(p, false); participants.remove(MessageObject.getPeerId(p.peer)); sortedParticipants.remove(MAX_PARTICIPANTS_COUNT); } } checkOnlineParticipants(); if (!canStreamVideo && hasAnyVideo && videoNotAvailableParticipant != null) { visibleVideoParticipants.add(videoNotAvailableParticipant); } int wideVideoIndex = 0; for (int i = 0; i < sortedParticipants.size(); i++) { TLRPC.TL_groupCallParticipant participant = sortedParticipants.get(i); if (canStreamVideo && participant.videoIndex != 0) { if (!participant.self && videoIsActive(participant, true, this) && videoIsActive(participant, false, this)) { VideoParticipant videoParticipant = videoParticipantsCache.get(participant.videoEndpoint); if (videoParticipant == null) { videoParticipant = new VideoParticipant(participant, false, true); videoParticipantsCache.put(participant.videoEndpoint, videoParticipant); } else { videoParticipant.participant = participant; videoParticipant.presentation = false; videoParticipant.hasSame = true; } VideoParticipant presentationParticipant = videoParticipantsCache.get(participant.presentationEndpoint); if (presentationParticipant == null) { presentationParticipant = new VideoParticipant(participant, true, true); } else { presentationParticipant.participant = participant; presentationParticipant.presentation = true; presentationParticipant.hasSame = true; } visibleVideoParticipants.add(videoParticipant); if (videoParticipant.aspectRatio > 1f) { wideVideoIndex = visibleVideoParticipants.size() - 1; } visibleVideoParticipants.add(presentationParticipant); if (presentationParticipant.aspectRatio > 1f) { wideVideoIndex = visibleVideoParticipants.size() - 1; } } else { if (participant.self) { if (videoIsActive(participant, true, this)) { visibleVideoParticipants.add(new VideoParticipant(participant, true, false)); } if (videoIsActive(participant, false, this)) { visibleVideoParticipants.add(new VideoParticipant(participant, false, false)); } } else { boolean presentation = videoIsActive(participant, true, this); VideoParticipant videoParticipant = videoParticipantsCache.get(presentation ? participant.presentationEndpoint : participant.videoEndpoint); if (videoParticipant == null) { videoParticipant = new VideoParticipant(participant, presentation, false); videoParticipantsCache.put(presentation ? participant.presentationEndpoint : participant.videoEndpoint, videoParticipant); } else { videoParticipant.participant = participant; videoParticipant.presentation = presentation; videoParticipant.hasSame = false; } visibleVideoParticipants.add(videoParticipant); if (videoParticipant.aspectRatio > 1f) { wideVideoIndex = visibleVideoParticipants.size() - 1; } } } } else { visibleParticipants.add(participant); } } if (!GroupCallActivity.isLandscapeMode && visibleVideoParticipants.size() % 2 == 1) { VideoParticipant videoParticipant = visibleVideoParticipants.remove(wideVideoIndex); visibleVideoParticipants.add(videoParticipant); } } public boolean canRecordVideo() { if (!canStreamVideo) { return false; } VoIPService voIPService = VoIPService.getSharedInstance(); if (voIPService != null && voIPService.groupCall == this && (voIPService.getVideoState(false) == Instance.VIDEO_STATE_ACTIVE || voIPService.getVideoState(true) == Instance.VIDEO_STATE_ACTIVE)) { return true; } return activeVideos < call.unmuted_video_limit; } public void saveActiveDates() { for (int a = 0, N = sortedParticipants.size(); a < N; a++) { TLRPC.TL_groupCallParticipant p = sortedParticipants.get(a); p.lastActiveDate = p.active_date; } } private void checkOnlineParticipants() { if (typingUpdateRunnableScheduled) { AndroidUtilities.cancelRunOnUIThread(typingUpdateRunnable); typingUpdateRunnableScheduled = false; } speakingMembersCount = 0; int currentTime = currentAccount.getConnectionsManager().getCurrentTime(); int minDiff = Integer.MAX_VALUE; for (int a = 0, N = sortedParticipants.size(); a < N; a++) { TLRPC.TL_groupCallParticipant participant = sortedParticipants.get(a); int diff = currentTime - participant.active_date; if (diff < 5) { speakingMembersCount++; minDiff = Math.min(diff, minDiff); } if (Math.max(participant.date, participant.active_date) <= currentTime - 5) { break; } } if (minDiff != Integer.MAX_VALUE) { AndroidUtilities.runOnUIThread(typingUpdateRunnable, minDiff * 1000); typingUpdateRunnableScheduled = true; } } public void toggleRecord(String title, @RecordType int type) { recording = !recording; TLRPC.TL_phone_toggleGroupCallRecord req = new TLRPC.TL_phone_toggleGroupCallRecord(); req.call = getInputGroupCall(); req.start = recording; if (title != null) { req.title = title; req.flags |= 2; } if (type == RECORD_TYPE_VIDEO_PORTAIT || type == RECORD_TYPE_VIDEO_LANDSCAPE) { req.flags |= 4; req.video = true; req.video_portrait = type == RECORD_TYPE_VIDEO_PORTAIT; } currentAccount.getConnectionsManager().sendRequest(req, (response, error) -> { if (response != null) { final TLRPC.Updates res = (TLRPC.Updates) response; currentAccount.getMessagesController().processUpdates(res, false); } }); currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.groupCallUpdated, chatId, call.id, false); } } public static int getParticipantVolume(TLRPC.TL_groupCallParticipant participant) { return ((participant.flags & 128) != 0 ? participant.volume : 10000); } private static boolean isBannableAction(int action) { switch (action) { case ACTION_PIN: case ACTION_CHANGE_INFO: case ACTION_INVITE: case ACTION_SEND: case ACTION_SEND_MEDIA: case ACTION_SEND_STICKERS: case ACTION_EMBED_LINKS: case ACTION_SEND_POLLS: case ACTION_VIEW: case ACTION_MANAGE_TOPICS: case ACTION_SEND_PHOTO: case ACTION_SEND_VIDEO: case ACTION_SEND_MUSIC: case ACTION_SEND_DOCUMENTS: case ACTION_SEND_VOICE: case ACTION_SEND_ROUND: case ACTION_SEND_PLAIN: return true; } return false; } private static boolean isAdminAction(int action) { switch (action) { case ACTION_PIN: case ACTION_CHANGE_INFO: case ACTION_INVITE: case ACTION_ADD_ADMINS: case ACTION_POST: case ACTION_EDIT_MESSAGES: case ACTION_DELETE_MESSAGES: case ACTION_BLOCK_USERS: case ACTION_MANAGE_TOPICS: return true; } return false; } private static boolean getBannedRight(TLRPC.TL_chatBannedRights rights, int action) { if (rights == null) { return false; } boolean value; switch (action) { case ACTION_PIN: return rights.pin_messages; case ACTION_CHANGE_INFO: return rights.change_info; case ACTION_INVITE: return rights.invite_users; case ACTION_SEND: return rights.send_messages; case ACTION_SEND_MEDIA: return rights.send_media; case ACTION_SEND_STICKERS: return rights.send_stickers; case ACTION_EMBED_LINKS: return rights.embed_links; case ACTION_SEND_POLLS: return rights.send_polls; case ACTION_VIEW: return rights.view_messages; case ACTION_MANAGE_TOPICS: return rights.manage_topics; case ACTION_SEND_PHOTO: return rights.send_photos; case ACTION_SEND_VIDEO: return rights.send_videos; case ACTION_SEND_MUSIC: return rights.send_audios; case ACTION_SEND_DOCUMENTS: return rights.send_docs; case ACTION_SEND_VOICE: return rights.send_voices; case ACTION_SEND_ROUND: return rights.send_roundvideos; case ACTION_SEND_PLAIN: return rights.send_plain; } return false; } public static boolean isActionBannedByDefault(TLRPC.Chat chat, int action) { if (chat == null) { return false; } if (getBannedRight(chat.banned_rights, action) && getBannedRight(chat.default_banned_rights, action)) { return true; } return getBannedRight(chat.default_banned_rights, action); } public static boolean isActionBanned(TLRPC.Chat chat, int action) { return chat != null && (getBannedRight(chat.banned_rights, action) || getBannedRight(chat.default_banned_rights, action)); } public static boolean canUserDoAdminAction(TLRPC.TL_chatAdminRights admin_rights, int action) { if (admin_rights != null) { boolean value; switch (action) { case ACTION_PIN: value = admin_rights.pin_messages; break; case ACTION_MANAGE_TOPICS: value = admin_rights.manage_topics; break; case ACTION_CHANGE_INFO: value = admin_rights.change_info; break; case ACTION_INVITE: value = admin_rights.invite_users; break; case ACTION_ADD_ADMINS: value = admin_rights.add_admins; break; case ACTION_POST: value = admin_rights.post_messages; break; case ACTION_EDIT_MESSAGES: value = admin_rights.edit_messages; break; case ACTION_DELETE_MESSAGES: value = admin_rights.delete_messages; break; case ACTION_BLOCK_USERS: value = admin_rights.ban_users; break; case ACTION_MANAGE_CALLS: value = admin_rights.manage_call; break; default: value = false; break; } if (value) { return true; } } return false; } public static boolean canUserDoAdminAction(TLRPC.Chat chat, int action) { if (chat == null) { return false; } if (chat.creator) { return true; } if (chat.admin_rights != null) { boolean value; switch (action) { case ACTION_PIN: value = chat.admin_rights.pin_messages; break; case ACTION_MANAGE_TOPICS: value = chat.admin_rights.manage_topics; break; case ACTION_CHANGE_INFO: value = chat.admin_rights.change_info; break; case ACTION_INVITE: value = chat.admin_rights.invite_users; break; case ACTION_ADD_ADMINS: value = chat.admin_rights.add_admins; break; case ACTION_POST: value = chat.admin_rights.post_messages; break; case ACTION_EDIT_MESSAGES: value = chat.admin_rights.edit_messages; break; case ACTION_DELETE_MESSAGES: value = chat.admin_rights.delete_messages; break; case ACTION_BLOCK_USERS: value = chat.admin_rights.ban_users; break; case ACTION_MANAGE_CALLS: value = chat.admin_rights.manage_call; break; default: value = false; break; } if (value) { return true; } } return false; } public static boolean canUserDoAction(TLRPC.Chat chat, TLRPC.ChannelParticipant participant, int action) { if (chat == null) { return true; } if (participant == null) { return false; } if (canUserDoAdminAction(participant.admin_rights, action)) { return true; } if (getBannedRight(participant.banned_rights, action)) { return false; } if (isBannableAction(action)) { if (participant.admin_rights != null && !isAdminAction(action)) { return true; } if (chat.default_banned_rights == null && ( chat instanceof TLRPC.TL_chat_layer92 || chat instanceof TLRPC.TL_chat_old || chat instanceof TLRPC.TL_chat_old2 || chat instanceof TLRPC.TL_channel_layer92 || chat instanceof TLRPC.TL_channel_layer77 || chat instanceof TLRPC.TL_channel_layer72 || chat instanceof TLRPC.TL_channel_layer67 || chat instanceof TLRPC.TL_channel_layer48 || chat instanceof TLRPC.TL_channel_old)) { return true; } if (chat.default_banned_rights == null || getBannedRight(chat.default_banned_rights, action)) { return false; } return true; } return false; } public static boolean canUserDoAction(TLRPC.Chat chat, int action) { if (chat == null) { return true; } if (canUserDoAdminAction(chat, action)) { return true; } if (getBannedRight(chat.banned_rights, action)) { return false; } if (isBannableAction(action)) { if (chat.admin_rights != null && !isAdminAction(action)) { return true; } if (chat.default_banned_rights == null && ( chat instanceof TLRPC.TL_chat_layer92 || chat instanceof TLRPC.TL_chat_old || chat instanceof TLRPC.TL_chat_old2 || chat instanceof TLRPC.TL_channel_layer92 || chat instanceof TLRPC.TL_channel_layer77 || chat instanceof TLRPC.TL_channel_layer72 || chat instanceof TLRPC.TL_channel_layer67 || chat instanceof TLRPC.TL_channel_layer48 || chat instanceof TLRPC.TL_channel_old)) { return true; } if (chat.default_banned_rights == null || getBannedRight(chat.default_banned_rights, action)) { return false; } return true; } return false; } public static boolean isLeftFromChat(TLRPC.Chat chat) { return chat == null || chat instanceof TLRPC.TL_chatEmpty || chat instanceof TLRPC.TL_chatForbidden || chat instanceof TLRPC.TL_channelForbidden || chat.left || chat.deactivated; } public static boolean isKickedFromChat(TLRPC.Chat chat) { return chat == null || chat instanceof TLRPC.TL_chatEmpty || chat instanceof TLRPC.TL_chatForbidden || chat instanceof TLRPC.TL_channelForbidden || chat.kicked || chat.deactivated || chat.banned_rights != null && chat.banned_rights.view_messages; } public static boolean isNotInChat(TLRPC.Chat chat) { return chat == null || chat instanceof TLRPC.TL_chatEmpty || chat instanceof TLRPC.TL_chatForbidden || chat instanceof TLRPC.TL_channelForbidden || chat.left || chat.kicked || chat.deactivated; } public static boolean isInChat(TLRPC.Chat chat) { if (chat == null || chat instanceof TLRPC.TL_chatEmpty || chat instanceof TLRPC.TL_chatForbidden || chat instanceof TLRPC.TL_channelForbidden) { return false; } if (chat.left || chat.kicked || chat.deactivated) { return false; } return true; } public static boolean canSendAsPeers(TLRPC.Chat chat) { return ChatObject.isChannel(chat) && chat.megagroup && (ChatObject.isPublic(chat) || chat.has_geo || chat.has_link); } public static boolean isChannel(TLRPC.Chat chat) { return chat instanceof TLRPC.TL_channel || chat instanceof TLRPC.TL_channelForbidden; } public static boolean isChannelOrGiga(TLRPC.Chat chat) { return (chat instanceof TLRPC.TL_channel || chat instanceof TLRPC.TL_channelForbidden) && (!chat.megagroup || chat.gigagroup); } public static boolean isMegagroup(TLRPC.Chat chat) { return (chat instanceof TLRPC.TL_channel || chat instanceof TLRPC.TL_channelForbidden) && chat.megagroup; } public static boolean isChannelAndNotMegaGroup(TLRPC.Chat chat) { return isChannel(chat) && !isMegagroup(chat); } public static boolean isBoostSupported(TLRPC.Chat chat) { return isChannelAndNotMegaGroup(chat) || isMegagroup(chat); } public static boolean isBoosted(TLRPC.ChatFull chatFull) { return chatFull != null && chatFull.boosts_applied > 0; } public static boolean isForum(TLRPC.Chat chat) { return chat != null && chat.forum; } public static boolean hasStories(TLRPC.Chat chat) { return chat != null && MessagesController.getInstance(UserConfig.selectedAccount).getStoriesController().hasStories(-chat.id); } public static boolean isMegagroup(int currentAccount, long chatId) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(chatId); return ChatObject.isChannel(chat) && chat.megagroup; } public static boolean hasAdminRights(TLRPC.Chat chat) { return chat != null && (chat.creator || chat.admin_rights != null && chat.admin_rights.flags != 0); } public static boolean canChangeChatInfo(TLRPC.Chat chat) { return canUserDoAction(chat, ACTION_CHANGE_INFO); } public static boolean canAddAdmins(TLRPC.Chat chat) { return canUserDoAction(chat, ACTION_ADD_ADMINS); } public static boolean canBlockUsers(TLRPC.Chat chat) { return canUserDoAction(chat, ACTION_BLOCK_USERS); } public static boolean canManageCalls(TLRPC.Chat chat) { return canUserDoAction(chat, ACTION_MANAGE_CALLS); } public static boolean canSendStickers(TLRPC.Chat chat) { if (isIgnoredChatRestrictionsForBoosters(chat)) { return true; } return canUserDoAction(chat, ACTION_SEND_STICKERS); } public static boolean canSendEmbed(TLRPC.Chat chat) { if (isIgnoredChatRestrictionsForBoosters(chat)) { return true; } return canUserDoAction(chat, ACTION_EMBED_LINKS); } public static boolean canSendPhoto(TLRPC.Chat chat) { if (isIgnoredChatRestrictionsForBoosters(chat)) { return true; } return canUserDoAction(chat, ACTION_SEND_PHOTO); } public static boolean canSendVideo(TLRPC.Chat chat) { if (isIgnoredChatRestrictionsForBoosters(chat)) { return true; } return canUserDoAction(chat, ACTION_SEND_VIDEO); } public static boolean canSendMusic(TLRPC.Chat chat) { if (isIgnoredChatRestrictionsForBoosters(chat)) { return true; } return canUserDoAction(chat, ACTION_SEND_MUSIC); } public static boolean canSendDocument(TLRPC.Chat chat) { if (isIgnoredChatRestrictionsForBoosters(chat)) { return true; } return canUserDoAction(chat, ACTION_SEND_DOCUMENTS); } public static boolean canSendVoice(TLRPC.Chat chat) { if (isIgnoredChatRestrictionsForBoosters(chat)) { return true; } return canUserDoAction(chat, ACTION_SEND_VOICE); } public static boolean canSendRoundVideo(TLRPC.Chat chat) { if (isIgnoredChatRestrictionsForBoosters(chat)) { return true; } return canUserDoAction(chat, ACTION_SEND_ROUND); } public static boolean canSendPolls(TLRPC.Chat chat) { if (isIgnoredChatRestrictionsForBoosters(chat)) { return true; } return canUserDoAction(chat, ACTION_SEND_POLLS); } public static boolean canSendMessages(TLRPC.Chat chat) { if (isIgnoredChatRestrictionsForBoosters(chat)) { return true; } return canUserDoAction(chat, ACTION_SEND); } public static boolean canSendPlain(TLRPC.Chat chat) { if (isIgnoredChatRestrictionsForBoosters(chat)) { return true; } return canUserDoAction(chat, ACTION_SEND_PLAIN); } public static boolean canPost(TLRPC.Chat chat) { return canUserDoAction(chat, ACTION_POST); } public static boolean canAddUsers(TLRPC.Chat chat) { return canUserDoAction(chat, ACTION_INVITE); } public static boolean shouldSendAnonymously(TLRPC.Chat chat) { return chat != null && chat.admin_rights != null && chat.admin_rights.anonymous; } public static long getSendAsPeerId(TLRPC.Chat chat, TLRPC.ChatFull chatFull) { return getSendAsPeerId(chat, chatFull, false); } public static long getSendAsPeerId(TLRPC.Chat chat, TLRPC.ChatFull chatFull, boolean invertChannel) { if (chat != null && chatFull != null && chatFull.default_send_as != null) { TLRPC.Peer p = chatFull.default_send_as; return p.user_id != 0 ? p.user_id : invertChannel ? -p.channel_id : p.channel_id; } if (chat != null && chat.admin_rights != null && chat.admin_rights.anonymous) { return invertChannel ? -chat.id : chat.id; } return UserConfig.getInstance(UserConfig.selectedAccount).getClientUserId(); } public static boolean canAddBotsToChat(TLRPC.Chat chat) { if (isChannel(chat)) { if (chat.megagroup && (chat.admin_rights != null && (chat.admin_rights.post_messages || chat.admin_rights.add_admins) || chat.creator)) { return true; } } else { if (chat.migrated_to == null) { return true; } } return false; } public static boolean canPinMessages(TLRPC.Chat chat) { return canUserDoAction(chat, ACTION_PIN) || ChatObject.isChannel(chat) && !chat.megagroup && chat.admin_rights != null && chat.admin_rights.edit_messages; } public static boolean canCreateTopic(TLRPC.Chat chat) { return canUserDoAction(chat, ACTION_MANAGE_TOPICS); } public static boolean canManageTopics(TLRPC.Chat chat) { return canUserDoAdminAction(chat, ACTION_MANAGE_TOPICS); } public static boolean canManageTopic(int currentAccount, TLRPC.Chat chat, TLRPC.TL_forumTopic topic) { return canManageTopics(chat) || isMyTopic(currentAccount, topic); } public static boolean canManageTopic(int currentAccount, TLRPC.Chat chat, long topicId) { return canManageTopics(chat) || isMyTopic(currentAccount, chat, topicId); } public static boolean canDeleteTopic(int currentAccount, TLRPC.Chat chat, long topicId) { if (topicId == 1) { // general topic can't be deleted return false; } return chat != null && canDeleteTopic(currentAccount, chat, MessagesController.getInstance(currentAccount).getTopicsController().findTopic(chat.id, topicId)); } public static boolean canDeleteTopic(int currentAccount, TLRPC.Chat chat, TLRPC.TL_forumTopic topic) { if (topic != null && topic.id == 1) { // general topic can't be deleted return false; } return canUserDoAction(chat, ACTION_DELETE_MESSAGES) || isMyTopic(currentAccount, topic) && topic.topMessage != null && topic.topicStartMessage != null && topic.topMessage.id - topic.topicStartMessage.id <= Math.max(1, topic.groupedMessages == null ? 0 : topic.groupedMessages.size()) && MessageObject.peersEqual(topic.from_id, topic.topMessage.from_id); } public static boolean isMyTopic(int currentAccount, TLRPC.TL_forumTopic topic) { return topic != null && (topic.my || topic.from_id instanceof TLRPC.TL_peerUser && topic.from_id.user_id == UserConfig.getInstance(currentAccount).clientUserId); } public static boolean isMyTopic(int currentAccount, TLRPC.Chat chat, long topicId) { return chat != null && chat.forum && isMyTopic(currentAccount, chat.id, topicId); } public static boolean isMyTopic(int currentAccount, long chatId, long topicId) { return isMyTopic(currentAccount, MessagesController.getInstance(currentAccount).getTopicsController().findTopic(chatId, topicId)); } public static boolean isChannel(long chatId, int currentAccount) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(chatId); return chat instanceof TLRPC.TL_channel || chat instanceof TLRPC.TL_channelForbidden; } public static boolean isChannelAndNotMegaGroup(long chatId, int currentAccount) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(chatId); return isChannelAndNotMegaGroup(chat); } public static boolean isCanWriteToChannel(long chatId, int currentAccount) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(chatId); return ChatObject.canSendMessages(chat) || chat.megagroup; } public static boolean canWriteToChat(TLRPC.Chat chat) { return !isChannel(chat) || chat.creator || chat.admin_rights != null && chat.admin_rights.post_messages || !chat.broadcast && !chat.gigagroup || chat.gigagroup && ChatObject.hasAdminRights(chat); } public static String getBannedRightsString(TLRPC.TL_chatBannedRights bannedRights) { String currentBannedRights = ""; currentBannedRights += bannedRights.view_messages ? 1 : 0; currentBannedRights += bannedRights.send_messages ? 1 : 0; currentBannedRights += bannedRights.send_media ? 1 : 0; currentBannedRights += bannedRights.send_stickers ? 1 : 0; currentBannedRights += bannedRights.send_gifs ? 1 : 0; currentBannedRights += bannedRights.send_games ? 1 : 0; currentBannedRights += bannedRights.send_inline ? 1 : 0; currentBannedRights += bannedRights.embed_links ? 1 : 0; currentBannedRights += bannedRights.send_polls ? 1 : 0; currentBannedRights += bannedRights.invite_users ? 1 : 0; currentBannedRights += bannedRights.change_info ? 1 : 0; currentBannedRights += bannedRights.pin_messages ? 1 : 0; currentBannedRights += bannedRights.manage_topics ? 1 : 0; currentBannedRights += bannedRights.send_photos ? 1 : 0; currentBannedRights += bannedRights.send_videos ? 1 : 0; currentBannedRights += bannedRights.send_roundvideos ? 1 : 0; currentBannedRights += bannedRights.send_voices ? 1 : 0; currentBannedRights += bannedRights.send_audios ? 1 : 0; currentBannedRights += bannedRights.send_docs ? 1 : 0; currentBannedRights += bannedRights.send_plain ? 1 : 0; currentBannedRights += bannedRights.until_date; return currentBannedRights; } public static boolean hasPhoto(TLRPC.Chat chat) { return chat != null && chat.photo != null && !(chat.photo instanceof TLRPC.TL_chatPhotoEmpty); } public static TLRPC.ChatPhoto getPhoto(TLRPC.Chat chat) { return hasPhoto(chat) ? chat.photo : null; } public static String getPublicUsername(TLRPC.Chat chat) { return getPublicUsername(chat, false); } public static String getPublicUsername(TLRPC.Chat chat, boolean editable) { if (chat == null) { return null; } if (!TextUtils.isEmpty(chat.username) && !editable) { return chat.username; } if (chat.usernames != null) { for (int i = 0; i < chat.usernames.size(); ++i) { TLRPC.TL_username u = chat.usernames.get(i); if (u != null && (u.active && !editable || u.editable) && !TextUtils.isEmpty(u.username)) { return u.username; } } } if (!TextUtils.isEmpty(chat.username) && editable && (chat.usernames == null || chat.usernames.size() <= 0)) { return chat.username; } return null; } public static boolean hasPublicLink(TLRPC.Chat chat, String username) { if (chat == null) { return false; } if (!TextUtils.isEmpty(chat.username)) { return chat.username.equalsIgnoreCase(username); } if (chat.usernames != null) { for (int i = 0; i < chat.usernames.size(); ++i) { TLRPC.TL_username u = chat.usernames.get(i); if (u != null && u.active && !TextUtils.isEmpty(u.username) && u.username.equalsIgnoreCase(username)) { return true; } } } return false; } public static boolean isPublic(TLRPC.Chat chat) { return !TextUtils.isEmpty(getPublicUsername(chat)); } public static String getRestrictedErrorText(TLRPC.Chat chat, int action) { if (action == ACTION_SEND_GIFS) { if (chat == null || ChatObject.isActionBannedByDefault(chat, action)) { return LocaleController.getString("GlobalAttachGifRestricted", R.string.GlobalAttachGifRestricted); } else if (AndroidUtilities.isBannedForever(chat.banned_rights)) { return LocaleController.formatString("AttachGifRestrictedForever", R.string.AttachGifRestrictedForever); } else { return LocaleController.formatString("AttachGifRestricted", R.string.AttachGifRestricted, LocaleController.formatDateForBan(chat.banned_rights.until_date)); } } else if (action == ACTION_SEND_STICKERS) { if (chat == null || ChatObject.isActionBannedByDefault(chat, action)) { return LocaleController.getString("GlobalAttachStickersRestricted", R.string.GlobalAttachStickersRestricted); } else if (AndroidUtilities.isBannedForever(chat.banned_rights)) { return LocaleController.formatString("AttachStickersRestrictedForever", R.string.AttachStickersRestrictedForever); } else { return LocaleController.formatString("AttachStickersRestricted", R.string.AttachStickersRestricted, LocaleController.formatDateForBan(chat.banned_rights.until_date)); } } else if (action == ACTION_SEND_PHOTO) { if (chat == null || ChatObject.isActionBannedByDefault(chat, action)) { return LocaleController.getString("GlobalAttachPhotoRestricted", R.string.GlobalAttachPhotoRestricted); } else if (AndroidUtilities.isBannedForever(chat.banned_rights)) { return LocaleController.formatString("AttachPhotoRestrictedForever", R.string.AttachPhotoRestrictedForever); } else { return LocaleController.formatString("AttachPhotoRestricted", R.string.AttachPhotoRestricted, LocaleController.formatDateForBan(chat.banned_rights.until_date)); } } else if (action == ACTION_SEND_VIDEO) { if (chat == null || ChatObject.isActionBannedByDefault(chat, action)) { return LocaleController.getString("GlobalAttachVideoRestricted", R.string.GlobalAttachVideoRestricted); } else if (AndroidUtilities.isBannedForever(chat.banned_rights)) { return LocaleController.formatString("AttachVideoRestrictedForever", R.string.AttachVideoRestrictedForever); } else { return LocaleController.formatString("AttachVideoRestricted", R.string.AttachVideoRestricted, LocaleController.formatDateForBan(chat.banned_rights.until_date)); } } else if (action == ACTION_SEND_DOCUMENTS) { if (chat == null || ChatObject.isActionBannedByDefault(chat, action)) { return LocaleController.getString("GlobalAttachDocumentsRestricted", R.string.GlobalAttachDocumentsRestricted); } else if (AndroidUtilities.isBannedForever(chat.banned_rights)) { return LocaleController.formatString("AttachDocumentsRestrictedForever", R.string.AttachDocumentsRestrictedForever); } else { return LocaleController.formatString("AttachDocumentsRestricted", R.string.AttachDocumentsRestricted, LocaleController.formatDateForBan(chat.banned_rights.until_date)); } } else if (action == ACTION_SEND_MEDIA) { if (chat == null || ChatObject.isActionBannedByDefault(chat, action)) { return LocaleController.getString("GlobalAttachMediaRestricted", R.string.GlobalAttachMediaRestricted); } else if (AndroidUtilities.isBannedForever(chat.banned_rights)) { return LocaleController.formatString("AttachMediaRestrictedForever", R.string.AttachMediaRestrictedForever); } else { return LocaleController.formatString("AttachMediaRestricted", R.string.AttachMediaRestricted, LocaleController.formatDateForBan(chat.banned_rights.until_date)); } } else if (action == ACTION_SEND_MUSIC) { if (chat == null || ChatObject.isActionBannedByDefault(chat, action)) { return LocaleController.getString("GlobalAttachAudioRestricted", R.string.GlobalAttachAudioRestricted); } else if (AndroidUtilities.isBannedForever(chat.banned_rights)) { return LocaleController.formatString("AttachAudioRestrictedForever", R.string.AttachAudioRestrictedForever); } else { return LocaleController.formatString("AttachAudioRestricted", R.string.AttachAudioRestricted, LocaleController.formatDateForBan(chat.banned_rights.until_date)); } } else if (action == ACTION_SEND_PLAIN) { if (chat == null || ChatObject.isActionBannedByDefault(chat, action)) { return LocaleController.getString("GlobalAttachPlainRestricted", R.string.GlobalAttachPlainRestricted); } else if (AndroidUtilities.isBannedForever(chat.banned_rights)) { return LocaleController.formatString("AttachPlainRestrictedForever", R.string.AttachPlainRestrictedForever); } else { return LocaleController.formatString("AttachPlainRestricted", R.string.AttachPlainRestricted, LocaleController.formatDateForBan(chat.banned_rights.until_date)); } } else if (action == ACTION_SEND_ROUND) { if (chat == null || ChatObject.isActionBannedByDefault(chat, action)) { return LocaleController.getString("GlobalAttachRoundRestricted", R.string.GlobalAttachRoundRestricted); } else if (AndroidUtilities.isBannedForever(chat.banned_rights)) { return LocaleController.formatString("AttachRoundRestrictedForever", R.string.AttachRoundRestrictedForever); } else { return LocaleController.formatString("AttachRoundRestricted", R.string.AttachRoundRestricted, LocaleController.formatDateForBan(chat.banned_rights.until_date)); } } else if (action == ACTION_SEND_VOICE) { if (chat == null || ChatObject.isActionBannedByDefault(chat, action)) { return LocaleController.getString("GlobalAttachVoiceRestricted", R.string.GlobalAttachVoiceRestricted); } else if (AndroidUtilities.isBannedForever(chat.banned_rights)) { return LocaleController.formatString("AttachVoiceRestrictedForever", R.string.AttachVoiceRestrictedForever); } else { return LocaleController.formatString("AttachVoiceRestricted", R.string.AttachVoiceRestricted, LocaleController.formatDateForBan(chat.banned_rights.until_date)); } } return ""; } public static class VideoParticipant { public TLRPC.TL_groupCallParticipant participant; public boolean presentation; public boolean hasSame; public float aspectRatio;// w / h public int aspectRatioFromWidth; public int aspectRatioFromHeight; public VideoParticipant(TLRPC.TL_groupCallParticipant participant, boolean presentation, boolean hasSame) { this.participant = participant; this.presentation = presentation; this.hasSame = hasSame; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } VideoParticipant that = (VideoParticipant) o; return presentation == that.presentation && MessageObject.getPeerId(participant.peer) == MessageObject.getPeerId(that.participant.peer); } public void setAspectRatio(int width, int height, Call call) { aspectRatioFromWidth = width; aspectRatioFromHeight = height; setAspectRatio(width / (float) height, call); } private void setAspectRatio(float aspectRatio, Call call) { if (this.aspectRatio != aspectRatio) { this.aspectRatio = aspectRatio; if (!GroupCallActivity.isLandscapeMode && call.visibleVideoParticipants.size() % 2 == 1) { call.updateVisibleParticipants(); } } } } public static MessagesController.PeerColor getPeerColorForAvatar(int currentAccount, TLRPC.Chat chat) { // if (chat != null && chat.profile_color != null && chat.profile_color.color >= 0 && MessagesController.getInstance(currentAccount).profilePeerColors != null) { // return MessagesController.getInstance(currentAccount).profilePeerColors.getColor(chat.profile_color.color); // } return null; } public static int getColorId(TLRPC.Chat chat) { if (chat == null) return 0; if (chat.color != null && (chat.color.flags & 1) != 0) return chat.color.color; return (int) (chat.id % 7); } public static long getEmojiId(TLRPC.Chat chat) { if (chat != null && chat.color != null && (chat.color.flags & 2) != 0) return chat.color.background_emoji_id; return 0; } public static int getProfileColorId(TLRPC.Chat chat) { if (chat == null) return 0; if (chat.profile_color != null && (chat.profile_color.flags & 1) != 0) return chat.profile_color.color; return -1; } public static long getProfileEmojiId(TLRPC.Chat chat) { if (chat != null && chat.profile_color != null && (chat.profile_color.flags & 2) != 0) return chat.profile_color.background_emoji_id; return 0; } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/messenger/ChatObject.java
41,654
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.common.util; import static com.facebook.infer.annotation.Assertions.assumeNotNull; import android.content.ContentResolver; import android.content.res.AssetFileDescriptor; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.provider.ContactsContract; import android.provider.DocumentsContract; import android.provider.MediaStore; import com.facebook.common.internal.Preconditions; import com.facebook.infer.annotation.Nullsafe; import com.facebook.infer.annotation.PropagatesNullable; import java.io.File; import java.io.FileNotFoundException; import java.net.URL; import javax.annotation.Nullable; @Nullsafe(Nullsafe.Mode.STRICT) public class UriUtil { /** http scheme for URIs */ public static final String HTTP_SCHEME = "http"; public static final String HTTPS_SCHEME = "https"; /** File scheme for URIs */ public static final String LOCAL_FILE_SCHEME = "file"; /** Content URI scheme for URIs */ public static final String LOCAL_CONTENT_SCHEME = "content"; /** URI prefix (including scheme) for contact photos */ private static final Uri LOCAL_CONTACT_IMAGE_URI = Uri.withAppendedPath(assumeNotNull(ContactsContract.AUTHORITY_URI), "display_photo"); /** Asset scheme for URIs */ public static final String LOCAL_ASSET_SCHEME = "asset"; /** Resource scheme for URIs */ public static final String LOCAL_RESOURCE_SCHEME = "res"; /** * Resource scheme for fully qualified resources which might have a package name that is different * than the application one. This has the constant value of "android.resource". */ public static final String QUALIFIED_RESOURCE_SCHEME = ContentResolver.SCHEME_ANDROID_RESOURCE; /** Data scheme for URIs */ public static final String DATA_SCHEME = "data"; /** * Convert android.net.Uri to java.net.URL as necessary for some networking APIs. * * @param uri uri to convert * @return url pointing to the same resource as uri */ @Nullable public static URL uriToUrl(@PropagatesNullable @Nullable Uri uri) { if (uri == null) { return null; } try { return new URL(uri.toString()); } catch (java.net.MalformedURLException e) { // This should never happen since we got a valid uri throw new RuntimeException(e); } } /** * Check if uri represents network resource * * @param uri uri to check * @return true if uri's scheme is equal to "http" or "https" */ public static boolean isNetworkUri(@Nullable Uri uri) { final String scheme = getSchemeOrNull(uri); return HTTPS_SCHEME.equals(scheme) || HTTP_SCHEME.equals(scheme); } /** * Check if uri represents local file * * @param uri uri to check * @return true if uri's scheme is equal to "file" */ public static boolean isLocalFileUri(@Nullable Uri uri) { final String scheme = getSchemeOrNull(uri); return LOCAL_FILE_SCHEME.equals(scheme); } /** * Check if uri represents local content * * @param uri uri to check * @return true if uri's scheme is equal to "content" */ public static boolean isLocalContentUri(@Nullable Uri uri) { final String scheme = getSchemeOrNull(uri); return LOCAL_CONTENT_SCHEME.equals(scheme); } /** * Checks if the given URI is a general Contact URI, and not a specific display photo. * * @param uri the URI to check * @return true if the uri is a Contact URI, and is not already specifying a display photo. */ public static boolean isLocalContactUri(Uri uri) { if (uri.getPath() == null) { return false; } return isLocalContentUri(uri) && ContactsContract.AUTHORITY.equals(uri.getAuthority()) && !uri.getPath().startsWith(assumeNotNull(LOCAL_CONTACT_IMAGE_URI.getPath())); } /** * Checks if the given URI is for a photo from the device's local media store. * * @param uri the URI to check * @return true if the URI points to a media store photo */ public static boolean isLocalCameraUri(Uri uri) { String uriString = uri.toString(); return uriString.startsWith(MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString()) || uriString.startsWith(MediaStore.Images.Media.INTERNAL_CONTENT_URI.toString()); } /** * Check if uri represents local asset * * @param uri uri to check * @return true if uri's scheme is equal to "asset" */ public static boolean isLocalAssetUri(@Nullable Uri uri) { final String scheme = getSchemeOrNull(uri); return LOCAL_ASSET_SCHEME.equals(scheme); } /** * Check if uri represents local resource * * @param uri uri to check * @return true if uri's scheme is equal to {@link #LOCAL_RESOURCE_SCHEME} */ public static boolean isLocalResourceUri(@Nullable Uri uri) { final String scheme = getSchemeOrNull(uri); return LOCAL_RESOURCE_SCHEME.equals(scheme); } /** * Check if uri represents fully qualified resource URI. * * @param uri uri to check * @return true if uri's scheme is equal to {@link #QUALIFIED_RESOURCE_SCHEME} */ public static boolean isQualifiedResourceUri(@Nullable Uri uri) { final String scheme = getSchemeOrNull(uri); return QUALIFIED_RESOURCE_SCHEME.equals(scheme); } /** Check if the uri is a data uri */ public static boolean isDataUri(@Nullable Uri uri) { return DATA_SCHEME.equals(getSchemeOrNull(uri)); } /** * @param uri uri to extract scheme from, possibly null * @return null if uri is null, result of uri.getScheme() otherwise */ @Nullable public static String getSchemeOrNull(@Nullable Uri uri) { return uri == null ? null : uri.getScheme(); } /** * A wrapper around {@link Uri#parse} that returns null if the input is null. * * @param uriAsString the uri as a string * @return the parsed Uri or null if the input was null */ public static @Nullable Uri parseUriOrNull(@Nullable String uriAsString) { return uriAsString != null ? Uri.parse(uriAsString) : null; } /** * Get the path of a file from the Uri. * * @param contentResolver the content resolver which will query for the source file * @param srcUri The source uri * @return The Path for the file or null if doesn't exists */ @Nullable public static String getRealPathFromUri(ContentResolver contentResolver, final Uri srcUri) { String result = null; Uri uri = srcUri; String mimeTypeString = contentResolver.getType(uri); if (isLocalContentUri(uri)) { boolean isVideo = mimeTypeString != null && mimeTypeString.startsWith("video/"); String selection = null; String[] selectionArgs = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && "com.android.providers.media.documents".equals(uri.getAuthority())) { String documentId = DocumentsContract.getDocumentId(uri); Preconditions.checkNotNull(documentId); uri = Preconditions.checkNotNull(getExternalContentUri(isVideo)); selection = getMediaIdString(isVideo) + "=?"; selectionArgs = new String[] {documentId.split(":")[1]}; } Cursor cursor = contentResolver.query( uri, new String[] {getDataPathString(isVideo)}, selection, selectionArgs, null); try { if (cursor != null && cursor.moveToFirst()) { int idx = cursor.getColumnIndexOrThrow(getDataPathString(isVideo)); if (idx != -1) { result = cursor.getString(idx); } } } finally { if (cursor != null) { cursor.close(); } } } else if (isLocalFileUri(uri)) { result = uri.getPath(); } return result; } private static Uri getExternalContentUri(boolean isVideo) { return isVideo ? MediaStore.Video.Media.EXTERNAL_CONTENT_URI : MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } private static String getMediaIdString(boolean isVideo) { return isVideo ? MediaStore.Video.Media._ID : MediaStore.Images.Media._ID; } private static String getDataPathString(boolean isVideo) { return isVideo ? MediaStore.Video.Media.DATA : MediaStore.Images.Media.DATA; } /** * Gets the AssetFileDescriptor for a local file. This offers an alternative solution for opening * content:// scheme files * * @param contentResolver the content resolver which will query for the source file * @param srcUri The source uri * @return The AssetFileDescriptor for the file or null if it doesn't exist */ @Nullable public static AssetFileDescriptor getAssetFileDescriptor( ContentResolver contentResolver, final Uri srcUri) { if (isLocalContentUri(srcUri)) { try { return contentResolver.openAssetFileDescriptor(srcUri, "r"); } catch (FileNotFoundException e) { return null; } } return null; } /** * Returns a URI for a given file using {@link Uri#fromFile(File)}. * * @param file a file with a valid path * @return the URI */ public static Uri getUriForFile(File file) { return Uri.fromFile(file); } /** * Return a URI for the given resource ID. The returned URI consists of a {@link * #LOCAL_RESOURCE_SCHEME} scheme and the resource ID as path. * * @param resourceId the resource ID to use * @return the URI */ public static Uri getUriForResourceId(int resourceId) { return new Uri.Builder().scheme(LOCAL_RESOURCE_SCHEME).path(String.valueOf(resourceId)).build(); } /** * Returns a URI for the given resource ID in the given package. Use this method only if you need * to specify a package name different to your application's main package. * * @param packageName a package name (e.g. com.facebook.myapp.plugin) * @param resourceId to resource ID to use * @return the URI */ public static Uri getUriForQualifiedResource(String packageName, int resourceId) { return new Uri.Builder() .scheme(QUALIFIED_RESOURCE_SCHEME) .authority(packageName) .path(String.valueOf(resourceId)) .build(); } }
facebook/fresco
fbcore/src/main/java/com/facebook/common/util/UriUtil.java
41,655
package edu.stanford.nlp.ie; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Properties; import java.util.Set; import java.util.stream.Collectors; import edu.stanford.nlp.io.IOUtils; import edu.stanford.nlp.io.RuntimeIOException; import edu.stanford.nlp.ie.crf.CRFClassifier; import edu.stanford.nlp.ie.ner.CMMClassifier; import edu.stanford.nlp.ling.CoreAnnotations; import edu.stanford.nlp.ling.CoreLabel; import edu.stanford.nlp.ling.HasWord; import edu.stanford.nlp.pipeline.DefaultPaths; import edu.stanford.nlp.sequences.DocumentReaderAndWriter; import edu.stanford.nlp.sequences.SeqClassifierFlags; import edu.stanford.nlp.util.CoreMap; import edu.stanford.nlp.util.ErasureUtils; import edu.stanford.nlp.util.Generics; import edu.stanford.nlp.util.StringUtils; import edu.stanford.nlp.util.PropertiesUtils; import edu.stanford.nlp.util.logging.Redwood; /** * Merges the outputs of two or more AbstractSequenceClassifiers according to * a simple precedence scheme: any given base classifier contributes only * classifications of labels that do not exist in the base classifiers specified * before, and that do not have any token overlap with labels assigned by * higher priority classifiers. * <p> * This is a pure AbstractSequenceClassifier, i.e., it sets the AnswerAnnotation label. * If you work with NER classifiers, you should use NERClassifierCombiner. This class * inherits from ClassifierCombiner, and takes care that all AnswerAnnotations are also * copied to NERAnnotation. * <p> * You can specify up to 10 base classifiers using the -loadClassifier1 to -loadClassifier10 * properties. We also maintain the older usage when only two base classifiers were accepted, * specified using -loadClassifier and -loadAuxClassifier. * <p> * ms 2009: removed all NER functionality (see NERClassifierCombiner), changed code so it * accepts an arbitrary number of base classifiers, removed dead code. * * @author Chris Cox * @author Mihai Surdeanu */ public class ClassifierCombiner<IN extends CoreMap & HasWord> extends AbstractSequenceClassifier<IN> { /** A logger for this class */ private static final Redwood.RedwoodChannels log = Redwood.channels(ClassifierCombiner.class); private static final boolean DEBUG = System.getProperty("ClassifierCombiner", null) != null; private List<AbstractSequenceClassifier<IN>> baseClassifiers; /** * NORMAL means that if one classifier uses PERSON, later classifiers can't also add PERSON, for example. <br> * HIGH_RECALL allows later models do set PERSON as long as it doesn't clobber existing annotations. */ enum CombinationMode { NORMAL, HIGH_RECALL } private static final CombinationMode DEFAULT_COMBINATION_MODE = CombinationMode.NORMAL; private static final String COMBINATION_MODE_PROPERTY = "ner.combinationMode"; private final CombinationMode combinationMode; // keep track of properties used to initialize private final Properties initProps; // keep track of paths used to load CRFs private List<String> initLoadPaths = new ArrayList<>(); /** * @param p Properties File that specifies {@code loadClassifier} * and {@code loadAuxClassifier} properties or, alternatively, {@code loadClassifier[1-10]} properties. * @throws FileNotFoundException If classifier files not found */ public ClassifierCombiner(Properties p) throws IOException { super(p); this.combinationMode = extractCombinationModeSafe(p); String loadPath1, loadPath2; List<String> paths = new ArrayList<>(); // // preferred configuration: specify up to 10 base classifiers using loadClassifier1 to loadClassifier10 properties // if((loadPath1 = p.getProperty("loadClassifier1")) != null && (loadPath2 = p.getProperty("loadClassifier2")) != null) { paths.add(loadPath1); paths.add(loadPath2); for(int i = 3; i <= 10; i ++){ String path; if ((path = p.getProperty("loadClassifier" + i)) != null) { paths.add(path); } } loadClassifiers(p, paths); } // // second accepted setup (backward compatible): two classifier given in loadClassifier and loadAuxClassifier // else if((loadPath1 = p.getProperty("loadClassifier")) != null && (loadPath2 = p.getProperty("loadAuxClassifier")) != null){ paths.add(loadPath1); paths.add(loadPath2); loadClassifiers(p, paths); } // // fall back strategy: use the two default paths on NLP machines // else { paths.add(DefaultPaths.DEFAULT_NER_THREECLASS_MODEL); paths.add(DefaultPaths.DEFAULT_NER_MUC_MODEL); loadClassifiers(p, paths); } this.initLoadPaths = new ArrayList<>(paths); this.initProps = p; } /** Loads a series of base classifiers from the paths specified using the * Properties specified. * * @param props Properties for the classifier to use (encodings, output format, etc.) * @param combinationMode How to handle multiple classifiers specifying the same entity type * @param loadPaths Paths to the base classifiers * @throws IOException If IO errors in loading classifier files */ public ClassifierCombiner(Properties props, CombinationMode combinationMode, String... loadPaths) throws IOException { super(props); this.combinationMode = combinationMode; List<String> paths = new ArrayList<>(Arrays.asList(loadPaths)); loadClassifiers(props, paths); this.initLoadPaths = new ArrayList<>(paths); this.initProps = props; } /** Loads a series of base classifiers from the paths specified using the * Properties specified. * * @param combinationMode How to handle multiple classifiers specifying the same entity type * @param loadPaths Paths to the base classifiers * @throws IOException If IO errors in loading classifier files */ public ClassifierCombiner(CombinationMode combinationMode, String... loadPaths) throws IOException { this(new Properties(), combinationMode, loadPaths); } /** Loads a series of base classifiers from the paths specified. * * @param loadPaths Paths to the base classifiers * @throws FileNotFoundException If classifier files not found */ public ClassifierCombiner(String... loadPaths) throws IOException { this(DEFAULT_COMBINATION_MODE, loadPaths); } /** Combines a series of base classifiers. * * @param classifiers The base classifiers */ @SafeVarargs public ClassifierCombiner(AbstractSequenceClassifier<IN>... classifiers) { super(new Properties()); this.combinationMode = DEFAULT_COMBINATION_MODE; baseClassifiers = new ArrayList<>(Arrays.asList(classifiers)); flags.backgroundSymbol = baseClassifiers.get(0).flags.backgroundSymbol; this.initProps = new Properties(); } // constructor for building a ClassifierCombiner from an ObjectInputStream public ClassifierCombiner(ObjectInputStream ois, Properties props) throws IOException, ClassNotFoundException, ClassCastException { // read the initial Properties out of the ObjectInputStream so you can properly start the AbstractSequenceClassifier // note now we load in props from command line and overwrite any that are given for command line super(PropertiesUtils.overWriteProperties((Properties) ois.readObject(),props)); // read another copy of initProps that I have helpfully included // TODO: probably set initProps in AbstractSequenceClassifier to avoid this writing twice thing, its hacky this.initProps = PropertiesUtils.overWriteProperties((Properties) ois.readObject(),props); // read the initLoadPaths this.initLoadPaths = (ArrayList<String>) ois.readObject(); // read the combinationMode from the serialized version String cm = (String) ois.readObject(); // see if there is a commandline override for the combinationMode, else set newCM to the serialized version CombinationMode newCM; if (props.getProperty("ner.combinationMode") != null) { // there is a possible commandline override, have to see if its valid try { // see if the commandline has a proper value newCM = CombinationMode.valueOf(props.getProperty("ner.combinationMode")); } catch (IllegalArgumentException e) { // the commandline override did not have a proper value, so just use the serialized version newCM = CombinationMode.valueOf(cm); } } else { // there was no commandline override given, so just use the serialized version newCM = CombinationMode.valueOf(cm); } this.combinationMode = newCM; // read in the base classifiers int numClassifiers = ois.readInt(); // set up the list of base classifiers this.baseClassifiers = new ArrayList<>(); int i = 0; while (i < numClassifiers) { try { log.info("loading CRF..."); CRFClassifier<IN> newCRF = ErasureUtils.uncheckedCast(CRFClassifier.getClassifier(ois, props)); baseClassifiers.add(newCRF); i++; } catch (Exception e) { try { log.info("loading CMM..."); CMMClassifier newCMM = ErasureUtils.uncheckedCast(CMMClassifier.getClassifier(ois, props)); baseClassifiers.add(newCMM); i++; } catch (Exception ex) { throw new IOException("Couldn't load classifier!", ex); } } } } /** * Either finds COMBINATION_MODE_PROPERTY or returns a default value. */ public static CombinationMode extractCombinationMode(Properties p) { String mode = p.getProperty(COMBINATION_MODE_PROPERTY); if (mode == null) { return DEFAULT_COMBINATION_MODE; } else { return CombinationMode.valueOf(mode.toUpperCase(Locale.ROOT)); } } /** * Either finds COMBINATION_MODE_PROPERTY or returns a default * value. If the value is not a legal value, a warning is printed. */ public static CombinationMode extractCombinationModeSafe(Properties p) { try { return extractCombinationMode(p); } catch (IllegalArgumentException e) { log.info("Illegal value of " + COMBINATION_MODE_PROPERTY + ": " + p.getProperty(COMBINATION_MODE_PROPERTY)); log.info(" Legal values:"); for (CombinationMode mode : CombinationMode.values()) { log.info(" " + mode); } log.info(); return CombinationMode.NORMAL; } } private void loadClassifiers(Properties props, List<String> paths) throws IOException { baseClassifiers = new ArrayList<>(); if (PropertiesUtils.getBool(props, "ner.usePresetNERTags", false)) { AbstractSequenceClassifier<IN> presetASC = new PresetSequenceClassifier<>(props); baseClassifiers.add(presetASC); } for (String path: paths){ AbstractSequenceClassifier<IN> cls = loadClassifierFromPath(props, path); baseClassifiers.add(cls); if (DEBUG) { System.err.printf("Successfully loaded classifier #%d from %s.%n", baseClassifiers.size(), path); } } if (baseClassifiers.size() > 0) { flags.backgroundSymbol = baseClassifiers.get(0).flags.backgroundSymbol; } } public static <INN extends CoreMap & HasWord> AbstractSequenceClassifier<INN> loadClassifierFromPath(Properties props, String path) throws IOException { //try loading as a CRFClassifier try { return ErasureUtils.uncheckedCast(CRFClassifier.getClassifier(path, props)); } catch (Exception e) { e.printStackTrace(); } //try loading as a CMMClassifier try { return ErasureUtils.uncheckedCast(CMMClassifier.getClassifier(path)); } catch (Exception e) { //fail //log.info("Couldn't load classifier from path :"+path); throw new IOException("Couldn't load classifier from " + path, e); } } @Override public Set<String> labels() { Set<String> labs = Generics.newHashSet(); for(AbstractSequenceClassifier<? extends CoreMap> cls: baseClassifiers) labs.addAll(cls.labels()); return labs; } /** * Reads the Answer annotations in the given labellings (produced by the base models) * and combines them using a priority ordering, i.e., for a given baseDocument all * labellings seen before in the baseDocuments list have higher priority. * Writes the answer to AnswerAnnotation in the labeling at position 0 * (considered to be the main document). * * @param baseDocuments Results of all base AbstractSequenceClassifier models * @return A List of IN with the combined annotations. (This is an * updating of baseDocuments.get(0), not a new List.) */ private List<IN> mergeDocuments(List<List<IN>> baseDocuments){ // we should only get here if there is something to merge assert(! baseClassifiers.isEmpty() && ! baseDocuments.isEmpty()); // all base outputs MUST have the same length (we generated them internally!) for(int i = 1; i < baseDocuments.size(); i ++) assert(baseDocuments.get(0).size() == baseDocuments.get(i).size()); String background = baseClassifiers.get(0).flags.backgroundSymbol; // baseLabels.get(i) points to the labels assigned by baseClassifiers.get(i) List<Set<String>> baseLabels = new ArrayList<>(); Set<String> seenLabels = Generics.newHashSet(); for (AbstractSequenceClassifier<? extends CoreMap> baseClassifier : baseClassifiers) { Set<String> labs = baseClassifier.labels(); if (combinationMode != CombinationMode.HIGH_RECALL) { labs.removeAll(seenLabels); } else { labs.remove(baseClassifier.flags.backgroundSymbol); labs.remove(background); } seenLabels.addAll(labs); baseLabels.add(labs); } if (DEBUG) { for(int i = 0; i < baseLabels.size(); i ++) log.info("mergeDocuments: Using classifier #" + i + " for " + baseLabels.get(i)); log.info("mergeDocuments: Background symbol is " + background); log.info("Base model outputs:"); for( int i = 0; i < baseDocuments.size(); i ++){ System.err.printf("Output of model #%d:", i); for (IN l : baseDocuments.get(i)) { log.info(' '); log.info(l.get(CoreAnnotations.AnswerAnnotation.class)); } log.info(); } } // incrementally merge each additional model with the main model (i.e., baseDocuments.get(0)) // this keeps adding labels from the additional models to mainDocument // hence, when all is done, mainDocument contains the labels of all base models List<IN> mainDocument = baseDocuments.get(0); for (int i = 1; i < baseDocuments.size(); i ++) { mergeTwoDocuments(mainDocument, baseDocuments.get(i), baseLabels.get(i), background); } if (DEBUG) { log.info("Output of combined model:"); for (IN l: mainDocument) { log.info(' '); log.info(l.get(CoreAnnotations.AnswerAnnotation.class)); } log.info(); log.info(); } return mainDocument; } /** This merges in labels from the auxDocument into the mainDocument when * tokens have one of the labels in auxLabels, and the subsequence * labeled with this auxLabel does not conflict with any non-background * labelling in the mainDocument. */ static <INN extends CoreMap & HasWord> void mergeTwoDocuments(List<INN> mainDocument, List<INN> auxDocument, Set<String> auxLabels, String background) { boolean insideAuxTag = false; boolean auxTagValid = true; String prevAnswer = background; Double prevAnswerProb = null; Collection<INN> constituents = new ArrayList<>(); Iterator<INN> auxIterator = auxDocument.listIterator(); for (INN wMain : mainDocument) { String mainAnswer = wMain.get(CoreAnnotations.AnswerAnnotation.class); INN wAux = auxIterator.next(); String auxAnswer = wAux.get(CoreAnnotations.AnswerAnnotation.class); Double auxAnswerProb = wAux.get(CoreAnnotations.AnswerProbAnnotation.class); boolean insideMainTag = !mainAnswer.equals(background); /* if the auxiliary classifier gave it one of the labels unique to auxClassifier, we might set the mainLabel to that. */ if (auxLabels.contains(auxAnswer)) { if ( ! prevAnswer.equals(auxAnswer) && ! prevAnswer.equals(background)) { if (auxTagValid){ for (INN wi : constituents) { wi.set(CoreAnnotations.AnswerAnnotation.class, prevAnswer); if (prevAnswerProb != null) wi.set(CoreAnnotations.AnswerProbAnnotation.class, prevAnswerProb); } } auxTagValid = true; constituents = new ArrayList<>(); } insideAuxTag = true; if (insideMainTag) { auxTagValid = false; } prevAnswer = auxAnswer; prevAnswerProb = auxAnswerProb; constituents.add(wMain); } else { if (insideAuxTag) { if (auxTagValid){ for (INN wi : constituents) { wi.set(CoreAnnotations.AnswerAnnotation.class, prevAnswer); if (prevAnswerProb != null) wi.set(CoreAnnotations.AnswerProbAnnotation.class, prevAnswerProb); } } constituents = new ArrayList<>(); } insideAuxTag=false; auxTagValid = true; prevAnswer = background; prevAnswerProb = null; } } // deal with a sequence final auxLabel if (auxTagValid){ for (INN wi : constituents) { wi.set(CoreAnnotations.AnswerAnnotation.class, prevAnswer); if (prevAnswerProb != null) wi.set(CoreAnnotations.AnswerProbAnnotation.class, prevAnswerProb); } } } /** * Generates the AnswerAnnotation labels of the combined model for the given * tokens, storing them in place in the tokens. * * @param tokens A List of IN * @return The passed in parameters, which will have the AnswerAnnotation field added/overwritten */ @Override public List<IN> classify(List<IN> tokens) { if (baseClassifiers.isEmpty()) { return tokens; } List<List<IN>> baseOutputs = new ArrayList<>(); // the first base model works in place, modifying the original tokens List<IN> output = baseClassifiers.get(0).classifySentence(tokens); // classify(List<IN>) is supposed to work in place, so add AnswerAnnotation to tokens! for (int i = 0, sz = output.size(); i < sz; i++) { tokens.get(i).set(CoreAnnotations.AnswerAnnotation.class, output.get(i).get(CoreAnnotations.AnswerAnnotation.class)); tokens.get(i).set(CoreAnnotations.AnswerProbAnnotation.class, output.get(i).get(CoreAnnotations.AnswerProbAnnotation.class)); } baseOutputs.add(tokens); for (int i = 1, sz = baseClassifiers.size(); i < sz; i ++) { //List<CoreLabel> copy = deepCopy(tokens); // no need for deep copy: classifySentence creates a copy of the input anyway // List<CoreLabel> copy = tokens; output = baseClassifiers.get(i).classifySentence(tokens); baseOutputs.add(output); } assert(baseOutputs.size() == baseClassifiers.size()); return mergeDocuments(baseOutputs); } @Override public void train(Collection<List<IN>> docs, DocumentReaderAndWriter<IN> readerAndWriter) { throw new UnsupportedOperationException(); } // write a ClassifierCombiner to disk, this is based on CRFClassifier code @Override public void serializeClassifier(String serializePath) { log.info("Serializing classifier to " + serializePath + "..."); ObjectOutputStream oos = null; try { oos = IOUtils.writeStreamFromString(serializePath); serializeClassifier(oos); log.info("done."); } catch (Exception e) { throw new RuntimeIOException("Failed to save classifier", e); } finally { IOUtils.closeIgnoringExceptions(oos); } } // method for writing a ClassifierCombiner to an ObjectOutputStream @Override public void serializeClassifier(ObjectOutputStream oos) { try { // record the properties used to initialize oos.writeObject(initProps); // this is a bit of a hack, but have to write this twice so you can get it again // after you initialize AbstractSequenceClassifier // basically when this is read from the ObjectInputStream, I read it once to call // super(props) and then I read it again so I can set this.initProps // TODO: probably should have AbstractSequenceClassifier store initProps to get rid of this double writing oos.writeObject(initProps); // record the initial loadPaths oos.writeObject(initLoadPaths); // record the combinationMode String combinationModeString = combinationMode.name(); oos.writeObject(combinationModeString); // get the number of classifiers to write to disk int numClassifiers = baseClassifiers.size(); oos.writeInt(numClassifiers); // go through baseClassifiers and write each one to disk with CRFClassifier's serialize method log.info(""); for (AbstractSequenceClassifier<IN> asc : baseClassifiers) { //CRFClassifier crfc = (CRFClassifier) asc; //log.info("Serializing a base classifier..."); asc.serializeClassifier(oos); } } catch (IOException e) { throw new RuntimeIOException(e); } } @Override public void loadClassifier(ObjectInputStream in, Properties props) throws IOException, ClassCastException, ClassNotFoundException { throw new UnsupportedOperationException(); } @Override public List<IN> classifyWithGlobalInformation(List<IN> tokenSeq, CoreMap doc, CoreMap sent) { return classify(tokenSeq); } // static method for getting a ClassifierCombiner from a string path public static ClassifierCombiner getClassifier(String loadPath, Properties props) throws IOException, ClassNotFoundException, ClassCastException { ObjectInputStream ois = IOUtils.readStreamFromString(loadPath); ClassifierCombiner returnCC = getClassifier(ois, props); IOUtils.closeIgnoringExceptions(ois); return returnCC; } // static method for getting a ClassifierCombiner from ObjectInputStream public static ClassifierCombiner getClassifier(ObjectInputStream ois, Properties props) throws IOException, ClassCastException, ClassNotFoundException { return new ClassifierCombiner(ois, props); } // Run a particular CRF of this ClassifierCombiner on a testFile. // User can say -crfToExamine 0 to get 1st element or -crfToExamine /edu/stanford/models/muc7.crf.ser.gz . // This does not currently support drill down on CMMs. public static void examineCRF(ClassifierCombiner cc, String crfNameOrIndex, SeqClassifierFlags flags, String testFile, String testFiles, DocumentReaderAndWriter<CoreLabel> readerAndWriter) throws Exception { CRFClassifier<CoreLabel> crf; // potential index into baseClassifiers int ci; // set ci with the following rules // 1. first see if ci is an index into baseClassifiers // 2. if its not an integer or wrong size, see if its a file name of a loadPath try { ci = Integer.parseInt(crfNameOrIndex); if (ci < 0 || ci >= cc.baseClassifiers.size()) { // ci is not an int corresponding to an element in baseClassifiers, see if name of a crf loadPath ci = cc.initLoadPaths.indexOf(crfNameOrIndex); } } catch (NumberFormatException e) { // cannot interpret crfNameOrIndex as an integer, see if name of a crf loadPath ci = cc.initLoadPaths.indexOf(crfNameOrIndex); } // if ci corresponds to an index in baseClassifiers, get the crf at that index, otherwise set crf to null if (ci >= 0 && ci < cc.baseClassifiers.size()) { // TODO: this will break if baseClassifiers contains something that is not a CRF crf = (CRFClassifier<CoreLabel>) cc.baseClassifiers.get(ci); } else { crf = null; } // if you can get a specific crf, generate the appropriate report, if null do nothing if (crf != null) { // if there is a crf and testFile was set , do the crf stuff for a single testFile if (testFile != null) { if (flags.searchGraphPrefix != null) { crf.classifyAndWriteViterbiSearchGraph(testFile, flags.searchGraphPrefix, crf.makeReaderAndWriter()); } else if (flags.printFirstOrderProbs) { crf.printFirstOrderProbs(testFile, readerAndWriter); } else if (flags.printFactorTable) { crf.printFactorTable(testFile, readerAndWriter); } else if (flags.printProbs) { crf.printProbs(testFile, readerAndWriter); } else if (flags.useKBest) { // TO DO: handle if user doesn't provide kBest int k = flags.kBest; crf.classifyAndWriteAnswersKBest(testFile, k, readerAndWriter); } else if (flags.printLabelValue) { crf.printLabelInformation(testFile, readerAndWriter); } else { // no crf test flag provided log.info("Warning: no crf test flag was provided, running classify and write answers"); crf.classifyAndWriteAnswers(testFile,readerAndWriter,true); } } else if (testFiles != null) { // if there is a crf and testFiles was set , do the crf stuff for testFiles // if testFile was set as well, testFile overrides List<File> files = Arrays.stream(testFiles.split(",")).map(File::new).collect(Collectors.toList()); if (flags.printProbs) { // there is a crf and printProbs crf.printProbs(files, crf.defaultReaderAndWriter()); } else { log.info("Warning: no crf test flag was provided, running classify files and write answers"); crf.classifyFilesAndWriteAnswers(files, crf.defaultReaderAndWriter(), true); } } } } // show some info about a ClassifierCombiner public static void showCCInfo(ClassifierCombiner cc) { log.info(""); log.info("classifiers used:"); log.info(""); if (cc.initLoadPaths.size() == cc.baseClassifiers.size()) { for (int i = 0 ; i < cc.initLoadPaths.size() ; i++) { log.info("baseClassifiers index "+i+" : "+cc.initLoadPaths.get(i)); } } else { for (int i = 0 ; i < cc.initLoadPaths.size() ; i++) { log.info("baseClassifiers index "+i); } } log.info(""); log.info("combinationMode: "+cc.combinationMode); log.info(""); } /** * Some basic testing of the ClassifierCombiner. * * @param args Command-line arguments as properties: -loadClassifier1 serializedFile -loadClassifier2 serializedFile * @throws Exception If IO or serialization error loading classifiers */ public static void main(String[] args) throws Exception { Properties props = StringUtils.argsToProperties(args); ClassifierCombiner ec = new ClassifierCombiner(props); log.info(ec.classifyToString("Marketing : Sony Hopes to Win Much Bigger Market For Wide Range of Small-Video Products --- By Andrew B. Cohen Staff Reporter of The Wall Street Journal")); } }
stanfordnlp/CoreNLP
src/edu/stanford/nlp/ie/ClassifierCombiner.java
41,656
import java.util.Arrays; import org.opencv.core.*; import org.opencv.highgui.HighGui; import org.opencv.imgproc.Imgproc; import org.opencv.video.Video; import org.opencv.videoio.VideoCapture; class Camshift { public void run(String[] args) { String filename = args[0]; VideoCapture capture = new VideoCapture(filename); if (!capture.isOpened()) { System.out.println("Unable to open file!"); System.exit(-1); } Mat frame = new Mat(), hsv_roi = new Mat(), mask = new Mat(), roi; // take the first frame of the video capture.read(frame); //setup initial location of window Rect track_window = new Rect(300, 200, 100, 50); // set up the ROI for tracking roi = new Mat(frame, track_window); Imgproc.cvtColor(roi, hsv_roi, Imgproc.COLOR_BGR2HSV); Core.inRange(hsv_roi, new Scalar(0, 60, 32), new Scalar(180, 255, 255), mask); MatOfFloat range = new MatOfFloat(0, 256); Mat roi_hist = new Mat(); MatOfInt histSize = new MatOfInt(180); MatOfInt channels = new MatOfInt(0); Imgproc.calcHist(Arrays.asList(hsv_roi), channels, mask, roi_hist, histSize, range); Core.normalize(roi_hist, roi_hist, 0, 255, Core.NORM_MINMAX); // Setup the termination criteria, either 10 iteration or move by at least 1 pt TermCriteria term_crit = new TermCriteria(TermCriteria.EPS | TermCriteria.COUNT, 10, 1); while (true) { Mat hsv = new Mat() , dst = new Mat(); capture.read(frame); if (frame.empty()) { break; } Imgproc.cvtColor(frame, hsv, Imgproc.COLOR_BGR2HSV); Imgproc.calcBackProject(Arrays.asList(hsv), channels, roi_hist, dst, range, 1); // apply camshift to get the new location RotatedRect rot_rect = Video.CamShift(dst, track_window, term_crit); // Draw it on image Point[] points = new Point[4]; rot_rect.points(points); for (int i = 0; i < 4 ;i++) { Imgproc.line(frame, points[i], points[(i+1)%4], new Scalar(255, 0, 0),2); } HighGui.imshow("img2", frame); int keyboard = HighGui.waitKey(30); if (keyboard == 'q'|| keyboard == 27) { break; } } System.exit(0); } } public class CamshiftDemo { public static void main(String[] args) { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); new Camshift().run(args); } }
opencv/opencv
samples/java/tutorial_code/video/meanshift/CamshiftDemo.java
41,657
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.weex.ui.component; import android.content.Context; import android.media.MediaPlayer; import android.net.Uri; import android.support.annotation.NonNull; import android.text.TextUtils; import android.view.View; import android.widget.FrameLayout; import org.apache.weex.WXEnvironment; import org.apache.weex.WXSDKInstance; import org.apache.weex.WXSDKManager; import org.apache.weex.annotation.Component; import org.apache.weex.adapter.URIAdapter; import org.apache.weex.common.Constants; import org.apache.weex.ui.action.BasicComponentData; import org.apache.weex.ui.view.WXVideoView; import org.apache.weex.utils.WXLogUtils; import org.apache.weex.utils.WXUtils; import java.util.HashMap; import java.util.Map; import org.apache.weex.ui.view.WXVideoView.Wrapper; @Component(lazyload = false) public class WXVideo extends WXComponent<FrameLayout> { private boolean mAutoPlay; private Wrapper mWrapper; /** * package **/ boolean mPrepared; private boolean mError; @Deprecated public WXVideo(WXSDKInstance instance, WXVContainer parent, String instanceId, boolean isLazy, BasicComponentData basicComponentData) { this(instance, parent, isLazy, basicComponentData); } public WXVideo(WXSDKInstance instance, WXVContainer parent, boolean isLazy, BasicComponentData basicComponentData) { super(instance, parent, isLazy, basicComponentData); } @Override protected FrameLayout initComponentHostView(@NonNull Context context) { final Wrapper video = new Wrapper(context); video.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int what, int extra) { if (WXEnvironment.isApkDebugable()) { WXLogUtils.d("Video", "onError:" + what); } video.getProgressBar().setVisibility(View.GONE); mPrepared = false; mError = true; if (getEvents().contains(Constants.Event.FAIL)) { WXVideo.this.notify(Constants.Event.FAIL, Constants.Value.STOP); } return true; } }); video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { if (WXEnvironment.isApkDebugable()) { WXLogUtils.d("Video", "onPrepared"); } video.getProgressBar().setVisibility(View.GONE); mPrepared = true; if (mAutoPlay) { video.start(); } //callback from video view, so videoview should not null WXVideoView videoView = video.getVideoView(); videoView.seekTo(5); if (video.getMediaController() != null) { if (!mStopped) { video.getMediaController().show(3); } else { video.getMediaController().hide(); } } mStopped = false; } }); video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { if (WXEnvironment.isApkDebugable()) { WXLogUtils.d("Video", "onCompletion"); } if (getEvents().contains(Constants.Event.FINISH)) { WXVideo.this.notify(Constants.Event.FINISH, Constants.Value.STOP); } } }); video.setOnVideoPauseListener(new WXVideoView.VideoPlayListener() { @Override public void onPause() { if (WXEnvironment.isApkDebugable()) { WXLogUtils.d("Video", "onPause"); } if (getEvents().contains(Constants.Event.PAUSE)) { WXVideo.this.notify(Constants.Event.PAUSE, Constants.Value.PAUSE); } } @Override public void onStart() { if (WXEnvironment.isApkDebugable()) { WXLogUtils.d("Video", "onStart"); } if (getEvents().contains(Constants.Event.START)) { WXVideo.this.notify(Constants.Event.START, Constants.Value.PLAY); } } }); mWrapper = video; return video; } private void notify(String event, String newStatus) { Map<String, Object> params = new HashMap<>(2); params.put(Constants.Name.PLAY_STATUS, newStatus); params.put("timeStamp", System.currentTimeMillis()); Map<String, Object> domChanges = new HashMap<>(); Map<String, Object> attrsChanges = new HashMap<>(); attrsChanges.put(Constants.Name.PLAY_STATUS, newStatus); domChanges.put("attrs", attrsChanges); WXSDKManager.getInstance().fireEvent(getInstanceId(), getRef(), event, params, domChanges); } @Override public void bindData(WXComponent component) { super.bindData(component); addEvent(Constants.Event.APPEAR); } @Override public void notifyAppearStateChange(String wxEventType, String direction) { super.notifyAppearStateChange(wxEventType, direction); mWrapper.createVideoViewIfVisible(); } @Override public void destroy() { super.destroy(); } @Override protected boolean setProperty(String key, Object param) { switch (key) { case Constants.Name.SRC: String src = WXUtils.getString(param, null); if (src != null) { setSrc(src); } return true; case Constants.Name.AUTO_PLAY: case Constants.Name.AUTOPLAY: Boolean result = WXUtils.getBoolean(param, null); if (result != null) { setAutoPlay(result); } return true; case Constants.Name.ZORDERTOP: Boolean zOrderTop = WXUtils.getBoolean(param, null); if (zOrderTop != null) { mWrapper.getVideoView().setZOrderOnTop(zOrderTop); } return true; case Constants.Name.PLAY_STATUS: String status = WXUtils.getString(param, null); if (status != null) { setPlaystatus(status); } return true; } return super.setProperty(key, param); } @WXComponentProp(name = Constants.Name.SRC) public void setSrc(String src) { if (TextUtils.isEmpty(src) || getHostView() == null) { return; } if (!TextUtils.isEmpty(src)) { WXSDKInstance instance = getInstance(); mWrapper.setVideoURI(instance.rewriteUri(Uri.parse(src), URIAdapter.VIDEO)); mWrapper.getProgressBar().setVisibility(View.VISIBLE); } } @WXComponentProp(name = Constants.Name.AUTO_PLAY) public void setAutoPlay(boolean autoPlay) { mAutoPlay = autoPlay; if(autoPlay){ mWrapper.createIfNotExist(); mWrapper.start(); } } @WXComponentProp(name = Constants.Name.CONTROLS) public void setControls(String controls) { if (TextUtils.equals("controls", controls)) { mWrapper.setControls(true); } else if (TextUtils.equals("nocontrols", controls)) { mWrapper.setControls(false); } } private boolean mStopped; @WXComponentProp(name = Constants.Name.PLAY_STATUS) public void setPlaystatus(String playstatus) { if (mPrepared && !mError && !mStopped) { if (playstatus.equals(Constants.Value.PLAY)) { mWrapper.start(); } else if (playstatus.equals(Constants.Value.PAUSE)) { mWrapper.pause(); } else if (playstatus.equals(Constants.Value.STOP)) { mWrapper.stopPlayback(); mStopped = true; } } else if ((mError || mStopped) && playstatus.equals(Constants.Value.PLAY)) { mError = false; mWrapper.resume(); mWrapper.getProgressBar().setVisibility(View.VISIBLE); } } }
kuaifan/WeexSDK
android/sdk/src/main/java/org/apache/weex/ui/component/WXVideo.java
41,658
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2024 DBeaver Corp and others * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ui; import org.eclipse.core.commands.ParameterizedCommand; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.e4.ui.model.application.ui.menu.MHandledItem; import org.eclipse.e4.ui.workbench.renderers.swt.HandledContributionItem; import org.eclipse.jface.action.*; import org.eclipse.jface.commands.ActionHandler; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.operation.IRunnableContext; import org.eclipse.jface.preference.IPreferenceNode; import org.eclipse.jface.preference.PreferenceDialog; import org.eclipse.jface.preference.PreferenceManager; import org.eclipse.jface.resource.ColorRegistry; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.viewers.AbstractTreeViewer; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.window.IShellProvider; import org.eclipse.jface.wizard.IWizardContainer; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.*; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.*; import org.eclipse.ui.*; import org.eclipse.ui.contexts.IContextService; import org.eclipse.ui.dialogs.PreferencesUtil; import org.eclipse.ui.handlers.IHandlerActivation; import org.eclipse.ui.handlers.IHandlerService; import org.eclipse.ui.internal.WorkbenchMessages; import org.eclipse.ui.menus.CommandContributionItem; import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer; import org.eclipse.ui.services.IServiceLocator; import org.eclipse.ui.swt.IFocusService; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.model.DBIcon; import org.jkiss.dbeaver.model.DBPImage; import org.jkiss.dbeaver.model.connection.DBPConnectionConfiguration; import org.jkiss.dbeaver.model.connection.DBPConnectionType; import org.jkiss.dbeaver.model.runtime.*; import org.jkiss.dbeaver.runtime.DBWorkbench; import org.jkiss.dbeaver.runtime.DummyRunnableContext; import org.jkiss.dbeaver.runtime.RunnableContextDelegate; import org.jkiss.dbeaver.ui.contentassist.ContentAssistUtils; import org.jkiss.dbeaver.ui.contentassist.SmartTextContentAdapter; import org.jkiss.dbeaver.ui.contentassist.StringContentProposalProvider; import org.jkiss.dbeaver.ui.controls.CustomSashForm; import org.jkiss.dbeaver.ui.dialogs.EditTextDialog; import org.jkiss.dbeaver.ui.dialogs.MessageBoxBuilder; import org.jkiss.dbeaver.ui.dialogs.Reply; import org.jkiss.dbeaver.ui.internal.UIActivator; import org.jkiss.dbeaver.ui.internal.UIMessages; import org.jkiss.dbeaver.utils.GeneralUtils; import org.jkiss.dbeaver.utils.RuntimeUtils; import org.jkiss.utils.ArrayUtils; import org.jkiss.utils.CommonUtils; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.nio.charset.Charset; import java.text.DecimalFormatSymbols; import java.text.MessageFormat; import java.util.Arrays; import java.util.Collection; import java.util.Locale; import java.util.SortedMap; /** * UI Utils */ public class UIUtils { private static final Log log = Log.getLog(UIUtils.class); private static final String INLINE_WIDGET_EDITOR_ID = "org.jkiss.dbeaver.ui.InlineWidgetEditor"; private static final Color COLOR_BLACK = new Color(null, 0, 0, 0); public static final Color COLOR_WHITE = new Color(null, 255, 255, 255); public static final Color COLOR_GREEN_CONTRAST = new Color(null, 23, 135, 58); public static final Color COLOR_VALIDATION_ERROR = new Color(255, 220, 220); private static final Color COLOR_WHITE_DARK = new Color(null, 208, 208, 208); private static final SharedTextColors SHARED_TEXT_COLORS = new SharedTextColors(); private static final SharedFonts SHARED_FONTS = new SharedFonts(); private static final String MAX_LONG_STRING = String.valueOf(Long.MAX_VALUE); public static VerifyListener getIntegerVerifyListener(Locale locale) { final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale); return e -> { for (int i = 0; i < e.text.length(); i++) { char ch = e.text.charAt(i); if (!Character.isDigit(ch) && ch != symbols.getMinusSign() && ch != symbols.getGroupingSeparator()) { e.doit = false; return; } } e.doit = true; }; } public static VerifyListener getNumberVerifyListener(Locale locale) { DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale); final char[] allowedChars = new char[] { symbols.getDecimalSeparator(), symbols.getGroupingSeparator(), symbols.getMinusSign(), symbols.getZeroDigit(), symbols.getMonetaryDecimalSeparator(), '+', '.', ',' }; final String exponentSeparator = symbols.getExponentSeparator(); return e -> { for (int i = 0; i < e.text.length(); i++) { char ch = e.text.charAt(i); if (!Character.isDigit(ch) && !ArrayUtils.contains(allowedChars, ch) && exponentSeparator.indexOf(ch) == -1) { e.doit = false; return; } } e.doit = true; }; } public static VerifyListener getUnsignedLongOrEmptyTextVerifyListener(Text text) { return e -> { if (e.text.isEmpty()) { e.doit = true; return; } for (int i = 0; i < e.text.length(); i++) { if (!Character.isDigit(e.text.charAt(i))) { e.doit = false; return; } } String newText = text.getText().substring(0, e.start) + e.text + text.getText().substring(e.end); if (newText.length() < MAX_LONG_STRING.length()) { e.doit = true; return; } if (newText.length() > MAX_LONG_STRING.length()) { e.doit = false; return; } e.doit = newText.compareTo(MAX_LONG_STRING) <= 0; }; } public static void createToolBarSeparator(Composite toolBar, int style) { Label label = new Label(toolBar, SWT.NONE); label.setImage(DBeaverIcons.getImage((style & SWT.HORIZONTAL) == SWT.HORIZONTAL ? UIIcon.SEPARATOR_H : UIIcon.SEPARATOR_V)); } public static void createLabelSeparator(Composite toolBar, int style) { Label label = new Label(toolBar, SWT.SEPARATOR | style); label.setLayoutData(new GridData(style == SWT.HORIZONTAL ? GridData.FILL_HORIZONTAL : GridData.FILL_VERTICAL)); } public static void createToolBarSeparator(ToolBar toolBar, int style) { Label label = new Label(toolBar, SWT.NONE); label.setImage(DBeaverIcons.getImage((style & SWT.HORIZONTAL) == SWT.HORIZONTAL ? UIIcon.SEPARATOR_H : UIIcon.SEPARATOR_V)); new ToolItem(toolBar, SWT.SEPARATOR).setControl(label); } public static TableColumn createTableColumn(Table table, int style, String text) { TableColumn column = new TableColumn(table, style); column.setText(text); return column; } public static TreeColumn createTreeColumn(Tree tree, int style, String text) { TreeColumn column = new TreeColumn(tree, style); column.setText(text); return column; } public static void executeOnResize(Control control, Runnable runnable) { control.addControlListener(new ControlAdapter() { @Override public void controlResized(ControlEvent e) { control.removeControlListener(this); runnable.run(); } }); } public static void packColumns(Table table) { packColumns(table, false); } public static void packColumns(Table table, boolean fit) { table.setRedraw(false); try { int totalWidth = 0; final TableColumn[] columns = table.getColumns(); for (TableColumn column : columns) { column.pack(); totalWidth += column.getWidth(); } final Rectangle clientArea = table.getBounds(); if (clientArea.width > 0 && totalWidth > clientArea.width) { for (TableColumn column : columns) { int colWidth = column.getWidth(); if (colWidth > totalWidth / 3) { // If some columns are too big (more than 33% of total width) // Then shrink them to 30% column.setWidth(totalWidth / 3); totalWidth -= colWidth; totalWidth += column.getWidth(); } } if (totalWidth < clientArea.width) { int extraSpace = totalWidth - clientArea.width; GC gc = new GC(table); try { for (TableColumn tc : columns) { double ratio = (double) tc.getWidth() / totalWidth; int newWidth = (int) (tc.getWidth() - extraSpace * ratio); int minWidth = gc.stringExtent(tc.getText()).x; minWidth += 5; if (newWidth < minWidth) { newWidth = minWidth; } tc.setWidth(newWidth); } } finally { gc.dispose(); } } } if (fit && totalWidth < clientArea.width) { int sbWidth = table.getBorderWidth() * 2; if (table.getVerticalBar() != null) { sbWidth = table.getVerticalBar().getSize().x; } if (columns.length > 0) { float extraSpace = (clientArea.width - totalWidth - sbWidth) / columns.length - 1; for (TableColumn tc : columns) { tc.setWidth((int) (tc.getWidth() + extraSpace)); } } } } finally { table.setRedraw(true); } } public static void packColumns(@NotNull Tree tree) { packColumns(tree, false, null); } public static void packColumns(@NotNull Tree tree, boolean fit, @Nullable float[] ratios) { tree.setRedraw(false); try { // Check for disposed items // TODO: it looks like SWT error. Sometimes tree items are disposed and NPE is thrown from column.pack for (TreeItem item : tree.getItems()) { if (item.isDisposed()) { return; } } final TreeColumn[] columns = tree.getColumns(); for (TreeColumn column : columns) { column.pack(); } Rectangle clientArea = tree.getClientArea(); if (clientArea.isEmpty()) { return; } int totalWidth = 0; for (TreeColumn column : columns) { int colWidth = column.getWidth(); if (colWidth > clientArea.width) { // Too wide column - make it a bit narrower colWidth = clientArea.width; column.setWidth(colWidth); } totalWidth += colWidth; } if (fit) { int areaWidth = clientArea.width; // if (tree.getVerticalBar() != null) { // areaWidth -= tree.getVerticalBar().getSize().x; // } if (totalWidth > areaWidth) { GC gc = new GC(tree); try { int extraSpace = totalWidth - areaWidth; for (TreeColumn tc : columns) { double ratio = (double) tc.getWidth() / totalWidth; int newWidth = (int) (tc.getWidth() - extraSpace * ratio); int minWidth = gc.stringExtent(tc.getText()).x; minWidth += 5; if (newWidth < minWidth) { newWidth = minWidth; } tc.setWidth(newWidth); } } finally { gc.dispose(); } } else if (totalWidth < areaWidth) { float extraSpace = areaWidth - totalWidth; if (columns.length > 0) { if (ratios == null || ratios.length < columns.length) { extraSpace /= columns.length; extraSpace--; for (TreeColumn tc : columns) { tc.setWidth((int) (tc.getWidth() + extraSpace)); } } else { for (int i = 0; i < columns.length; i++) { TreeColumn tc = columns[i]; tc.setWidth((int) (tc.getWidth() + extraSpace * ratios[i])); } } } } } } finally { tree.setRedraw(true); } } public static void maxTableColumnsWidth(Table table) { table.setRedraw(false); try { int columnCount = table.getColumnCount(); if (columnCount > 0) { int totalWidth = 0; final TableColumn[] columns = table.getColumns(); for (TableColumn tc : columns) { tc.pack(); totalWidth += tc.getWidth(); } final Rectangle clientArea = table.getClientArea(); if (totalWidth < clientArea.width) { int extraSpace = clientArea.width - totalWidth; extraSpace /= columnCount; for (TableColumn tc : columns) { tc.setWidth(tc.getWidth() + extraSpace); } } } } finally { table.setRedraw(true); } } public static int getColumnAtPos(TableItem item, int x, int y) { int columnCount = item.getParent().getColumnCount(); for (int i = 0; i < columnCount; i++) { Rectangle rect = item.getBounds(i); if (rect.contains(x, y)) { return i; } } return -1; } public static int getColumnAtPos(TreeItem item, int x, int y) { int columnCount = item.getParent().getColumnCount(); for (int i = 0; i < columnCount; i++) { Rectangle rect = item.getBounds(i); if (rect.contains(x, y)) { return i; } } return -1; } public static TableItem getNextTableItem(Table table, TableItem item) { TableItem[] items = table.getItems(); for (int i = 0; i < items.length - 1; i++) { if (items[i] == item) { return items[i + 1]; } } return null; } public static TableItem getPreviousTableItem(Table table, TableItem item) { TableItem[] items = table.getItems(); for (int i = 1; i < items.length; i++) { if (items[i] == item) { return items[i - 1]; } } return null; } public static TreeItem getNextTreeItem(Tree tree, TreeItem item) { TreeItem[] items = tree.getItems(); for (int i = 0; i < items.length - 1; i++) { if (items[i] == item) { return items[i + 1]; } } return null; } public static void dispose(Widget widget) { if (widget != null && !widget.isDisposed()) { try { widget.dispose(); } catch (Exception e) { log.debug("widget dispose error", e); } } } public static void dispose(Resource resource) { if (resource != null && !resource.isDisposed()) { try { resource.dispose(); } catch (Exception e) { log.debug("Resource dispose error", e); } } } public static void showMessageBox(final Shell shell, final String title, final String info, final int messageType) { DBPImage icon = null; if (messageType == SWT.ICON_ERROR) { icon = DBIcon.STATUS_ERROR; } else if (messageType == SWT.ICON_WARNING) { icon = DBIcon.STATUS_WARNING; } else if (messageType == SWT.ICON_QUESTION) { icon = DBIcon.STATUS_QUESTION; } else if (messageType == SWT.ICON_INFORMATION) { icon = DBIcon.STATUS_INFO; } Runnable messageBoxRunnable; if (icon != null) { final DBPImage finalIcon = icon; messageBoxRunnable = () -> MessageBoxBuilder.builder(shell != null ? shell : getActiveWorkbenchShell()) .setTitle(title) .setMessage(info) .setReplies(Reply.OK) .setDefaultReply(Reply.OK) .setPrimaryImage(finalIcon) .showMessageBox(); } else { //show legacy message box messageBoxRunnable = () -> { Shell activeShell = shell != null ? shell : getActiveWorkbenchShell(); MessageBox messageBox = new MessageBox(activeShell, messageType | SWT.OK); messageBox.setMessage(info); messageBox.setText(title); messageBox.open(); }; } syncExec(messageBoxRunnable); } public static boolean confirmAction(final String title, final String question) { return confirmAction(null, title, question); } public static boolean confirmAction(@Nullable Shell shell, final String title, final String question) { return confirmAction(shell, title, question, DBIcon.STATUS_QUESTION); } public static boolean confirmAction(@Nullable Shell shell, String title, String message, @NotNull DBPImage image) { final Reply[] reply = {null}; syncExec(() -> reply[0] = MessageBoxBuilder.builder(shell != null ? shell : getActiveWorkbenchShell()) .setTitle(title) .setMessage(message) .setReplies(Reply.YES, Reply.NO) .setDefaultReply(Reply.NO) .setPrimaryImage(image) .showMessageBox() ); return reply[0] == Reply.YES; } /** * Confirm action with custom labels * */ public static boolean confirmAction(@Nullable Shell shell, String title, String message, @NotNull DBPImage image, String[] buttons) { final Reply[] reply = { null }; syncExec(() -> reply[0] = MessageBoxBuilder.builder(shell != null ? shell : getActiveWorkbenchShell()) .setTitle(title) .setMessage(message) .setLabels(buttons) .setDefaultReply(Reply.NO) .setPrimaryImage(image) .setDefaultFocus(buttons.length - 1) .showMessageBox()); return reply[0] == Reply.OK; } public static int getFontHeight(Control control) { return getFontHeight(control.getFont()); } public static int getFontHeight(Font font) { FontData[] fontData = font.getFontData(); if (fontData.length == 0) { return 20; } return fontData[0].getHeight(); } public static int getTextHeight(@NotNull Control control) { return getTextSize(control, "X").y; } @NotNull public static Point getTextSize(@NotNull Control control, @NotNull String text) { GC gc = new GC(control); try { return gc.textExtent(text); } finally { gc.dispose(); } } public static Font makeBoldFont(Font normalFont) { return modifyFont(normalFont, SWT.BOLD); } @NotNull public static Font modifyFont(@NotNull Font normalFont, int style) { final FontData[] data = normalFont.getFontData(); for (FontData fd : data) { fd.setStyle(fd.getStyle() | style); } return new Font(normalFont.getDevice(), data); } public static Group createControlGroup(Composite parent, String label, int columns, int layoutStyle, int widthHint) { Group group = new Group(parent, SWT.NONE); group.setText(label); if (parent.getLayout() instanceof GridLayout) { GridData gd = new GridData(layoutStyle); if (widthHint > 0) { gd.widthHint = widthHint; } group.setLayoutData(gd); } GridLayout gl = new GridLayout(columns, false); group.setLayout(gl); return group; } public static Label createControlLabel(Composite parent, String label) { return createControlLabel(parent, label, 1); } public static Label createControlLabel(Composite parent, String label, int hSpan) { Label textLabel = new Label(parent, SWT.NONE); textLabel.setText(label + ": "); //$NON-NLS-1$ // Vert align center. Because height of single line control may differ from label height. This makes form ugly. // For multiline texts we need to set vert align manually. GridData gd = new GridData(GridData.VERTICAL_ALIGN_CENTER /*| GridData.HORIZONTAL_ALIGN_END*/); gd.horizontalSpan = hSpan; textLabel.setLayoutData(gd); return textLabel; } public static Label createLabel(Composite parent, String label) { Label textLabel = new Label(parent, SWT.NONE); textLabel.setText(label); return textLabel; } public static Label createLabel(Composite parent, @NotNull DBPImage image) { Label imageLabel = new Label(parent, SWT.NONE); imageLabel.setImage(DBeaverIcons.getImage(image)); return imageLabel; } @NotNull public static Control createInfoLabel(@NotNull Composite parent, @NotNull String text) { return createInfoLabel(parent, text, null); } @NotNull public static Control createInfoLabel(@NotNull Composite parent, @NotNull String text, @Nullable Runnable listener) { return createInfoLabel(parent, text, SWT.NONE, 1, listener); } @NotNull public static Control createInfoLabel(@NotNull Composite parent, @NotNull String text, int gridStyle, int hSpan) { return createInfoLabel(parent, text, gridStyle, hSpan, null); } @NotNull public static Control createWarningLabel( @NotNull Composite parent, @NotNull String text, int gridStyle, int hSpan ) { return createInfoLabel(parent, text, gridStyle, hSpan, null, DBeaverIcons.getImage(DBIcon.SMALL_WARNING)); } @NotNull public static Control createInfoLabel( @NotNull Composite parent, @NotNull String text, int gridStyle, int hSpan, @Nullable Runnable callback ) { return createInfoLabel(parent, text, gridStyle, hSpan, callback, DBeaverIcons.getImage(DBIcon.SMALL_INFO)); } @NotNull public static Control createInfoLabel( @NotNull Composite parent, @NotNull String text, int gridStyle, int hSpan, @Nullable Runnable callback, @NotNull Image image ) { final Control control; if (callback == null) { final CLabel label = new CLabel(parent, SWT.NONE); label.setImage(image); label.setText(text); control = label; } else { control = createInfoLink(parent, "<a href=\"#\">" + text + "</a>", callback).getParent(); } if (gridStyle != SWT.NONE || hSpan > 1) { final GridData gd = new GridData(gridStyle); gd.horizontalSpan = hSpan; control.setLayoutData(gd); } return control; } @NotNull public static Link createInfoLink(@NotNull Composite parent, @NotNull String text, @NotNull Runnable callback) { final Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(GridLayoutFactory.fillDefaults().numColumns(2).create()); final Label imageLabel = new Label(composite, SWT.NONE); imageLabel.setImage(DBeaverIcons.getImage(DBIcon.SMALL_INFO)); imageLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false)); final Link link = new Link(composite, SWT.NONE); link.setText(text); link.addSelectionListener(SelectionListener.widgetSelectedAdapter(e -> callback.run())); link.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).create()); return link; } public static Text createLabelText(Composite parent, String label, String value) { return createLabelText(parent, label, value, SWT.BORDER); } public static Text createLabelText(Composite parent, String label, String value, int style) { return createLabelText(parent, label, value, style, new GridData(GridData.FILL_HORIZONTAL)); } @NotNull public static Text createLabelText(@NotNull Composite parent, @NotNull String label, @Nullable String value, int style, @Nullable Object layoutData) { Label controlLabel = createControlLabel(parent, label); Text text = new Text(parent, style); fixReadonlyTextBackground(text); if (value != null) { text.setText(value); } if (layoutData != null) { text.setLayoutData(layoutData); } return text; } @NotNull public static Text createLabelTextAdvanced(@NotNull Composite parent, @NotNull String label, @Nullable String value, int style) { Label controlLabel = createControlLabel(parent, label); Composite panel = createComposite(parent, 2); panel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Text text = new Text(panel, style); text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fixReadonlyTextBackground(text); if (value != null) { text.setText(value); } ToolBar editTB = new ToolBar(panel, SWT.HORIZONTAL); ToolItem editButton = new ToolItem(editTB, SWT.DOWN); //Button editButton = new Button(panel, SWT.DOWN); //editButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); //editButton.setText("..."); editButton.setImage(DBeaverIcons.getImage(UIIcon.EDIT)); //$NON-NLS-1$ editButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { String newText = EditTextDialog.editText(parent.getShell(), label, text.getText()); if (newText != null) { text.setText(newText); } } }); editTB.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); return text; } @NotNull public static Spinner createLabelSpinner(@NotNull Composite parent, @NotNull String label, @Nullable String tooltip, int value, int minimum, int maximum) { final Label l = createControlLabel(parent, label); if (tooltip != null) { l.setToolTipText(tooltip); } return createSpinner(parent, tooltip, value, minimum, maximum); } @NotNull public static Spinner createSpinner(Composite parent, String tooltip, int value, int minimum, int maximum) { Spinner spinner = new Spinner(parent, SWT.BORDER); spinner.setMinimum(minimum); spinner.setMaximum(maximum); spinner.setSelection(value); if (tooltip != null) { spinner.setToolTipText(tooltip); } return spinner; } @NotNull public static Spinner createLabelSpinner(@NotNull Composite parent, @NotNull String label, int value, int minimum, int maximum) { return createLabelSpinner(parent, label, null, value, minimum, maximum); } @NotNull public static Button createLabelCheckbox(Composite parent, String label, boolean checked) { return createLabelCheckbox(parent, label, null, checked, SWT.NONE); } @NotNull public static Button createLabelCheckbox(Composite parent, String label, String tooltip, boolean checked) { return createLabelCheckbox(parent, label, tooltip, checked, SWT.NONE); } @NotNull public static Button createLabelCheckbox(@NotNull Composite parent, @NotNull String label, @Nullable String tooltip, boolean checked, int style) { Label labelControl = createControlLabel(parent, label); // labelControl.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); final Button button = new Button(parent, SWT.CHECK | style); if (checked) { button.setSelection(true); } labelControl.addMouseListener(new MouseAdapter() { @Override public void mouseUp(MouseEvent e) { if (!button.isDisposed() && button.isVisible() && button.isEnabled()) { button.setSelection(!button.getSelection()); button.notifyListeners(SWT.Selection, new Event()); } } }); if (tooltip != null) { labelControl.setToolTipText(tooltip); button.setToolTipText(tooltip); } return button; } public static Button createCheckbox(Composite parent, String label, String tooltip, boolean checked, int hSpan) { Button checkbox = createCheckbox(parent, label, checked); if (tooltip != null) { checkbox.setToolTipText(tooltip); } if (hSpan > 1) { GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gd.horizontalSpan = hSpan; checkbox.setLayoutData(gd); } return checkbox; } public static Button createCheckbox(Composite parent, String label, boolean checked) { final Button button = new Button(parent, SWT.CHECK); button.setText(label); if (checked) { button.setSelection(true); } return button; } public static Button createCheckbox(Composite parent, boolean checked) { final Button button = new Button(parent, SWT.CHECK); if (checked) { button.setSelection(true); } return button; } public static Combo createLabelCombo(Composite parent, String label, int style) { return createLabelCombo(parent, label, null, style); } public static Combo createLabelCombo(Composite parent, String label, String tooltip, int style) { Label labelControl = createControlLabel(parent, label); if (tooltip != null) { labelControl.setToolTipText(tooltip); } final Combo combo = new Combo(parent, style); combo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); if (tooltip != null) { combo.setToolTipText(tooltip); } return combo; } public static Button createToolButton(Composite parent, String text, SelectionListener selectionListener) { Button button = new Button(parent, SWT.PUSH); button.setText(text); button.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); if (selectionListener != null) { button.addSelectionListener(selectionListener); } return button; } public static ToolItem createToolItem(ToolBar parent, String text, DBPImage icon, SelectionListener selectionListener) { return createToolItem(parent, text, icon != null ? DBeaverIcons.getImage(icon) : null, selectionListener); } public static ToolItem createToolItem(ToolBar parent, String title, String text, DBPImage icon, SelectionListener selectionListener) { ToolItem toolItem = createToolItem(parent, text, icon != null ? DBeaverIcons.getImage(icon) : null, selectionListener); if (title != null) { toolItem.setText(title); } return toolItem; } public static ToolItem createToolItem(ToolBar parent, String text, Image icon, SelectionListener selectionListener) { ToolItem button = new ToolItem(parent, SWT.PUSH); button.setToolTipText(text); if (icon != null) { button.setImage(icon); } if (selectionListener != null) { button.addSelectionListener(selectionListener); } return button; } public static void updateContributionItems(IContributionManager manager) { for (IContributionItem item : manager.getItems()) { item.update(); } } @Nullable public static Shell getActiveShell() { final Display display = Display.getCurrent(); final Shell activeShell = display.getActiveShell(); if (activeShell != null) { return activeShell; } final Shell[] shells = display.getShells(); for (Shell shell : shells) { if (shell.isVisible()) { return shell; } } return shells.length > 0 ? shells[0] : null; } @Nullable public static Shell getShell(IShellProvider provider) { return provider == null ? null : provider.getShell(); } @Nullable public static Shell getShell(IWorkbenchPart part) { return part == null ? null : getShell(part.getSite()); } @Nullable public static Integer getTextInteger(Text text) { String str = text.getText(); str = str.trim(); if (str.length() == 0) { return null; } try { return Integer.valueOf(str); } catch (NumberFormatException e) { log.debug(e); return null; } } @Nullable public static IHandlerActivation registerKeyBinding(IServiceLocator serviceLocator, IAction action) { IHandlerService handlerService = serviceLocator.getService(IHandlerService.class); if (handlerService != null) { return handlerService.activateHandler(action.getActionDefinitionId(), new ActionHandler(action)); } else { return null; } } public static Composite createPlaceholder(Composite parent, int columns) { return createPlaceholder(parent, columns, 0); } public static Composite createComposite(@NotNull Composite parent, int columns) { Composite ph = new Composite(parent, SWT.NONE); GridLayout gl = new GridLayout(columns, false); gl.marginWidth = 0; gl.marginHeight = 0; ph.setLayout(gl); return ph; } /** * Creates {@link ScrolledComposite} from the {@link Composite} * * @param parent composite parent * @return ScrolledComposite */ @NotNull public static ScrolledComposite createScrolledComposite(@NotNull Composite parent) { ScrolledComposite scrolledComposite = new ScrolledComposite(parent, SWT.V_SCROLL); scrolledComposite.setLayout(new GridLayout(1, false)); scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); return scrolledComposite; } /** * Configures created composite to detect resize and be appropriately sized with its contents * * @param scrolledComposite composite to configure * @param content it's contents */ public static void configureScrolledComposite(@NotNull ScrolledComposite scrolledComposite, @NotNull Control content) { scrolledComposite.setContent(content); scrolledComposite.setExpandHorizontal(true); scrolledComposite.setExpandVertical(true); scrolledComposite.addControlListener(new ControlAdapter() { @Override public void controlResized(ControlEvent e) { scrolledComposite.setMinHeight(content.computeSize(SWT.DEFAULT, SWT.DEFAULT).y); } }); scrolledComposite.setMinSize(content.computeSize(SWT.DEFAULT, SWT.DEFAULT)); } public static Composite createPlaceholder(@NotNull Composite parent, int columns, int spacing) { Composite ph = new Composite(parent, SWT.NONE); GridLayout gl = new GridLayout(columns, false); gl.verticalSpacing = spacing; gl.horizontalSpacing = spacing; gl.marginHeight = 0; gl.marginWidth = 0; ph.setLayout(gl); return ph; } public static Composite createFormPlaceholder(Composite parent, int columns, int hSpan) { Composite ph = new Composite(parent, SWT.NONE); GridLayout gl = new GridLayout(columns, false); gl.marginHeight = 0; gl.marginWidth = 0; ph.setLayout(gl); GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = hSpan; ph.setLayoutData(gd); return ph; } public static void setGridSpan(Control control, int horizontalSpan, int verticalSpan) { GridData gd; final Object layoutData = control.getLayoutData(); if (layoutData == null) { if (control.getParent().getLayout() instanceof GridLayout) { gd = new GridData(); control.setLayoutData(gd); } else { log.debug("Can't set grid span for layout: " + control.getParent().getLayout()); return; } } else if (layoutData instanceof GridData) { gd = (GridData) layoutData; } else { log.debug("Can't set grid span for non-grid layout: " + layoutData.getClass().getName()); return; } gd.horizontalSpan = horizontalSpan; gd.verticalSpan = verticalSpan; } public static Label createHorizontalLine(Composite parent) { return createHorizontalLine(parent, 1, 0); } public static Label createHorizontalLine(Composite parent, int hSpan, int vIndent) { Label horizontalLine = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL); GridData gd = new GridData(GridData.FILL, GridData.FILL, true, false, 1, 1); gd.horizontalSpan = hSpan; gd.verticalIndent = vIndent; horizontalLine.setLayoutData(gd); return horizontalLine; } public static Label createVerticalLine(Composite parent) { Label horizontalLine = new Label(parent, SWT.SEPARATOR | SWT.VERTICAL); if (parent.getLayout() instanceof GridLayout) { GridData gd = new GridData(GridData.FILL, GridData.FILL, false, true, 1, 1); horizontalLine.setLayoutData(gd); } return horizontalLine; } @Nullable public static String getComboSelection(Combo combo) { int selectionIndex = combo.getSelectionIndex(); if (selectionIndex < 0) { return null; } return combo.getItem(selectionIndex); } public static boolean setComboSelection(Combo combo, String value) { if (value == null) { return false; } int count = combo.getItemCount(); for (int i = 0; i < count; i++) { if (value.equals(combo.getItem(i))) { combo.select(i); return true; } } return false; } // public static Combo createEncodingCombo(Composite parent, String curCharset) // { // // } public static Combo createEncodingCombo(Composite parent, @Nullable String curCharset) { Combo encodingCombo = new Combo(parent, SWT.DROP_DOWN); encodingCombo.setVisibleItemCount(30); SortedMap<String, Charset> charsetMap = Charset.availableCharsets(); int index = 0; int defIndex = -1; for (String csName : charsetMap.keySet()) { Charset charset = charsetMap.get(csName); encodingCombo.add(charset.displayName()); if (curCharset != null) { if (charset.displayName().equalsIgnoreCase(curCharset)) { defIndex = index; } if (defIndex < 0) { for (String alias : charset.aliases()) { if (alias.equalsIgnoreCase(curCharset)) { defIndex = index; } } } } index++; } if (defIndex >= 0) { encodingCombo.select(defIndex); } else if (curCharset != null) { log.warn("Charset '" + curCharset + "' is not recognized"); //$NON-NLS-1$ //$NON-NLS-2$ } return encodingCombo; } @NotNull public static CustomSashForm createPartDivider(final IWorkbenchPart workbenchPart, Composite parent, int style) { return new CustomSashForm(parent, style); } @NotNull public static String formatMessage(@Nullable String message, @Nullable Object... args) { if (message == null) { return ""; //$NON-NLS-1$ } else { return MessageFormat.format(message, args); } } @NotNull public static Button createPushButton(@NotNull Composite parent, @Nullable String label, @Nullable Image image) { return createPushButton(parent, label, image, null); } @NotNull public static Button createPushButton(@NotNull Composite parent, @Nullable String label, @Nullable Image image, @Nullable SelectionListener selectionListener) { Button button = new Button(parent, SWT.PUSH); if (label != null) { button.setText(label); } if (image != null) { button.setImage(image); } if (selectionListener != null) { button.addSelectionListener(selectionListener); } return button; } @NotNull public static Button createDialogButton(@NotNull Composite parent, @Nullable String label, @Nullable SelectionListener selectionListener) { return createDialogButton(parent, label, null, null, selectionListener); } @NotNull public static Button createDialogButton(@NotNull Composite parent, @Nullable String label, @Nullable DBPImage icon, @Nullable String toolTip, @Nullable SelectionListener selectionListener) { return createDialogButton(parent, label, toolTip, icon, GridData.HORIZONTAL_ALIGN_FILL, selectionListener); } @NotNull public static Button createDialogButton( @NotNull Composite parent, @Nullable String label, @Nullable String toolTip, @Nullable DBPImage icon, int style, @Nullable SelectionListener selectionListener ) { Button button = new Button(parent, SWT.PUSH); button.setText(label); button.setFont(JFaceResources.getDialogFont()); if (icon != null) { button.setImage(DBeaverIcons.getImage(icon)); } if (toolTip != null) { button.setToolTipText(toolTip); } // Dialog settings GridData gd = new GridData(style); GC gc = new GC(button); int widthHint; try { gc.setFont(JFaceResources.getDialogFont()); widthHint = org.eclipse.jface.dialogs.Dialog.convertHorizontalDLUsToPixels(gc.getFontMetrics(), IDialogConstants.BUTTON_WIDTH); } finally { gc.dispose(); } Point minSize = button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); gd.widthHint = Math.max(widthHint, minSize.x); button.setLayoutData(gd); if (selectionListener != null) { button.addSelectionListener(selectionListener); } return button; } @NotNull public static Button createRadioButton(@NotNull Composite parent, @Nullable String label, @NotNull Object data, @Nullable SelectionListener selectionListener) { Button button = new Button(parent, SWT.RADIO); button.setText(label); if (selectionListener != null) { button.addSelectionListener(selectionListener); } button.setData(data); return button; } public static void setHelp(Control control, String pluginId, String helpContextID) { if (control != null && !control.isDisposed()) { PlatformUI.getWorkbench().getHelpSystem().setHelp(control, pluginId + "." + helpContextID); //$NON-NLS-1$ } } public static void setHelp(Control control, String helpContextID) { setHelp(control, UIActivator.PLUGIN_ID, helpContextID); } public static String makeAnchor(String text) { return "<a>" + text + "</a>"; //$NON-NLS-1$ //$NON-NLS-2$ } @Nullable public static <T> T findView(IWorkbenchWindow workbenchWindow, Class<T> viewClass) { IViewReference[] references = workbenchWindow.getActivePage().getViewReferences(); for (IViewReference ref : references) { IViewPart view = ref.getView(false); if (view != null && viewClass.isAssignableFrom(view.getClass())) { return viewClass.cast(view); } } return null; } @Nullable public static IViewPart findView(IWorkbenchWindow workbenchWindow, String viewId) { IViewReference[] references = workbenchWindow.getActivePage().getViewReferences(); for (IViewReference ref : references) { if (ref.getId().equals(viewId)) { return ref.getView(false); } } return null; } public static void setClipboardContents(Display display, Transfer transfer, Object contents) { Clipboard clipboard = new Clipboard(display); clipboard.setContents(new Object[] { contents }, new Transfer[] { transfer }); clipboard.dispose(); } public static void showPreferencesFor(Shell shell, Object element, String ... defPageID) { PreferenceDialog propDialog; if (element == null) { propDialog = PreferencesUtil.createPreferenceDialogOn(shell, defPageID[0], defPageID, null, PreferencesUtil.OPTION_NONE); } else { propDialog = PreferencesUtil.createPropertyDialogOn(shell, element, defPageID[0], null, null, PreferencesUtil.OPTION_NONE); } if (propDialog != null) { propDialog.open(); } } /** * Creates a new link that opens the given preference page either in the current * preference container, is present, or in a new modal dialog. */ @NotNull public static Link createPreferenceLink( @NotNull Composite parent, @NotNull String message, @NotNull String pageId, @Nullable IWorkbenchPreferenceContainer pageContainer, @Nullable Object pageData ) { final IPreferenceNode node = findPreferenceNode(pageId); final Link link = new Link(parent, 0); if (node == null) { link.setText(NLS.bind(WorkbenchMessages.PreferenceNode_NotFound, pageId)); } else { final boolean canOpenHere = findPreferenceNode(pageContainer, pageId) != null; final String label = canOpenHere ? node.getLabelText() : NLS.bind(UIMessages.link_external_label, node.getLabelText()); link.setText(NLS.bind(message, label)); link.setToolTipText(canOpenHere ? null : UIMessages.link_external_tip); link.addSelectionListener(SelectionListener.widgetSelectedAdapter(e -> { if (pageContainer != null && canOpenHere) { // Open in the same dialog pageContainer.openPage(pageId, pageData); } else { // Open in a new dialog PreferencesUtil.createPreferenceDialogOn( link.getShell(), pageId, new String[]{pageId}, pageData, PreferencesUtil.OPTION_NONE ).open(); } })); } return link; } @Nullable private static IPreferenceNode findPreferenceNode(@NotNull String pageId) { return findPreferenceNode(PlatformUI.getWorkbench().getPreferenceManager(), pageId); } @Nullable private static IPreferenceNode findPreferenceNode(@Nullable IWorkbenchPreferenceContainer container, @NotNull String pageId) { if (container instanceof PreferenceDialog dialog) { return findPreferenceNode(dialog.getPreferenceManager(), pageId); } return null; } @Nullable private static IPreferenceNode findPreferenceNode(@NotNull PreferenceManager preferenceManager, @NotNull String pageId) { return preferenceManager.getElements(PreferenceManager.POST_ORDER).stream() .filter(next -> next.getId().equals(pageId)) .findFirst() .orElse(null); } public static void addFocusTracker(IServiceLocator serviceLocator, String controlID, Control control) { IFocusService focusService = serviceLocator.getService(IFocusService.class); if (focusService == null) { focusService = UIUtils.getActiveWorkbenchWindow().getService(IFocusService.class); } if (focusService != null) { IFocusService finalFocusService = focusService; finalFocusService.addFocusTracker(control, controlID); control.addDisposeListener(e -> { // Unregister from focus service finalFocusService.removeFocusTracker(control); }); } else { log.debug("Focus service not found in " + serviceLocator); } } public static void addDefaultEditActionsSupport(final IServiceLocator site, final Control control) { UIUtils.addFocusTracker(site, UIUtils.INLINE_WIDGET_EDITOR_ID, control); } @NotNull public static IDialogSettings getDialogSettings(@NotNull String dialogId) { IDialogSettings workbenchSettings = UIActivator.getDefault().getDialogSettings(); return getSettingsSection(workbenchSettings, dialogId); } @NotNull public static IDialogSettings getSettingsSection(@NotNull IDialogSettings parent, @NotNull String sectionId) { IDialogSettings section = parent.getSection(sectionId); if (section == null) { section = parent.addNewSection(sectionId); } return section; } public static void putSectionValueWithType(IDialogSettings dialogSettings, @NotNull String key, Object value) { if (value == null) { dialogSettings.put(key, ((String) null)); return; } if (value instanceof Double) { dialogSettings.put(key, (Double) value); } else if (value instanceof Float) { dialogSettings.put(key, (Float) value); } else if (value instanceof Integer) { dialogSettings.put(key, (Integer) value); } else if (value instanceof Long) { dialogSettings.put(key, (Long) value); } else if (value instanceof String) { dialogSettings.put(key, (String) value); } else if (value instanceof Boolean) { dialogSettings.put(key, (Boolean) value); } else { // do nothing } dialogSettings.put(key + "_type", value.getClass().getSimpleName()); } public static Object getSectionValueWithType(IDialogSettings dialogSettings, @NotNull String key) { String type = dialogSettings.get(key + "_type"); if (type != null) { switch (type) { case "Double": return dialogSettings.getDouble(key); case "Float": return dialogSettings.getFloat(key); case "Integer": return dialogSettings.getInt(key); case "Long": return dialogSettings.getLong(key); case "String": return dialogSettings.get(key); case "Boolean": return dialogSettings.getBoolean(key); } } return dialogSettings.get(key); } @Nullable public static IWorkbenchPartSite getWorkbenchPartSite(IServiceLocator serviceLocator) { IWorkbenchPartSite partSite = serviceLocator.getService(IWorkbenchPartSite.class); if (partSite == null) { IWorkbenchPart activePart = serviceLocator.getService(IWorkbenchPart.class); if (activePart == null) { IWorkbenchWindow workbenchWindow = getActiveWorkbenchWindow(); if (workbenchWindow != null) { IWorkbenchPage activePage = workbenchWindow.getActivePage(); if (activePage != null) { activePart = activePage.getActivePart(); } } } if (activePart != null) { partSite = activePart.getSite(); } } return partSite; } public static boolean isContextActive(String contextId) { Collection<?> contextIds = getActiveWorkbenchWindow().getService(IContextService.class).getActiveContextIds(); for (Object id : contextIds) { if (contextId.equals(id)) { return true; } } return false; } @Nullable public static ISelectionProvider getSelectionProvider(IServiceLocator serviceLocator) { ISelectionProvider selectionProvider = serviceLocator.getService(ISelectionProvider.class); if (selectionProvider != null) { return selectionProvider; } IWorkbenchPartSite partSite = getWorkbenchPartSite(serviceLocator); if (partSite == null) { IWorkbenchPart activePart = serviceLocator.getService(IWorkbenchPart.class); if (activePart == null) { IWorkbenchWindow activeWindow = getActiveWorkbenchWindow(); if (activeWindow != null) { activePart = activeWindow.getActivePage().getActivePart(); } } if (activePart != null) { partSite = activePart.getSite(); } } if (partSite != null) { return partSite.getSelectionProvider(); } else { return null; } } public static void enableWithChildren(Control control, boolean enable) { control.setEnabled(enable); if (control instanceof Composite) { for (Control child : ((Composite)control).getChildren()) { if (child instanceof Composite) { enableWithChildren(child, enable); } else { child.setEnabled(enable); } } } } public static boolean isUIThread() { return Display.getCurrent() != null; } /** * Determine whether this control or any of it's child has focus * * @param control * control to check * @return true if it has focus */ public static boolean hasFocus(Control control) { if (control == null || control.isDisposed()) { return false; } Control focusControl = control.getDisplay().getFocusControl(); if (focusControl == null) { return false; } for (Control fc = focusControl; fc != null; fc = fc.getParent()) { if (fc == control) { return true; } } return false; } public static CTabItem getTabItem(CTabFolder tabFolder, Object data) { for (CTabItem item : tabFolder.getItems()) { if (item.getData() == data) { return item; } } return null; } public static void disposeControlOnItemDispose(final CTabItem tabItem) { tabItem.addDisposeListener(e -> { final Control control = tabItem.getControl(); if (!control.isDisposed()) { control.dispose(); } }); } public static TreeItem getTreeItem(Tree tree, Object data) { for (TreeItem item : tree.getItems()) { if (item.getData() == data) { return item; } TreeItem child = getTreeItem(item, data); if (child != null) { return child; } } return null; } private static TreeItem getTreeItem(TreeItem parent, Object data) { for (TreeItem item : parent.getItems()) { if (item.getData() == data) { return item; } TreeItem child = getTreeItem(item, data); if (child != null) { return child; } } return null; } public static int blend(int v1, int v2, int ratio) { return (ratio * v1 + (100 - ratio) * v2) / 100; } public static RGB blend(RGB c1, RGB c2, int ratio) { int r = blend(c1.red, c2.red, ratio); int g = blend(c1.green, c2.green, ratio); int b = blend(c1.blue, c2.blue, ratio); return new RGB(r, g, b); } public static boolean isParent(Control parent, Control child) { for (Control c = child; c != null; c = c.getParent()) { if (c == parent) { return true; } } return false; } public static boolean isInDialog() { try { Shell activeShell = Display.getCurrent().getActiveShell(); return activeShell != null && isInDialog(activeShell); } catch (Exception e) { // IF we are in wrong thread return false; } } public static boolean isInDialog(Control control) { return control.getShell().getData() instanceof org.eclipse.jface.dialogs.Dialog; } public static boolean isInWizard(Control control) { return control.getShell().getData() instanceof IWizardContainer; } public static Link createLink(Composite parent, String text, SelectionListener listener) { Link link = new Link(parent, SWT.NONE); link.setText(text); link.addSelectionListener(listener); return link; } public static void postEvent(Control ownerControl, final Event event) { final Display display = ownerControl.getDisplay(); asyncExec(() -> display.post(event)); } public static void drawMessageOverControl(Control control, PaintEvent e, String message, int offset) { drawMessageOverControl(control, e.gc, message, offset); } public static void drawMessageOverControl(Control control, GC gc, String message, int offset) { Rectangle bounds = control.getBounds(); final int height = gc.textExtent(message).y; for (String line : message.split("\n")) { line = line.trim(); Point ext = gc.textExtent(line); gc.drawText(line, (bounds.width - ext.x) / 2, (bounds.height - height) / 2 + offset); offset += ext.y; } } public static void createTableContextMenu(@NotNull final Table table, @Nullable DBRCreator<Boolean, IContributionManager> menuCreator) { MenuManager menuMgr = new MenuManager(); menuMgr.addMenuListener(manager -> { if (menuCreator != null) { if (!menuCreator.createObject(menuMgr)) { return; } } UIUtils.fillDefaultTableContextMenu(manager, table); }); menuMgr.setRemoveAllWhenShown(true); table.setMenu(menuMgr.createContextMenu(table)); table.addDisposeListener(e -> menuMgr.dispose()); } public static void setControlContextMenu(Control control, IMenuListener menuListener) { MenuManager menuMgr = new MenuManager(); menuMgr.addMenuListener(menuListener); menuMgr.setRemoveAllWhenShown(true); control.setMenu(menuMgr.createContextMenu(control)); control.addDisposeListener(e -> menuMgr.dispose()); } public static void fillDefaultTableContextMenu(IContributionManager menu, final Table table) { if (table.getColumnCount() > 1) { menu.add(new Action(NLS.bind(UIMessages.utils_actions_copy_label, table.getColumn(0).getText())) { @Override public void run() { StringBuilder text = new StringBuilder(); for (TableItem item : table.getSelection()) { if (text.length() > 0) text.append("\n"); text.append(item.getText(0)); } if (text.length() == 0) { return; } UIUtils.setClipboardContents(table.getDisplay(), TextTransfer.getInstance(), text.toString()); } }); } menu.add(new Action(UIMessages.utils_actions_copy_all_label) { @Override public void run() { StringBuilder text = new StringBuilder(); int columnCount = table.getColumnCount(); for (TableItem item : table.getSelection()) { if (text.length() > 0) text.append("\n"); for (int i = 0 ; i < columnCount; i++) { if (i > 0) text.append("\t"); text.append(item.getText(i)); } } if (text.length() == 0) { return; } UIUtils.setClipboardContents(table.getDisplay(), TextTransfer.getInstance(), text.toString()); } }); } public static void fillDefaultTreeContextMenu(IContributionManager menu, final Tree tree) { if (tree.getColumnCount() > 1) { menu.add(new Action("Copy " + tree.getColumn(0).getText()) { @Override public void run() { StringBuilder text = new StringBuilder(); for (TreeItem item : tree.getSelection()) { if (text.length() > 0) text.append("\n"); text.append(item.getText(0)); } if (text.length() == 0) { return; } UIUtils.setClipboardContents(tree.getDisplay(), TextTransfer.getInstance(), text.toString()); } }); } menu.add(new Action(UIMessages.utils_actions_copy_all_label) { @Override public void run() { StringBuilder text = new StringBuilder(); int columnCount = tree.getColumnCount(); for (TreeItem item : tree.getSelection()) { if (text.length() > 0) text.append("\n"); for (int i = 0 ; i < columnCount; i++) { if (i > 0) text.append("\t"); text.append(item.getText(i)); } } if (text.length() == 0) { return; } UIUtils.setClipboardContents(tree.getDisplay(), TextTransfer.getInstance(), text.toString()); } }); //menu.add(ActionFactory.SELECT_ALL.create(UIUtils.getActiveWorkbenchWindow())); } public static void addFileOpenOverlay(Text text, SelectionListener listener) { final Image browseImage = DBeaverIcons.getImage(DBIcon.TREE_FOLDER); final Rectangle iconBounds = browseImage.getBounds(); text.addPaintListener(e -> { final Rectangle bounds = ((Text) e.widget).getBounds(); e.gc.drawImage(browseImage, bounds.width - iconBounds.width - 2, 0); }); } public static Combo createDelimiterCombo(Composite group, String label, String[] options, String defDelimiter, boolean multiDelims) { createControlLabel(group, label); Combo combo = new Combo(group, SWT.BORDER | SWT.DROP_DOWN); combo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); for (String option : options) { combo.add(CommonUtils.escapeDisplayString(option)); } if (!multiDelims) { if (!ArrayUtils.contains(options, defDelimiter)) { combo.add(CommonUtils.escapeDisplayString(defDelimiter)); } String[] items = combo.getItems(); for (int i = 0, itemsLength = items.length; i < itemsLength; i++) { String delim = CommonUtils.unescapeDisplayString(items[i]); if (delim.equals(defDelimiter)) { combo.select(i); break; } } } else { combo.setText(CommonUtils.escapeDisplayString(defDelimiter)); } return combo; } public static SharedTextColors getSharedTextColors() { return SHARED_TEXT_COLORS; } public static SharedFonts getSharedFonts() { return SHARED_FONTS; } public static void run( IRunnableContext runnableContext, boolean fork, boolean cancelable, final DBRRunnableWithProgress runnableWithProgress) throws InvocationTargetException, InterruptedException { runnableContext.run(fork, cancelable, monitor -> runnableWithProgress.run(RuntimeUtils.makeMonitor(monitor))); } public static AbstractUIJob runUIJob(String jobName, final DBRRunnableWithProgress runnableWithProgress) { return runUIJob(jobName, 0, runnableWithProgress); } public static AbstractUIJob runUIJob(String jobName, int timeout, final DBRRunnableWithProgress runnableWithProgress) { AbstractUIJob job = new AbstractUIJob(jobName) { @Override public IStatus runInUIThread(DBRProgressMonitor monitor) { try { runnableWithProgress.run(monitor); } catch (InvocationTargetException e) { return GeneralUtils.makeExceptionStatus(e); } catch (InterruptedException e) { return Status.CANCEL_STATUS; } return Status.OK_STATUS; } }; job.setSystem(true); job.schedule(timeout); return job; } @Nullable public static IWorkbenchWindow findActiveWorkbenchWindow() { IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); if (window != null) { return window; } IWorkbenchWindow[] windows = workbench.getWorkbenchWindows(); if (windows.length > 0) { return windows[0]; } return null; } @NotNull public static IWorkbenchWindow getActiveWorkbenchWindow() { IWorkbenchWindow workbenchWindow = findActiveWorkbenchWindow(); if (workbenchWindow == null) { throw new IllegalStateException("No workbench window"); } return workbenchWindow; } public static IWorkbenchWindow getParentWorkbenchWindow(Control control) { for (Control p = control.getParent(); p != null; p = p.getParent()) { if (p.getData() instanceof IWorkbenchWindow) { return (IWorkbenchWindow) p.getData(); } } return null; } @Nullable public static Shell getActiveWorkbenchShell() { if (PlatformUI.isWorkbenchRunning()) { IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); if (window != null) { Shell shell = window.getShell(); if (shell != null && shell.isVisible()) { return shell; } } } return getActiveShell(); } public static DBRRunnableContext getDefaultRunnableContext() { IWorkbench workbench = PlatformUI.getWorkbench(); if (workbench != null && workbench.getActiveWorkbenchWindow() != null) { return new RunnableContextDelegate(workbench.getActiveWorkbenchWindow()); } else { return (fork, cancelable, runnable) -> runnable.run(new VoidProgressMonitor()); } } public static DBRRunnableContext getDialogRunnableContext() { return (fork, cancelable, runnable) -> runInProgressDialog(runnable); } /** * Runs task in Eclipse progress service. * NOTE: this call can't be canceled if it will block in IO */ public static void runInProgressService(final DBRRunnableWithProgress runnable) throws InvocationTargetException, InterruptedException { getDefaultRunnableContext().run(true, true, runnable); } /** * Runs task in Eclipse progress dialog. * NOTE: this call can't be canceled if it will block in IO */ public static void runInProgressDialog(final DBRRunnableWithProgress runnable) throws InvocationTargetException { try { IRunnableContext runnableContext; IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow(); if (workbenchWindow != null) { runnableContext = new ProgressMonitorDialog(workbench.getActiveWorkbenchWindow().getShell()); } else { runnableContext = workbench.getProgressService(); } runnableContext.run(true, true, monitor -> runnable.run(RuntimeUtils.makeMonitor(monitor))); } catch (InterruptedException e) { // do nothing } } public static void runInUI(IRunnableContext context, final DBRRunnableWithProgress runnable) { try { PlatformUI.getWorkbench().getProgressService().runInUI(context, monitor -> runnable.run(RuntimeUtils.makeMonitor(monitor)), ResourcesPlugin.getWorkspace().getRoot()); } catch (InvocationTargetException e) { DBWorkbench.getPlatformUI().showError(null, null, e.getTargetException()); } catch (InterruptedException e) { // do nothing } } public static void runInUI(final DBRRunnableWithProgress runnable) { IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); IRunnableContext context = window != null ? window : DummyRunnableContext.INSTANCE; runInUI(context, runnable); } public static Display getDisplay() { try { return PlatformUI.getWorkbench().getDisplay(); } catch (Exception e) { return Display.getDefault(); } } public static void timerExec(int milliseconds, @NotNull Runnable runnable) { try { Display display = getDisplay(); if (!display.isDisposed()) { display.timerExec(milliseconds, runnable); } } catch (Exception e) { log.debug(e); } } public static void asyncExec(Runnable runnable) { try { Display display = getDisplay(); if (!display.isDisposed()) { display.asyncExec(runnable); } } catch (Exception e) { log.debug(e); } } public static void syncExec(Runnable runnable) { try { Display display = getDisplay(); if (!display.isDisposed()) { display.syncExec(runnable); } } catch (Exception e) { log.debug(e); } } public static <T> T syncExec(RunnableWithResult<T> runnable) { try { getDisplay().syncExec(runnable); return runnable.getResult(); } catch (Exception e) { log.debug(e); return null; } } @Nullable public static Color getSharedColor(@Nullable String rgbString) { if (CommonUtils.isEmpty(rgbString)) { return null; } return SHARED_TEXT_COLORS.getColor(rgbString); } @Nullable public static Color getSharedColor(@Nullable RGB rgb) { if (rgb == null) { return null; } return SHARED_TEXT_COLORS.getColor(rgb); } public static Color getConnectionColor(DBPConnectionConfiguration connectionInfo) { String rgbString = connectionInfo.getConnectionColor(); if (CommonUtils.isEmpty(rgbString)) { rgbString = connectionInfo.getConnectionType().getColor(); } if (CommonUtils.isEmpty(rgbString)) { return null; } return getConnectionColorByRGB(rgbString); } public static Color getConnectionTypeColor(DBPConnectionType connectionType) { String rgbString = connectionType.getColor(); if (CommonUtils.isEmpty(rgbString)) { return null; } return getConnectionColorByRGB(rgbString); } public static Color getConnectionColorByRGB(String rgbStringOrId) { if (rgbStringOrId.isEmpty()) { return null; } if (Character.isAlphabetic(rgbStringOrId.charAt(0))) { // Some color constant RGB rgb = getActiveWorkbenchWindow().getWorkbench().getThemeManager().getCurrentTheme().getColorRegistry().getRGB(rgbStringOrId); return SHARED_TEXT_COLORS.getColor(rgb); } else { Color connectionColor = SHARED_TEXT_COLORS.getColor(rgbStringOrId); if (connectionColor.getBlue() == 255 && connectionColor.getRed() == 255 && connectionColor.getGreen() == 255) { // For white color return just null to avoid explicit color set. // It is important for dark themes return null; } return connectionColor; } } /** * Create centralized shell from default display * */ public static Shell createCenteredShell(Shell parent) { final Rectangle bounds = parent.getBounds(); final int x = bounds.x + bounds.width / 2 - 120; final int y = bounds.y + bounds.height / 2 - 170; final Shell shell = new Shell(parent); shell.setLocation(x, y); return shell; } public static void centerShell(Shell parent, Shell shell) { if (parent == null || shell == null) { return; } Point size = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT); final Rectangle parentBounds = parent.getBounds(); final int x = parentBounds.x + (parentBounds.width - size.x) / 2; final int y = parentBounds.y + (parentBounds.height - size.y) / 2; shell.setLocation(x, y); } public static Image getShardImage(String id) { return PlatformUI.getWorkbench().getSharedImages().getImage(id); } public static ImageDescriptor getShardImageDescriptor(String id) { return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(id); } public static void addVariablesToControl(@NotNull Control controlForTip, @NotNull String[] variables, String toolTipPattern) { final StringContentProposalProvider proposalProvider = new StringContentProposalProvider(Arrays .stream(variables) .map(GeneralUtils::variablePattern) .toArray(String[]::new)); UIUtils.setContentProposalToolTip(controlForTip, toolTipPattern, variables); ContentAssistUtils.installContentProposal(controlForTip, new SmartTextContentAdapter(), proposalProvider); } public static void setContentProposalToolTip(Control control, String toolTip, String ... variables) { control.setToolTipText(getSupportedVariablesTip(toolTip, variables)); } @NotNull public static String getSupportedVariablesTip(String toolTip, String ... variables) { StringBuilder varsTip = new StringBuilder(); varsTip.append(toolTip).append(". ").append(UIMessages.pref_page_connections_tool_tip_text_allowed_variables).append(":\n"); for (int i = 0; i < variables.length; i++) { String var = variables[i]; if (i > 0) varsTip.append(",\n"); varsTip.append(" ").append(GeneralUtils.variablePattern(var)); } varsTip.append("."); //$NON-NLS-1$ return varsTip.toString(); } public static CoolItem createCoolItem(CoolBar coolBar, Control control) { CoolItem item = new CoolItem(coolBar, SWT.NONE); item.setControl(control); Point size = control.computeSize(SWT.DEFAULT, SWT.DEFAULT); Point preferred = item.computeSize(size.x, size.y); item.setPreferredSize(preferred); return item; } public static void resizeShell(@NotNull Shell shell) { final Rectangle displayArea = shell.getDisplay().getClientArea(); final Point shellLocation = shell.getLocation(); final Point shellSize = shell.getSize(); final Point compSize = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); boolean needsLayout = false; if (shellSize.x < compSize.x || shellSize.y < compSize.y) { shellSize.x = Math.max(shellSize.x, compSize.x); shellSize.y = Math.max(shellSize.y, compSize.y); shell.setSize(shellSize); } if (shellLocation.x + shellSize.x > displayArea.width || shellLocation.y + shellSize.y > displayArea.height) { shellLocation.x = CommonUtils.clamp(displayArea.width - shellSize.x, 0, shellLocation.x); shellLocation.y = CommonUtils.clamp(displayArea.height - shellSize.y, 0, shellLocation.y); shell.setLocation(shellLocation.x, shellLocation.y); needsLayout = true; } if (needsLayout) { shell.layout(true); } } public static void waitJobCompletion(AbstractJob job) { waitJobCompletion(job, null); } public static void waitJobCompletion(@NotNull AbstractJob job, @Nullable IProgressMonitor monitor) { // Wait until job finished Display display = Display.getCurrent(); while (!job.isFinished()) { if (monitor != null && monitor.isCanceled()) { job.cancel(); } if (!display.readAndDispatch()) { display.sleep(); } } display.update(); } public static void waitInUI(DBRCondition condition, long waitTime) { syncExec(() -> { long startTime = System.currentTimeMillis(); Display display = Display.getCurrent(); do { if (!display.readAndDispatch()) { RuntimeUtils.pause(100); } } while (!condition.isConditionMet() && (System.currentTimeMillis() - startTime) < waitTime); display.update(); }); } public static void fixReadonlyTextBackground(Text textField) { // There is still no good workaround: https://bugs.eclipse.org/bugs/show_bug.cgi?id=340889 if (false) { if (RuntimeUtils.isWindows()) { // On Windows everything is fine return; } if ((textField.getStyle() & SWT.READ_ONLY) == SWT.READ_ONLY) { textField.setBackground(textField.getDisplay().getSystemColor(SWT.COLOR_WIDGET_HIGHLIGHT_SHADOW)); } else { textField.setBackground(null); } } } public static ColorRegistry getColorRegistry() { return PlatformUI.getWorkbench().getThemeManager().getCurrentTheme().getColorRegistry(); } public static Color getGlobalColor(String colorName) { return getColorRegistry().get(colorName); } public static Control createEmptyLabel(Composite parent, int horizontalSpan, int verticalSpan) { Label emptyLabel = new Label(parent, SWT.NONE); GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_END); gd.horizontalSpan = horizontalSpan; gd.verticalSpan = verticalSpan; gd.widthHint = 0; emptyLabel.setLayoutData(gd); return emptyLabel; } public static void disposeChildControls(Composite composite) { for (Control child : composite.getChildren()) { child.dispose(); } } ////////////////////////////////////////// // From E4 sources /** * Returns the grey value in which the given color would be drawn in grey-scale. */ public static double greyLevel(RGB rgb) { if (rgb.red == rgb.green && rgb.green == rgb.blue) return rgb.red; return (0.299 * rgb.red + 0.587 * rgb.green + 0.114 * rgb.blue + 0.5); } /** * Returns whether the given color is dark or light depending on the colors grey-scale level. */ public static boolean isDark(RGB rgb) { return greyLevel(rgb) < 128; } /** * Calculate the Contrast color based on Luma(brightness) * https://en.wikipedia.org/wiki/Luma_(video) * * Do not dispose returned color. */ public static Color getContrastColor(Color color) { if (color == null) { return COLOR_BLACK; } double luminance = 1 - (0.299 * color.getRed() + 0.587 * color.getGreen() + 0.114 * color.getBlue()) / 255; if (luminance > 0.5) { return UIStyles.isDarkTheme() ? COLOR_WHITE_DARK : COLOR_WHITE; } return COLOR_BLACK; } public static Color getInvertedColor(Color color) { return new Color(255 - color.getRed(), 255 - color.getGreen(), 255 - color.getBlue()); } public static void openWebBrowser(String url) { url = url.trim(); if (!url.startsWith("http://") && !url.startsWith("https://") && !url.startsWith("ftp://")) { url = "http://" + url; } ShellUtils.launchProgram(url); } public static void setBackgroundForAll(Control control, Color color) { if (!(control instanceof Button)) { control.setBackground(color); } if (control instanceof Composite) { for (Control ch : ((Composite) control).getChildren()) { setBackgroundForAll(ch, color); } } } public static <T extends Control> void addEmptyTextHint(T control, DBRValueProvider<String, T> tipProvider) { final Font hintFont = UIUtils.modifyFont(control.getFont(), SWT.ITALIC); control.addDisposeListener(e -> hintFont.dispose()); control.addPaintListener(e -> { String tip = tipProvider.getValue(control); if (tip != null && isEmptyTextControl(control) && !control.isFocusControl()) { final GC gc = e.gc; final Point textSize = gc.textExtent(tip); final Point controlSize = control.computeSize(SWT.DEFAULT, SWT.DEFAULT); final int baseline = (controlSize.y - textSize.y) / 2; gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW)); gc.setFont(hintFont); gc.drawText(tip, baseline, baseline, true); gc.setFont(null); } }); } private static boolean isEmptyTextControl(Control control) { return (control instanceof Text && ((Text) control).getCharCount() == 0) || (control instanceof StyledText && ((StyledText) control).getCharCount() == 0) || (control instanceof Combo && ((Combo) control).getText().isEmpty()); } public static void expandAll(AbstractTreeViewer treeViewer) { Control control = treeViewer.getControl(); control.setRedraw(false); try { // Do not use expandAll(true) as it is not supported by Eclipse versions before 2019 treeViewer.expandAll(); } finally { control.setRedraw(true); } } public static Font getMonospaceFont() { return PlatformUI.getWorkbench().getThemeManager().getCurrentTheme().getFontRegistry().get(UIFonts.DBEAVER_FONTS_MONOSPACE); } public static <T extends Control> T getParentOfType(Control control, Class<T> parentType) { while (control != null) { if (parentType.isInstance(control)) { return parentType.cast(control); } control = control.getParent(); } return null; } public static Object normalizePropertyValue(Object text) { if (text instanceof String) { return CommonUtils.toString(text).trim(); } return text; } public static void setControlVisible(Control control, boolean visible) { control.setVisible(visible); Object gd = control.getLayoutData(); if (gd instanceof GridData) { ((GridData) gd).exclude = !visible; } } public static void drawTextWithBackground(@NotNull GC gc, @NotNull String text, int x, int y) { final Point size = gc.textExtent(text); final int centerX = x - size.x / 2; final int centerY = y - size.y; gc.setForeground(UIStyles.getDefaultTextForeground()); gc.setBackground(UIStyles.getDefaultTextBackground()); gc.fillRectangle(centerX - 2, centerY - 2, size.x + 4, size.y + 4); gc.drawText(text, centerX, centerY, true); gc.drawRoundRectangle(centerX - 3, centerY - 3, size.x + 5, size.y + 5, 5, 5); } public static void installMacOSFocusLostSubstitution(@NotNull Widget widget, @NotNull Runnable onFocusLost) { if (!RuntimeUtils.isMacOS()) { return; } if (widget instanceof Combo || widget instanceof CCombo) { widget.addListener(SWT.Selection, new TypedListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onFocusLost.run(); } })); } else { widget.addDisposeListener(e -> onFocusLost.run()); } } public static void installAndUpdateMainFont(@NotNull Control control) { final IPropertyChangeListener listener = event -> { if (event.getProperty().equals(UIFonts.DBEAVER_FONTS_MAIN_FONT)) { applyMainFont(control); } }; PlatformUI.getWorkbench().getThemeManager().addPropertyChangeListener(listener); control.addDisposeListener(e -> PlatformUI.getWorkbench().getThemeManager().removePropertyChangeListener(listener)); applyMainFont(control); } public static void applyMainFont(@Nullable Control control) { if (control == null || control.isDisposed() || mainFontIsDefault()) { return; } applyMainFont(control, JFaceResources.getFont(UIFonts.DBEAVER_FONTS_MAIN_FONT)); } @Nullable public static Text recreateTextControl(@Nullable Text original, int style) { if (original == null || original.getStyle() == style) { return original; } final Composite parent = original.getParent(); final Control[] tabList = parent.getTabList(); final Text text = new Text(parent, style); text.setText(original.getText()); text.setLayoutData(original.getLayoutData()); text.moveAbove(original); copyListeners(original, text, SWT.DefaultSelection); copyListeners(original, text, SWT.Modify); copyListeners(original, text, SWT.Verify); original.dispose(); for (int i = 0; i < tabList.length; i++) { if (tabList[i] == original) { tabList[i] = text; } } parent.setTabList(tabList); parent.layout(true, true); return text; } private static void copyListeners(@NotNull Widget source, @NotNull Widget target, int eventType) { for (Listener listener : source.getListeners(eventType)) { target.addListener(eventType, listener); } } private static void applyMainFont(@NotNull Control control, @NotNull Font font) { control.setFont(font); if (control instanceof Composite) { for (Control element : ((Composite) control).getChildren()) { applyMainFont(element, font); } } } private static boolean mainFontIsDefault() { final FontData[] mainFontData = JFaceResources.getFontRegistry().getFontData(UIFonts.DBEAVER_FONTS_MAIN_FONT); final FontData[] defaultFontData = JFaceResources.getFontRegistry().getFontData(JFaceResources.DEFAULT_FONT); return Arrays.equals(mainFontData, defaultFontData); } @Nullable public static ToolItem findToolItemByCommandId(@NotNull ToolBarManager toolbarManager, @NotNull String commandId) { for (ToolItem item : toolbarManager.getControl().getItems()) { Object data = item.getData(); if (data instanceof CommandContributionItem) { ParameterizedCommand cmd = ((CommandContributionItem) data).getCommand(); if (cmd != null && commandId.equals(cmd.getId())) { return item; } } else if (data instanceof HandledContributionItem) { MHandledItem model = ((HandledContributionItem) data).getModel(); if (model != null ) { ParameterizedCommand cmd = model.getWbCommand(); if (cmd != null && commandId.equals(cmd.getId())) { return item; } } } } return null; } public static void populateToolItemCommandIds(ToolBarManager toolbarManager) { // used for accessibility automation, see dbeaver-qa-auto for (ToolItem item : toolbarManager.getControl().getItems()) { Object data = item.getData(); if (data instanceof CommandContributionItem) { ParameterizedCommand cmd = ((CommandContributionItem) data).getCommand(); if (cmd != null) { item.setData("commandId", cmd.getId()); } } else if (data instanceof HandledContributionItem) { MHandledItem model = ((HandledContributionItem) data).getModel(); if (model != null) { ParameterizedCommand cmd = model.getWbCommand(); if (cmd != null) { item.setData("commandId", cmd.getId()); } } } } } public static void enableDoubleBuffering(@NotNull Control control) { if ((control.getStyle() & SWT.DOUBLE_BUFFERED) != 0) { // Already enabled - no op return; } try { final Field styleField = Widget.class.getDeclaredField("style"); if (!styleField.canAccess(control)) { styleField.setAccessible(true); } styleField.set(control, styleField.getInt(control) | SWT.DOUBLE_BUFFERED); } catch (Exception e) { log.error("Unable to enable double buffering", e.getCause()); } } }
dbeaver/dbeaver
plugins/org.jkiss.dbeaver.ui/src/org/jkiss/dbeaver/ui/UIUtils.java
41,659
package me.chanjar.weixin.cp.bean.message; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import lombok.Data; import me.chanjar.weixin.common.api.WxConsts.KefuMsgType; import me.chanjar.weixin.cp.bean.article.MpnewsArticle; import me.chanjar.weixin.cp.bean.article.NewArticle; import me.chanjar.weixin.cp.bean.messagebuilder.*; import me.chanjar.weixin.cp.bean.taskcard.TaskCardButton; import me.chanjar.weixin.cp.bean.templatecard.*; import org.apache.commons.lang3.StringUtils; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; import static me.chanjar.weixin.common.api.WxConsts.KefuMsgType.*; /** * 消息. * * @author Daniel Qian */ @Data public class WxCpMessage implements Serializable { private static final long serialVersionUID = -2082278303476631708L; /** * 指定接收消息的成员,成员ID列表(多个接收者用‘|’分隔,最多支持1000个)。 * 特殊情况:指定为"@all",则向该企业应用的全部成员发送 */ private String toUser; /** * 指定接收消息的部门,部门ID列表,多个接收者用‘|’分隔,最多支持100个。 * 当touser为"@all"时忽略本参数 */ private String toParty; /** * 指定接收消息的标签,标签ID列表,多个接收者用‘|’分隔,最多支持100个。 * 当touser为"@all"时忽略本参数 */ private String toTag; /** * 企业应用的id,整型。企业内部开发,可在应用的设置页面查看;第三方服务商,可通过接口 获取企业授权信息 获取该参数值 */ private Integer agentId; /** * 消息类型 * 文本消息: text * 图片消息: image * 语音消息: voice * 视频消息: video * 文件消息: file * 文本卡片消息: textcard * 图文消息: news * 图文消息: mpnews * markdown消息: markdown * 模板卡片消息: template_card */ private String msgType; /** * 消息内容,最长不超过2048个字节,超过将截断(支持id转译) */ private String content; /** * 媒体文件id,可以调用上传临时素材接口获取 */ private String mediaId; /** * 图文消息缩略图的media_id, 可以通过素材管理接口获得。此处thumb_media_id即上传接口返回的media_id */ private String thumbMediaId; /** * 标题,不超过128个字节,超过会自动截断(支持id转译) */ private String title; /** * 描述,不超过512个字节,超过会自动截断(支持id转译) */ private String description; private String musicUrl; private String hqMusicUrl; /** * 表示是否是保密消息,默认为0;注意仅 mpnews 类型的消息支持safe值为2,其他消息类型不支持 * 0表示可对外分享 * 1表示不能分享且内容显示水印 * 2表示仅限在企业内分享 */ private String safe; /** * 点击后跳转的链接。最长2048字节,请确保包含了协议头(http/https) */ private String url; /** * 按钮文字。 默认为“详情”, 不超过4个文字,超过自动截断。 */ private String btnTxt; /** * 图文消息,一个图文消息支持1到8条图文 */ private List<NewArticle> articles = new ArrayList<>(); /** * 图文消息,一个图文消息支持1到8条图文 */ private List<MpnewsArticle> mpnewsArticles = new ArrayList<>(); /** * 小程序appid,必须是与当前应用关联的小程序,appid和pagepath必须同时填写,填写后会忽略url字段 */ private String appId; /** * 点击消息卡片后的小程序页面,最长1024个字节,仅限本小程序内的页面。该字段不填则消息点击后不跳转。 */ private String page; /** * 是否放大第一个content_item */ private Boolean emphasisFirstItem; /** * 消息内容键值对,最多允许10个item */ private Map<String, String> contentItems; /** * enable_id_trans * 表示是否开启id转译,0表示否,1表示是,默认0 */ private Boolean enableIdTrans = false; /** * enable_duplicate_check * 表示是否开启重复消息检查,0表示否,1表示是,默认0 */ private Boolean enableDuplicateCheck = false; /** * duplicate_check_interval * 表示是否重复消息检查的时间间隔,默认1800s,最大不超过4小时 */ private Integer duplicateCheckInterval; /** * 任务卡片特有的属性. */ private String taskId; private List<TaskCardButton> taskButtons = new ArrayList<>(); // 模板型卡片特有属性 /** * 模板卡片类型,文本通知型卡片填写 “text_notice”, * 图文展示型卡片此处填写 “news_notice”, * 按钮交互型卡片填写”button_interaction”, * 投票选择型卡片填写”vote_interaction”, * 多项选择型卡片填写 “multiple_interaction” */ private String cardType; /** * 卡片来源样式信息,不需要来源样式可不填写 * 来源图片的url */ private String sourceIconUrl; /** * 卡片来源样式信息,不需要来源样式可不填写 * 来源图片的描述,建议不超过20个字 */ private String sourceDesc; /** * 来源文字的颜色,目前支持:0(默认) 灰色,1 黑色,2 红色,3 绿色 */ private Integer sourceDescColor; /** * 更多操作界面的描述 */ private String actionMenuDesc; /** * 操作列表,列表长度取值范围为 [1, 3] */ private List<ActionMenuItem> actionMenuActionList; /** * 一级标题,建议不超过36个字 */ private String mainTitleTitle; /** * 标题辅助信息,建议不超过44个字 */ private String mainTitleDesc; /** * 左图右文样式,news_notice类型的卡片,card_image 和 image_text_area 两者必填一个字段,不可都不填 */ private TemplateCardImageTextArea imageTextArea; /** * 图文展示型的卡片必须有图片字段。 * 图片的url. */ private String cardImageUrl; /** * 图片的宽高比,宽高比要小于2.25,大于1.3,不填该参数默认1.3 */ private Float cardImageAspectRatio; /** * 关键数据样式 * 关键数据样式的数据内容,建议不超过14个字 */ private String emphasisContentTitle; /** * 关键数据样式的数据描述内容,建议不超过22个字 */ private String emphasisContentDesc; /** * 二级普通文本,建议不超过160个字 */ private String subTitleText; /** * 卡片二级垂直内容,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过4 */ private List<VerticalContent> verticalContents; /** * 二级标题+文本列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过6 */ private List<HorizontalContent> horizontalContents; /** * 跳转指引样式的列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过3 */ private List<TemplateCardJump> jumps; /** * 整体卡片的点击跳转事件,text_notice必填本字段 * 跳转事件类型,1 代表跳转url,2 代表打开小程序。text_notice卡片模版中该字段取值范围为[1,2] */ private Integer cardActionType; /** * 跳转事件的url,card_action.type是1时必填 */ private String cardActionUrl; /** * 跳转事件的小程序的appid,必须是与当前应用关联的小程序,card_action.type是2时必填 */ private String cardActionAppid; /** * 跳转事件的小程序的pagepath,card_action.type是2时选填 */ private String cardActionPagepath; /** * 按钮交互型卡片需指定。 * button_selection */ private TemplateCardButtonSelection buttonSelection; /** * 按钮交互型卡片需指定。 * 按钮列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过6 */ private List<TemplateCardButton> buttons; /** * 投票选择型卡片需要指定 * 选择题key值,用户提交选项后,会产生回调事件,回调事件会带上该key值表示该题,最长支持1024字节 */ private String checkboxQuestionKey; /** * 选择题模式,单选:0,多选:1,不填默认0 */ private Integer checkboxMode; /** * 选项list,选项个数不超过 20 个,最少1个 */ private List<CheckboxOption> options; /** * 提交按钮样式 * 按钮文案,建议不超过10个字,不填默认为提交 */ private String submitButtonText; /** * 提交按钮的key,会产生回调事件将本参数作为EventKey返回,最长支持1024字节 */ private String submitButtonKey; /** * 下拉式的选择器列表,multiple_interaction类型的卡片该字段不可为空,一个消息最多支持 3 个选择器 */ private List<MultipleSelect> selects; /** * 引用文献样式 */ private QuoteArea quoteArea; /** * 获得文本消息builder. * * @return the text builder */ public static TextBuilder TEXT() { return new TextBuilder(); } /** * 获得文本卡片消息builder. * * @return the text card builder */ public static TextCardBuilder TEXTCARD() { return new TextCardBuilder(); } /** * 获得图片消息builder. * * @return the image builder */ public static ImageBuilder IMAGE() { return new ImageBuilder(); } /** * 获得语音消息builder. * * @return the voice builder */ public static VoiceBuilder VOICE() { return new VoiceBuilder(); } /** * 获得视频消息builder. * * @return the video builder */ public static VideoBuilder VIDEO() { return new VideoBuilder(); } /** * 获得图文消息builder. * * @return the news builder */ public static NewsBuilder NEWS() { return new NewsBuilder(); } /** * 获得mpnews图文消息builder. * * @return the mpnews builder */ public static MpnewsBuilder MPNEWS() { return new MpnewsBuilder(); } /** * 获得markdown消息builder. * * @return the markdown msg builder */ public static MarkdownMsgBuilder MARKDOWN() { return new MarkdownMsgBuilder(); } /** * 获得文件消息builder. * * @return the file builder */ public static FileBuilder FILE() { return new FileBuilder(); } /** * 获得任务卡片消息builder. * * @return the task card builder */ public static TaskCardBuilder TASKCARD() { return new TaskCardBuilder(); } /** * 获得模板卡片消息builder. * * @return the template card builder */ public static TemplateCardBuilder TEMPLATECARD() { return new TemplateCardBuilder(); } /** * 获得小程序通知消息builder. * * @return the mini program notice msg builder */ public static MiniProgramNoticeMsgBuilder newMiniProgramNoticeBuilder() { return new MiniProgramNoticeMsgBuilder(); } /** * <pre> * 请使用. * {@link KefuMsgType#TEXT} * {@link KefuMsgType#IMAGE} * {@link KefuMsgType#VOICE} * {@link KefuMsgType#MUSIC} * {@link KefuMsgType#VIDEO} * {@link KefuMsgType#NEWS} * {@link KefuMsgType#MPNEWS} * {@link KefuMsgType#MARKDOWN} * {@link KefuMsgType#TASKCARD} * {@link KefuMsgType#MINIPROGRAM_NOTICE} * {@link KefuMsgType#TEMPLATE_CARD} * </pre> * * @param msgType 消息类型 */ public void setMsgType(String msgType) { this.msgType = msgType; } /** * To json string. * * @return the string */ public String toJson() { JsonObject messageJson = new JsonObject(); if (this.getAgentId() != null) { messageJson.addProperty("agentid", this.getAgentId()); } if (StringUtils.isNotBlank(this.getToUser())) { messageJson.addProperty("touser", this.getToUser()); } messageJson.addProperty("msgtype", this.getMsgType()); if (StringUtils.isNotBlank(this.getToParty())) { messageJson.addProperty("toparty", this.getToParty()); } if (StringUtils.isNotBlank(this.getToTag())) { messageJson.addProperty("totag", this.getToTag()); } if (this.getEnableIdTrans()) { messageJson.addProperty("enable_id_trans", 1); } if (this.getEnableDuplicateCheck()) { messageJson.addProperty("enable_duplicate_check", 1); } if (this.getDuplicateCheckInterval() != null) { messageJson.addProperty("duplicate_check_interval", this.getDuplicateCheckInterval()); } this.handleMsgType(messageJson); if (StringUtils.isNotBlank(this.getSafe())) { messageJson.addProperty("safe", this.getSafe()); } return messageJson.toString(); } private void handleMsgType(JsonObject messageJson) { switch (this.getMsgType()) { case TEXT: { JsonObject text = new JsonObject(); text.addProperty("content", this.getContent()); messageJson.add("text", text); break; } case MARKDOWN: { JsonObject text = new JsonObject(); text.addProperty("content", this.getContent()); messageJson.add("markdown", text); break; } case TEXTCARD: { JsonObject text = new JsonObject(); text.addProperty("title", this.getTitle()); text.addProperty("description", this.getDescription()); text.addProperty("url", this.getUrl()); text.addProperty("btntxt", this.getBtnTxt()); messageJson.add("textcard", text); break; } case IMAGE: { JsonObject image = new JsonObject(); image.addProperty("media_id", this.getMediaId()); messageJson.add("image", image); break; } case FILE: { JsonObject image = new JsonObject(); image.addProperty("media_id", this.getMediaId()); messageJson.add("file", image); break; } case VOICE: { JsonObject voice = new JsonObject(); voice.addProperty("media_id", this.getMediaId()); messageJson.add("voice", voice); break; } case VIDEO: { JsonObject video = new JsonObject(); video.addProperty("media_id", this.getMediaId()); video.addProperty("thumb_media_id", this.getThumbMediaId()); video.addProperty("title", this.getTitle()); video.addProperty("description", this.getDescription()); messageJson.add("video", video); break; } case NEWS: { JsonObject newsJsonObject = new JsonObject(); JsonArray articleJsonArray = new JsonArray(); for (NewArticle article : this.getArticles()) { JsonObject articleJson = new JsonObject(); articleJson.addProperty("title", article.getTitle()); articleJson.addProperty("description", article.getDescription()); articleJson.addProperty("url", article.getUrl()); articleJson.addProperty("picurl", article.getPicUrl()); articleJson.addProperty("appid", article.getAppid()); articleJson.addProperty("pagepath", article.getPagepath()); articleJsonArray.add(articleJson); } newsJsonObject.add("articles", articleJsonArray); messageJson.add("news", newsJsonObject); break; } case MPNEWS: { JsonObject newsJsonObject = new JsonObject(); if (this.getMediaId() != null) { newsJsonObject.addProperty("media_id", this.getMediaId()); } else { JsonArray articleJsonArray = new JsonArray(); for (MpnewsArticle article : this.getMpnewsArticles()) { article2Json(articleJsonArray, article); } newsJsonObject.add("articles", articleJsonArray); } messageJson.add("mpnews", newsJsonObject); break; } case TASKCARD: { JsonObject text = new JsonObject(); text.addProperty("title", this.getTitle()); text.addProperty("description", this.getDescription()); if (StringUtils.isNotBlank(this.getUrl())) { text.addProperty("url", this.getUrl()); } text.addProperty("task_id", this.getTaskId()); JsonArray buttonJsonArray = new JsonArray(); for (TaskCardButton button : this.getTaskButtons()) { btn2Json(buttonJsonArray, button); } text.add("btn", buttonJsonArray); messageJson.add("taskcard", text); break; } case MINIPROGRAM_NOTICE: { JsonObject notice = new JsonObject(); notice.addProperty("appid", this.getAppId()); notice.addProperty("page", this.getPage()); notice.addProperty("description", this.getDescription()); notice.addProperty("title", this.getTitle()); notice.addProperty("emphasis_first_item", this.getEmphasisFirstItem()); JsonArray content = new JsonArray(); for (Map.Entry<String, String> item : this.getContentItems().entrySet()) { JsonObject articleJson = new JsonObject(); articleJson.addProperty("key", item.getKey()); articleJson.addProperty("value", item.getValue()); content.add(articleJson); } notice.add("content_item", content); messageJson.add("miniprogram_notice", notice); break; } case TEMPLATE_CARD: { JsonObject template = new JsonObject(); template.addProperty("card_type", this.getCardType()); if (StringUtils.isNotBlank(this.getSourceIconUrl()) || StringUtils.isNotBlank(this.getSourceDesc())) { JsonObject source = new JsonObject(); if (StringUtils.isNotBlank(this.getSourceIconUrl())) { source.addProperty("icon_url", this.getSourceIconUrl()); } if (StringUtils.isNotBlank(this.getSourceDesc())) { source.addProperty("desc", this.getSourceDesc()); } source.addProperty("desc_color", this.getSourceDescColor()); template.add("source", source); } if (StringUtils.isNotBlank(this.getActionMenuDesc())) { JsonObject action_menu = new JsonObject(); action_menu.addProperty("desc", this.getActionMenuDesc()); JsonArray actionList = new JsonArray(); List<ActionMenuItem> actionMenuItemList = this.getActionMenuActionList(); for (ActionMenuItem actionItemI : actionMenuItemList) { actionList.add(actionItemI.toJson()); } action_menu.add("action_list", actionList); template.add("action_menu", action_menu); } if (StringUtils.isNotBlank(this.getMainTitleTitle()) || StringUtils.isNotBlank(this.getMainTitleDesc())) { JsonObject mainTitle = new JsonObject(); if (StringUtils.isNotBlank(this.getMainTitleTitle())) { mainTitle.addProperty("title", this.getMainTitleTitle()); } if (StringUtils.isNotBlank(this.getMainTitleDesc())) { mainTitle.addProperty("desc", this.getMainTitleDesc()); } template.add("main_title", mainTitle); } if (this.getImageTextArea() != null) { template.add("image_text_area", this.getImageTextArea().toJson()); } if (StringUtils.isNotBlank(this.getCardImageUrl()) || this.getCardImageAspectRatio() != null) { JsonObject cardImage = new JsonObject(); if (StringUtils.isNotBlank(this.getCardImageUrl())) { cardImage.addProperty("url", this.getCardImageUrl()); } if (null != this.getCardImageAspectRatio()) { cardImage.addProperty("aspect_ratio", this.getCardImageAspectRatio()); } template.add("card_image", cardImage); } if (StringUtils.isNotBlank(this.getEmphasisContentTitle()) || StringUtils.isNotBlank(this.getEmphasisContentDesc())) { JsonObject emphasisContent = new JsonObject(); if (StringUtils.isNotBlank(this.getEmphasisContentTitle())) { emphasisContent.addProperty("title", this.getEmphasisContentTitle()); } if (StringUtils.isNotBlank(this.getEmphasisContentDesc())) { emphasisContent.addProperty("desc", this.getEmphasisContentDesc()); } template.add("emphasis_content", emphasisContent); } if (StringUtils.isNotBlank(this.getSubTitleText())) { template.addProperty("sub_title_text", this.getSubTitleText()); } if (StringUtils.isNotBlank(this.getTaskId())) { template.addProperty("task_id", this.getTaskId()); } List<VerticalContent> verticalContents = this.getVerticalContents(); if (null != verticalContents && !verticalContents.isEmpty()) { JsonArray vContentJsonArray = new JsonArray(); for (VerticalContent vContent : this.getVerticalContents()) { JsonObject tempObject = vContent.toJson(); vContentJsonArray.add(tempObject); } template.add("vertical_content_list", vContentJsonArray); } List<HorizontalContent> horizontalContents = this.getHorizontalContents(); if (null != horizontalContents && !horizontalContents.isEmpty()) { JsonArray hContentJsonArray = new JsonArray(); for (HorizontalContent hContent : this.getHorizontalContents()) { JsonObject tempObject = hContent.toJson(); hContentJsonArray.add(tempObject); } template.add("horizontal_content_list", hContentJsonArray); } List<TemplateCardJump> jumps = this.getJumps(); if (null != jumps && !jumps.isEmpty()) { JsonArray jumpJsonArray = new JsonArray(); for (TemplateCardJump jump : this.getJumps()) { JsonObject tempObject = jump.toJson(); jumpJsonArray.add(tempObject); } template.add("jump_list", jumpJsonArray); } if (null != this.getCardActionType()) { JsonObject cardAction = new JsonObject(); cardAction.addProperty("type", this.getCardActionType()); if (StringUtils.isNotBlank(this.getCardActionUrl())) { cardAction.addProperty("url", this.getCardActionUrl()); } if (StringUtils.isNotBlank(this.getCardActionAppid())) { cardAction.addProperty("appid", this.getCardActionAppid()); } if (StringUtils.isNotBlank(this.getCardActionPagepath())) { cardAction.addProperty("pagepath", this.getCardActionPagepath()); } template.add("card_action", cardAction); } TemplateCardButtonSelection buttonSelection = this.getButtonSelection(); if (null != buttonSelection) { template.add("button_selection", buttonSelection.toJson()); } List<TemplateCardButton> buttons = this.getButtons(); if (null != buttons && !buttons.isEmpty()) { JsonArray btnJsonArray = new JsonArray(); for (TemplateCardButton btn : this.getButtons()) { JsonObject tempObject = btn.toJson(); btnJsonArray.add(tempObject); } template.add("button_list", btnJsonArray); } // checkbox if (StringUtils.isNotBlank(this.getCheckboxQuestionKey())) { JsonObject checkBox = new JsonObject(); checkBox.addProperty("question_key", this.getCheckboxQuestionKey()); if (null != this.getCheckboxMode()) { checkBox.addProperty("mode", this.getCheckboxMode()); } JsonArray optionArray = new JsonArray(); for (CheckboxOption option : this.getOptions()) { JsonObject tempObject = option.toJson(); optionArray.add(tempObject); } checkBox.add("option_list", optionArray); template.add("checkbox", checkBox); } // submit_button if (StringUtils.isNotBlank(this.getSubmitButtonText()) || StringUtils.isNotBlank(this.getSubmitButtonKey())) { JsonObject submit_button = new JsonObject(); if (StringUtils.isNotBlank(this.getSubmitButtonText())) { submit_button.addProperty("text", this.getSubmitButtonText()); } if (StringUtils.isNotBlank(this.getSubmitButtonKey())) { submit_button.addProperty("key", this.getSubmitButtonKey()); } template.add("submit_button", submit_button); } // select_list List<MultipleSelect> selects = this.getSelects(); if (null != selects && !selects.isEmpty()) { JsonArray selectJsonArray = new JsonArray(); for (MultipleSelect select : this.getSelects()) { JsonObject tempObject = select.toJson(); selectJsonArray.add(tempObject); } template.add("select_list", selectJsonArray); } QuoteArea quoteArea = this.getQuoteArea(); if (null != quoteArea) { JsonObject quoteAreaJson = quoteArea.toJson(); template.add("quote_area", quoteAreaJson); } messageJson.add("template_card", template); break; } default: { // do nothing } } } private void btn2Json(JsonArray buttonJsonArray, TaskCardButton button) { JsonObject buttonJson = new JsonObject(); buttonJson.addProperty("key", button.getKey()); buttonJson.addProperty("name", button.getName()); if (StringUtils.isNotBlank(button.getReplaceName())) { buttonJson.addProperty("replace_name", button.getReplaceName()); } if (StringUtils.isNotBlank(button.getColor())) { buttonJson.addProperty("color", button.getColor()); } if (button.getBold() != null) { buttonJson.addProperty("is_bold", button.getBold()); } buttonJsonArray.add(buttonJson); } private void article2Json(JsonArray articleJsonArray, MpnewsArticle article) { JsonObject articleJson = new JsonObject(); articleJson.addProperty("title", article.getTitle()); articleJson.addProperty("thumb_media_id", article.getThumbMediaId()); articleJson.addProperty("author", article.getAuthor()); articleJson.addProperty("content_source_url", article.getContentSourceUrl()); articleJson.addProperty("content", article.getContent()); articleJson.addProperty("digest", article.getDigest()); articleJson.addProperty("show_cover_pic", article.getShowCoverPic()); articleJsonArray.add(articleJson); } }
Wechat-Group/WxJava
weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/message/WxCpMessage.java
41,660
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.stream; import static io.netty.util.internal.ObjectUtil.checkPositive; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.channel.ChannelProgressivePromise; import io.netty.channel.ChannelPromise; import io.netty.util.ReferenceCountUtil; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.nio.channels.ClosedChannelException; import java.util.ArrayDeque; import java.util.Queue; /** * A {@link ChannelHandler} that adds support for writing a large data stream * asynchronously neither spending a lot of memory nor getting * {@link OutOfMemoryError}. Large data streaming such as file * transfer requires complicated state management in a {@link ChannelHandler} * implementation. {@link ChunkedWriteHandler} manages such complicated states * so that you can send a large data stream without difficulties. * <p> * To use {@link ChunkedWriteHandler} in your application, you have to insert * a new {@link ChunkedWriteHandler} instance: * <pre> * {@link ChannelPipeline} p = ...; * p.addLast("streamer", <b>new {@link ChunkedWriteHandler}()</b>); * p.addLast("handler", new MyHandler()); * </pre> * Once inserted, you can write a {@link ChunkedInput} so that the * {@link ChunkedWriteHandler} can pick it up and fetch the content of the * stream chunk by chunk and write the fetched chunk downstream: * <pre> * {@link Channel} ch = ...; * ch.write(new {@link ChunkedFile}(new File("video.mkv")); * </pre> * * <h3>Sending a stream which generates a chunk intermittently</h3> * * Some {@link ChunkedInput} generates a chunk on a certain event or timing. * Such {@link ChunkedInput} implementation often returns {@code null} on * {@link ChunkedInput#readChunk(ChannelHandlerContext)}, resulting in the indefinitely suspended * transfer. To resume the transfer when a new chunk is available, you have to * call {@link #resumeTransfer()}. */ public class ChunkedWriteHandler extends ChannelDuplexHandler { private static final InternalLogger logger = InternalLoggerFactory.getInstance(ChunkedWriteHandler.class); private Queue<PendingWrite> queue; private volatile ChannelHandlerContext ctx; public ChunkedWriteHandler() { } /** * @deprecated use {@link #ChunkedWriteHandler()} */ @Deprecated public ChunkedWriteHandler(int maxPendingWrites) { checkPositive(maxPendingWrites, "maxPendingWrites"); } private void allocateQueue() { if (queue == null) { queue = new ArrayDeque<PendingWrite>(); } } private boolean queueIsEmpty() { return queue == null || queue.isEmpty(); } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { this.ctx = ctx; } /** * Continues to fetch the chunks from the input. */ public void resumeTransfer() { final ChannelHandlerContext ctx = this.ctx; if (ctx == null) { return; } if (ctx.executor().inEventLoop()) { resumeTransfer0(ctx); } else { // let the transfer resume on the next event loop round ctx.executor().execute(new Runnable() { @Override public void run() { resumeTransfer0(ctx); } }); } } private void resumeTransfer0(ChannelHandlerContext ctx) { try { doFlush(ctx); } catch (Exception e) { logger.warn("Unexpected exception while sending chunks.", e); } } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (!queueIsEmpty() || msg instanceof ChunkedInput) { allocateQueue(); queue.add(new PendingWrite(msg, promise)); } else { ctx.write(msg, promise); } } @Override public void flush(ChannelHandlerContext ctx) throws Exception { doFlush(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { doFlush(ctx); ctx.fireChannelInactive(); } @Override public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { if (ctx.channel().isWritable()) { // channel is writable again try to continue flushing doFlush(ctx); } ctx.fireChannelWritabilityChanged(); } private void discard(Throwable cause) { if (queueIsEmpty()) { return; } for (;;) { PendingWrite currentWrite = queue.poll(); if (currentWrite == null) { break; } Object message = currentWrite.msg; if (message instanceof ChunkedInput) { ChunkedInput<?> in = (ChunkedInput<?>) message; boolean endOfInput; long inputLength; try { endOfInput = in.isEndOfInput(); inputLength = in.length(); closeInput(in); } catch (Exception e) { closeInput(in); currentWrite.fail(e); logger.warn("ChunkedInput failed", e); continue; } if (!endOfInput) { if (cause == null) { cause = new ClosedChannelException(); } currentWrite.fail(cause); } else { currentWrite.success(inputLength); } } else { if (cause == null) { cause = new ClosedChannelException(); } currentWrite.fail(cause); } } } private void doFlush(final ChannelHandlerContext ctx) { final Channel channel = ctx.channel(); if (!channel.isActive()) { discard(null); return; } if (queueIsEmpty()) { ctx.flush(); return; } boolean requiresFlush = true; ByteBufAllocator allocator = ctx.alloc(); while (channel.isWritable()) { final PendingWrite currentWrite = queue.peek(); if (currentWrite == null) { break; } if (currentWrite.promise.isDone()) { // This might happen e.g. in the case when a write operation // failed, but there are still unconsumed chunks left. // Most chunked input sources would stop generating chunks // and report end of input, but this doesn't work with any // source wrapped in HttpChunkedInput. // Note, that we're not trying to release the message/chunks // as this had to be done already by someone who resolved the // promise (using ChunkedInput.close method). // See https://github.com/netty/netty/issues/8700. queue.remove(); continue; } final Object pendingMessage = currentWrite.msg; if (pendingMessage instanceof ChunkedInput) { final ChunkedInput<?> chunks = (ChunkedInput<?>) pendingMessage; boolean endOfInput; boolean suspend; Object message = null; try { message = chunks.readChunk(allocator); endOfInput = chunks.isEndOfInput(); // No need to suspend when reached at the end. suspend = message == null && !endOfInput; } catch (final Throwable t) { queue.remove(); if (message != null) { ReferenceCountUtil.release(message); } closeInput(chunks); currentWrite.fail(t); break; } if (suspend) { // ChunkedInput.nextChunk() returned null and it has // not reached at the end of input. Let's wait until // more chunks arrive. Nothing to write or notify. break; } if (message == null) { // If message is null write an empty ByteBuf. // See https://github.com/netty/netty/issues/1671 message = Unpooled.EMPTY_BUFFER; } if (endOfInput) { // We need to remove the element from the queue before we call writeAndFlush() as this operation // may cause an action that also touches the queue. queue.remove(); } // Flush each chunk to conserve memory ChannelFuture f = ctx.writeAndFlush(message); if (endOfInput) { if (f.isDone()) { handleEndOfInputFuture(f, chunks, currentWrite); } else { // Register a listener which will close the input once the write is complete. // This is needed because the Chunk may have some resource bound that can not // be closed before it's not written. // // See https://github.com/netty/netty/issues/303 f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { handleEndOfInputFuture(future, chunks, currentWrite); } }); } } else { final boolean resume = !channel.isWritable(); if (f.isDone()) { handleFuture(f, chunks, currentWrite, resume); } else { f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { handleFuture(future, chunks, currentWrite, resume); } }); } } requiresFlush = false; } else { queue.remove(); ctx.write(pendingMessage, currentWrite.promise); requiresFlush = true; } if (!channel.isActive()) { discard(new ClosedChannelException()); break; } } if (requiresFlush) { ctx.flush(); } } private static void handleEndOfInputFuture(ChannelFuture future, ChunkedInput<?> input, PendingWrite currentWrite) { if (!future.isSuccess()) { closeInput(input); currentWrite.fail(future.cause()); } else { // read state of the input in local variables before closing it long inputProgress = input.progress(); long inputLength = input.length(); closeInput(input); currentWrite.progress(inputProgress, inputLength); currentWrite.success(inputLength); } } private void handleFuture(ChannelFuture future, ChunkedInput<?> input, PendingWrite currentWrite, boolean resume) { if (!future.isSuccess()) { closeInput(input); currentWrite.fail(future.cause()); } else { currentWrite.progress(input.progress(), input.length()); if (resume && future.channel().isWritable()) { resumeTransfer(); } } } private static void closeInput(ChunkedInput<?> chunks) { try { chunks.close(); } catch (Throwable t) { logger.warn("Failed to close a ChunkedInput.", t); } } private static final class PendingWrite { final Object msg; final ChannelPromise promise; PendingWrite(Object msg, ChannelPromise promise) { this.msg = msg; this.promise = promise; } void fail(Throwable cause) { ReferenceCountUtil.release(msg); promise.tryFailure(cause); } void success(long total) { if (promise.isDone()) { // No need to notify the progress or fulfill the promise because it's done already. return; } progress(total, total); promise.trySuccess(); } void progress(long progress, long total) { if (promise instanceof ChannelProgressivePromise) { ((ChannelProgressivePromise) promise).tryProgress(progress, total); } } } }
netty/netty
handler/src/main/java/io/netty/handler/stream/ChunkedWriteHandler.java
41,661
package com.bumptech.glide; import static com.bumptech.glide.testutil.BitmapSubject.assertThat; import static org.junit.Assume.assumeTrue; import android.content.Context; import android.graphics.Bitmap; import android.os.Build; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; import com.bumptech.glide.load.resource.bitmap.DownsampleStrategy; import com.bumptech.glide.request.target.Target; import com.bumptech.glide.test.GlideApp; import com.bumptech.glide.test.ResourceIds; import com.bumptech.glide.testutil.ConcurrencyHelper; import com.bumptech.glide.testutil.TearDownGlide; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) public class DownsampleVideoTest { // The dimensions of the test video. private static final int WIDTH = 1080; private static final int HEIGHT = 1920; @Rule public final TearDownGlide tearDownGlide = new TearDownGlide(); private final ConcurrencyHelper concurrency = new ConcurrencyHelper(); private final Context context = ApplicationProvider.getApplicationContext(); @Before public void setUp() { assumeTrue(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1); } @Test public void loadVideo_downsampleStrategyNone_returnsOriginalVideoDimensions() { Bitmap bitmap = concurrency.get( GlideApp.with(context) .asBitmap() .load(ResourceIds.raw.video) .downsample(DownsampleStrategy.NONE) .submit(10, 10)); assertThat(bitmap).hasDimensions(WIDTH, HEIGHT); } @Test public void loadVideo_downsampleStrategyNone_doesNotUpscale() { Bitmap bitmap = concurrency.get( GlideApp.with(context) .asBitmap() .load(ResourceIds.raw.video) .downsample(DownsampleStrategy.NONE) .submit(WIDTH * 2, HEIGHT * 2)); assertThat(bitmap).hasDimensions(WIDTH, HEIGHT); } @Test public void loadVideo_downsampleDefault_downsamplesVideo() { Bitmap bitmap = concurrency.get( GlideApp.with(context).asBitmap().load(ResourceIds.raw.video).submit(10, 10)); assertThat(bitmap).hasDimensions(10, 18); } @Test public void loadVideo_downsampleAtMost_downsamplesToSmallerSize() { Bitmap bitmap = concurrency.get( GlideApp.with(context) .asBitmap() .downsample(DownsampleStrategy.AT_MOST) .load(ResourceIds.raw.video) .submit(540, 959)); assertThat(bitmap).hasDimensions(270, 480); } @Test public void loadVideo_downsampleAtMost_doesNotUpscale() { Bitmap bitmap = concurrency.get( GlideApp.with(context) .asBitmap() .downsample(DownsampleStrategy.AT_MOST) .load(ResourceIds.raw.video) .submit(WIDTH * 2, HEIGHT * 2)); assertThat(bitmap).hasDimensions(WIDTH, HEIGHT); } @Test public void loadVideo_downsampleAtLeast_downsamplesToLargerSize() { Bitmap bitmap = concurrency.get( GlideApp.with(context) .asBitmap() .downsample(DownsampleStrategy.AT_LEAST) .load(ResourceIds.raw.video) .submit(270, 481)); assertThat(bitmap).hasDimensions(540, 960); } @Test public void loadVideo_downsampleAtLeast_doesNotUpscale() { Bitmap bitmap = concurrency.get( GlideApp.with(context) .asBitmap() .downsample(DownsampleStrategy.AT_LEAST) .load(ResourceIds.raw.video) .submit(WIDTH * 2, HEIGHT * 2)); assertThat(bitmap).hasDimensions(WIDTH, HEIGHT); } @Test public void loadVideo_downsampleCenterInside_downsamplesWithinBox() { Bitmap bitmap = concurrency.get( GlideApp.with(context) .asBitmap() .downsample(DownsampleStrategy.CENTER_INSIDE) .load(ResourceIds.raw.video) .submit(270, 481)); assertThat(bitmap).hasDimensions(270, 480); } @Test public void loadVideo_downsampleCenterInside_doesNotUpscale() { Bitmap bitmap = concurrency.get( GlideApp.with(context) .asBitmap() .downsample(DownsampleStrategy.CENTER_INSIDE) .load(ResourceIds.raw.video) .submit(WIDTH * 2, HEIGHT * 2)); assertThat(bitmap).hasDimensions(WIDTH, HEIGHT); } @Test public void loadVideo_downsampleCenterOutside_downsamplesOutsideBox() { Bitmap bitmap = concurrency.get( GlideApp.with(context) .asBitmap() .downsample(DownsampleStrategy.CENTER_OUTSIDE) .load(ResourceIds.raw.video) .submit(270, 481)); assertThat(bitmap).hasDimensions(271, 481); } @Test public void loadVideo_downsampleCenterOutside_upsacles() { Bitmap bitmap = concurrency.get( GlideApp.with(context) .asBitmap() .downsample(DownsampleStrategy.CENTER_OUTSIDE) .load(ResourceIds.raw.video) .submit(WIDTH * 2, HEIGHT * 2)); assertThat(bitmap).hasDimensions(WIDTH * 2, HEIGHT * 2); } @Test public void loadVideo_downsampleFitCenter_downsamplesInsideBox() { Bitmap bitmap = concurrency.get( GlideApp.with(context) .asBitmap() .downsample(DownsampleStrategy.FIT_CENTER) .load(ResourceIds.raw.video) .submit(270, 481)); assertThat(bitmap).hasDimensions(270, 480); } @Test public void loadVideo_downsampleFitCenter_upscales() { Bitmap bitmap = concurrency.get( GlideApp.with(context) .asBitmap() .downsample(DownsampleStrategy.FIT_CENTER) .load(ResourceIds.raw.video) .submit(WIDTH * 2, HEIGHT * 2)); assertThat(bitmap).hasDimensions(WIDTH * 2, HEIGHT * 2); } @Test public void loadVideo_withSizeOriginal_ignoresDownsampleStrategy() { Bitmap bitmap = concurrency.get( GlideApp.with(context) .asBitmap() .downsample(DownsampleStrategy.AT_MOST) .load(ResourceIds.raw.video) .submit(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)); assertThat(bitmap).hasDimensions(WIDTH, HEIGHT); } }
bumptech/glide
instrumentation/src/androidTest/java/com/bumptech/glide/DownsampleVideoTest.java
41,662
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.messenger; import android.text.TextUtils; import android.util.SparseArray; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import org.telegram.ui.LaunchActivity; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.regex.Matcher; import java.util.regex.Pattern; public class FileLoader extends BaseController { private static final int PRIORITY_STREAM = 4; public static final int PRIORITY_HIGH = 3; public static final int PRIORITY_NORMAL_UP = 2; public static final int PRIORITY_NORMAL = 1; public static final int PRIORITY_LOW = 0; private int priorityIncreasePointer; private static Pattern sentPattern; public static FilePathDatabase.FileMeta getFileMetadataFromParent(int currentAccount, Object parentObject) { if (parentObject instanceof String) { String str = (String) parentObject; if (str.startsWith("sent_")) { if (sentPattern == null) { sentPattern = Pattern.compile("sent_.*_([0-9]+)_([0-9]+)_([0-9]+)_([0-9]+)"); } try { Matcher matcher = sentPattern.matcher(str); if (matcher.matches()) { FilePathDatabase.FileMeta fileMeta = new FilePathDatabase.FileMeta(); fileMeta.messageId = Integer.parseInt(matcher.group(1)); fileMeta.dialogId = Long.parseLong(matcher.group(2)); fileMeta.messageType = Integer.parseInt(matcher.group(3)); fileMeta.messageSize = Long.parseLong(matcher.group(4)); return fileMeta; } } catch (Exception e) { FileLog.e(e); } } } else if (parentObject instanceof MessageObject) { MessageObject messageObject = (MessageObject) parentObject; FilePathDatabase.FileMeta fileMeta = new FilePathDatabase.FileMeta(); fileMeta.messageId = messageObject.getId(); fileMeta.dialogId = messageObject.getDialogId(); fileMeta.messageType = messageObject.type; fileMeta.messageSize = messageObject.getSize(); return fileMeta; } else if (parentObject instanceof TLRPC.StoryItem) { TLRPC.StoryItem storyItem = (TLRPC.StoryItem) parentObject; FilePathDatabase.FileMeta fileMeta = new FilePathDatabase.FileMeta(); fileMeta.dialogId = storyItem.dialogId; fileMeta.messageType = MessageObject.TYPE_STORY; return fileMeta; } return null; } public static TLRPC.VideoSize getVectorMarkupVideoSize(TLRPC.Photo photo) { if (photo == null || photo.video_sizes == null) { return null; } for (int i = 0; i < photo.video_sizes.size(); i++) { TLRPC.VideoSize videoSize = photo.video_sizes.get(i); if (videoSize instanceof TLRPC.TL_videoSizeEmojiMarkup || videoSize instanceof TLRPC.TL_videoSizeStickerMarkup) { return videoSize; } } return null; } public static TLRPC.VideoSize getEmojiMarkup(ArrayList<TLRPC.VideoSize> video_sizes) { for (int i = 0; i < video_sizes.size(); i++) { if (video_sizes.get(i) instanceof TLRPC.TL_videoSizeEmojiMarkup || video_sizes.get(i) instanceof TLRPC.TL_videoSizeStickerMarkup) { return video_sizes.get(i); } } return null; } private int getPriorityValue(int priorityType) { if (priorityType == PRIORITY_STREAM) { return Integer.MAX_VALUE; } else if (priorityType == PRIORITY_HIGH) { priorityIncreasePointer++; return FileLoaderPriorityQueue.PRIORITY_VALUE_MAX + priorityIncreasePointer; } else if (priorityType == PRIORITY_NORMAL_UP) { priorityIncreasePointer++; return FileLoaderPriorityQueue.PRIORITY_VALUE_NORMAL + priorityIncreasePointer; } else if (priorityType == PRIORITY_NORMAL) { return FileLoaderPriorityQueue.PRIORITY_VALUE_NORMAL; } else { return 0; } } public DispatchQueue getFileLoaderQueue() { return fileLoaderQueue; } public void setLocalPathTo(TLObject attach, String attachPath) { long documentId = 0; int dcId = 0; int type = 0; if (attach instanceof TLRPC.Document) { TLRPC.Document document = (TLRPC.Document) attach; if (document.key != null) { type = MEDIA_DIR_CACHE; } else { if (MessageObject.isVoiceDocument(document)) { type = MEDIA_DIR_AUDIO; } else if (MessageObject.isVideoDocument(document)) { type = MEDIA_DIR_VIDEO; } else { type = MEDIA_DIR_DOCUMENT; } } documentId = document.id; dcId = document.dc_id; filePathDatabase.putPath(documentId, dcId, type, FilePathDatabase.FLAG_LOCALLY_CREATED, attachPath); } else if (attach instanceof TLRPC.PhotoSize) { TLRPC.PhotoSize photoSize = (TLRPC.PhotoSize) attach; if (photoSize instanceof TLRPC.TL_photoStrippedSize || photoSize instanceof TLRPC.TL_photoPathSize) { return; } else if (photoSize.location == null || photoSize.location.key != null || photoSize.location.volume_id == Integer.MIN_VALUE && photoSize.location.local_id < 0 || photoSize.size < 0) { type = MEDIA_DIR_CACHE; } else { type = MEDIA_DIR_IMAGE; } documentId = photoSize.location.volume_id; dcId = photoSize.location.dc_id + (photoSize.location.local_id << 16); filePathDatabase.putPath(documentId, dcId, type, FilePathDatabase.FLAG_LOCALLY_CREATED, attachPath); } } public interface FileLoaderDelegate { void fileUploadProgressChanged(FileUploadOperation operation, String location, long uploadedSize, long totalSize, boolean isEncrypted); void fileDidUploaded(String location, TLRPC.InputFile inputFile, TLRPC.InputEncryptedFile inputEncryptedFile, byte[] key, byte[] iv, long totalFileSize); void fileDidFailedUpload(String location, boolean isEncrypted); void fileDidLoaded(String location, File finalFile, Object parentObject, int type); void fileDidFailedLoad(String location, int state); void fileLoadProgressChanged(FileLoadOperation operation, String location, long uploadedSize, long totalSize); } public static final int MEDIA_DIR_IMAGE = 0; public static final int MEDIA_DIR_AUDIO = 1; public static final int MEDIA_DIR_VIDEO = 2; public static final int MEDIA_DIR_DOCUMENT = 3; public static final int MEDIA_DIR_CACHE = 4; public static final int MEDIA_DIR_FILES = 5; public static final int MEDIA_DIR_STORIES = 6; public static final int MEDIA_DIR_IMAGE_PUBLIC = 100; public static final int MEDIA_DIR_VIDEO_PUBLIC = 101; public static final int IMAGE_TYPE_LOTTIE = 1; public static final int IMAGE_TYPE_ANIMATION = 2; public static final int IMAGE_TYPE_SVG = 3; public static final int IMAGE_TYPE_SVG_WHITE = 4; public static final int IMAGE_TYPE_THEME_PREVIEW = 5; // private final FileLoaderPriorityQueue largeFilesQueue = new FileLoaderPriorityQueue("large files queue", 2); // private final FileLoaderPriorityQueue filesQueue = new FileLoaderPriorityQueue("files queue", 3); // private final FileLoaderPriorityQueue imagesQueue = new FileLoaderPriorityQueue("imagesQueue queue", 6); // private final FileLoaderPriorityQueue audioQueue = new FileLoaderPriorityQueue("audioQueue queue", 3); private final FileLoaderPriorityQueue[] smallFilesQueue = new FileLoaderPriorityQueue[5]; private final FileLoaderPriorityQueue[] largeFilesQueue = new FileLoaderPriorityQueue[5]; public final static long DEFAULT_MAX_FILE_SIZE = 1024L * 1024L * 2000L; public final static long DEFAULT_MAX_FILE_SIZE_PREMIUM = DEFAULT_MAX_FILE_SIZE * 2L; public final static int PRELOAD_CACHE_TYPE = 11; private volatile static DispatchQueue fileLoaderQueue = new DispatchQueue("fileUploadQueue"); private final FilePathDatabase filePathDatabase; private final LinkedList<FileUploadOperation> uploadOperationQueue = new LinkedList<>(); private final LinkedList<FileUploadOperation> uploadSmallOperationQueue = new LinkedList<>(); private final ConcurrentHashMap<String, FileUploadOperation> uploadOperationPaths = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, FileUploadOperation> uploadOperationPathsEnc = new ConcurrentHashMap<>(); private int currentUploadOperationsCount = 0; private int currentUploadSmallOperationsCount = 0; private final ConcurrentHashMap<String, FileLoadOperation> loadOperationPaths = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, LoadOperationUIObject> loadOperationPathsUI = new ConcurrentHashMap<>(10, 1, 2); private HashMap<String, Long> uploadSizes = new HashMap<>(); private HashMap<String, Boolean> loadingVideos = new HashMap<>(); private String forceLoadingFile; private static SparseArray<File> mediaDirs = null; private FileLoaderDelegate delegate = null; private int lastReferenceId; private ConcurrentHashMap<Integer, Object> parentObjectReferences = new ConcurrentHashMap<>(); private static final FileLoader[] Instance = new FileLoader[UserConfig.MAX_ACCOUNT_COUNT]; public static FileLoader getInstance(int num) { FileLoader localInstance = Instance[num]; if (localInstance == null) { synchronized (FileLoader.class) { localInstance = Instance[num]; if (localInstance == null) { Instance[num] = localInstance = new FileLoader(num); } } } return localInstance; } public FileLoader(int instance) { super(instance); filePathDatabase = new FilePathDatabase(instance); for (int i = 0; i < smallFilesQueue.length; i++) { smallFilesQueue[i] = new FileLoaderPriorityQueue(instance, "smallFilesQueue dc" + (i + 1), FileLoaderPriorityQueue.TYPE_SMALL, fileLoaderQueue); largeFilesQueue[i] = new FileLoaderPriorityQueue(instance, "largeFilesQueue dc" + (i + 1), FileLoaderPriorityQueue.TYPE_LARGE, fileLoaderQueue); } dumpFilesQueue(); } public static void setMediaDirs(SparseArray<File> dirs) { mediaDirs = dirs; } public static File checkDirectory(int type) { return mediaDirs.get(type); } public static File getDirectory(int type) { File dir = mediaDirs.get(type); if (dir == null && type != FileLoader.MEDIA_DIR_CACHE) { dir = mediaDirs.get(FileLoader.MEDIA_DIR_CACHE); } if (BuildVars.NO_SCOPED_STORAGE) { try { if (dir != null && !dir.isDirectory()) { dir.mkdirs(); } } catch (Exception e) { //don't prompt } } return dir; } public int getFileReference(Object parentObject) { int reference = lastReferenceId++; parentObjectReferences.put(reference, parentObject); return reference; } public Object getParentObject(int reference) { return parentObjectReferences.get(reference); } public void setLoadingVideoInternal(TLRPC.Document document, boolean player) { String key = getAttachFileName(document); String dKey = key + (player ? "p" : ""); loadingVideos.put(dKey, true); getNotificationCenter().postNotificationName(NotificationCenter.videoLoadingStateChanged, key); } public void setLoadingVideo(TLRPC.Document document, boolean player, boolean schedule) { if (document == null) { return; } if (schedule) { AndroidUtilities.runOnUIThread(() -> setLoadingVideoInternal(document, player)); } else { setLoadingVideoInternal(document, player); } } public void setLoadingVideoForPlayer(TLRPC.Document document, boolean player) { if (document == null) { return; } String key = getAttachFileName(document); if (loadingVideos.containsKey(key + (player ? "" : "p"))) { loadingVideos.put(key + (player ? "p" : ""), true); } } private void removeLoadingVideoInternal(TLRPC.Document document, boolean player) { String key = getAttachFileName(document); String dKey = key + (player ? "p" : ""); if (loadingVideos.remove(dKey) != null) { getNotificationCenter().postNotificationName(NotificationCenter.videoLoadingStateChanged, key); } } public void removeLoadingVideo(TLRPC.Document document, boolean player, boolean schedule) { if (document == null) { return; } if (schedule) { AndroidUtilities.runOnUIThread(() -> removeLoadingVideoInternal(document, player)); } else { removeLoadingVideoInternal(document, player); } } public boolean isLoadingVideo(TLRPC.Document document, boolean player) { return document != null && loadingVideos.containsKey(getAttachFileName(document) + (player ? "p" : "")); } public boolean isLoadingVideoAny(TLRPC.Document document) { return isLoadingVideo(document, false) || isLoadingVideo(document, true); } public void cancelFileUpload(final String location, final boolean enc) { if (location == null) { return; } fileLoaderQueue.postRunnable(() -> { FileUploadOperation operation; if (!enc) { operation = uploadOperationPaths.get(location); } else { operation = uploadOperationPathsEnc.get(location); } uploadSizes.remove(location); if (operation != null) { uploadOperationPathsEnc.remove(location); uploadOperationQueue.remove(operation); uploadSmallOperationQueue.remove(operation); operation.cancel(); } }); } public void checkUploadNewDataAvailable(final String location, final boolean encrypted, final long newAvailableSize, final long finalSize) { checkUploadNewDataAvailable(location, encrypted, newAvailableSize, finalSize, null); } public void checkUploadNewDataAvailable(final String location, final boolean encrypted, final long newAvailableSize, final long finalSize, final Float progress) { fileLoaderQueue.postRunnable(() -> { FileUploadOperation operation; if (encrypted) { operation = uploadOperationPathsEnc.get(location); } else { operation = uploadOperationPaths.get(location); } if (operation != null) { operation.checkNewDataAvailable(newAvailableSize, finalSize, progress); } else if (finalSize != 0) { uploadSizes.put(location, finalSize); } }); } public void onNetworkChanged(final boolean slow) { fileLoaderQueue.postRunnable(() -> { for (ConcurrentHashMap.Entry<String, FileUploadOperation> entry : uploadOperationPaths.entrySet()) { entry.getValue().onNetworkChanged(slow); } for (ConcurrentHashMap.Entry<String, FileUploadOperation> entry : uploadOperationPathsEnc.entrySet()) { entry.getValue().onNetworkChanged(slow); } }); } public void uploadFile(final String location, final boolean encrypted, final boolean small, final int type) { uploadFile(location, encrypted, small, 0, type, false); } public void uploadFile(final String location, final boolean encrypted, final boolean small, final long estimatedSize, final int type, boolean forceSmallFile) { if (location == null) { return; } fileLoaderQueue.postRunnable(() -> { if (encrypted) { if (uploadOperationPathsEnc.containsKey(location)) { return; } } else { if (uploadOperationPaths.containsKey(location)) { return; } } long esimated = estimatedSize; if (esimated != 0) { Long finalSize = uploadSizes.get(location); if (finalSize != null) { esimated = 0; uploadSizes.remove(location); } } FileUploadOperation operation = new FileUploadOperation(currentAccount, location, encrypted, esimated, type); if (delegate != null && estimatedSize != 0) { delegate.fileUploadProgressChanged(operation, location, 0, estimatedSize, encrypted); } if (encrypted) { uploadOperationPathsEnc.put(location, operation); } else { uploadOperationPaths.put(location, operation); } if (forceSmallFile) { operation.setForceSmallFile(); } operation.setDelegate(new FileUploadOperation.FileUploadOperationDelegate() { @Override public void didFinishUploadingFile(final FileUploadOperation operation, final TLRPC.InputFile inputFile, final TLRPC.InputEncryptedFile inputEncryptedFile, final byte[] key, final byte[] iv) { fileLoaderQueue.postRunnable(() -> { if (encrypted) { uploadOperationPathsEnc.remove(location); } else { uploadOperationPaths.remove(location); } if (small) { currentUploadSmallOperationsCount--; if (currentUploadSmallOperationsCount < 1) { FileUploadOperation operation12 = uploadSmallOperationQueue.poll(); if (operation12 != null) { currentUploadSmallOperationsCount++; operation12.start(); } } } else { currentUploadOperationsCount--; if (currentUploadOperationsCount < 1) { FileUploadOperation operation12 = uploadOperationQueue.poll(); if (operation12 != null) { currentUploadOperationsCount++; operation12.start(); } } } if (delegate != null) { delegate.fileDidUploaded(location, inputFile, inputEncryptedFile, key, iv, operation.getTotalFileSize()); } }); } @Override public void didFailedUploadingFile(final FileUploadOperation operation) { fileLoaderQueue.postRunnable(() -> { if (encrypted) { uploadOperationPathsEnc.remove(location); } else { uploadOperationPaths.remove(location); } if (delegate != null) { delegate.fileDidFailedUpload(location, encrypted); } if (small) { currentUploadSmallOperationsCount--; if (currentUploadSmallOperationsCount < 1) { FileUploadOperation operation1 = uploadSmallOperationQueue.poll(); if (operation1 != null) { currentUploadSmallOperationsCount++; operation1.start(); } } } else { currentUploadOperationsCount--; if (currentUploadOperationsCount < 1) { FileUploadOperation operation1 = uploadOperationQueue.poll(); if (operation1 != null) { currentUploadOperationsCount++; operation1.start(); } } } }); } @Override public void didChangedUploadProgress(FileUploadOperation operation, long uploadedSize, long totalSize) { if (delegate != null) { delegate.fileUploadProgressChanged(operation, location, uploadedSize, totalSize, encrypted); } } }); if (small) { if (currentUploadSmallOperationsCount < 1) { currentUploadSmallOperationsCount++; operation.start(); } else { uploadSmallOperationQueue.add(operation); } } else { if (currentUploadOperationsCount < 1) { currentUploadOperationsCount++; operation.start(); } else { uploadOperationQueue.add(operation); } } }); } public void setForceStreamLoadingFile(TLRPC.FileLocation location, String ext) { if (location == null) { return; } fileLoaderQueue.postRunnable(() -> { forceLoadingFile = getAttachFileName(location, ext); FileLoadOperation operation = loadOperationPaths.get(forceLoadingFile); if (operation != null) { if (operation.isPreloadVideoOperation()) { operation.setIsPreloadVideoOperation(false); } operation.setForceRequest(true); operation.setPriority(getPriorityValue(PRIORITY_STREAM)); operation.getQueue().remove(operation); operation.getQueue().add(operation); operation.getQueue().checkLoadingOperations(); } }); } public void cancelLoadFile(TLRPC.Document document) { cancelLoadFile(document, false); } public void cancelLoadFile(TLRPC.Document document, boolean deleteFile) { cancelLoadFile(document, null, null, null, null, null, deleteFile); } public void cancelLoadFile(SecureDocument document) { cancelLoadFile(null, document, null, null, null, null, false); } public void cancelLoadFile(WebFile document) { cancelLoadFile(null, null, document, null, null, null, false); } public void cancelLoadFile(TLRPC.PhotoSize photo) { cancelLoadFile(photo, false); } public void cancelLoadFile(TLRPC.PhotoSize photo, boolean deleteFile) { cancelLoadFile(null, null, null, photo.location, null, null, deleteFile); } public void cancelLoadFile(TLRPC.FileLocation location, String ext) { cancelLoadFile(location, ext, false); } public void cancelLoadFile(TLRPC.FileLocation location, String ext, boolean deleteFile) { cancelLoadFile(null, null, null, location, ext, null, deleteFile); } public void cancelLoadFile(String fileName) { cancelLoadFile(null, null, null, null, null, fileName, true); } public void cancelLoadFiles(ArrayList<String> fileNames) { for (int a = 0, N = fileNames.size(); a < N; a++) { cancelLoadFile(null, null, null, null, null, fileNames.get(a), true); } } private void cancelLoadFile(final TLRPC.Document document, final SecureDocument secureDocument, final WebFile webDocument, final TLRPC.FileLocation location, final String locationExt, String name, boolean deleteFile) { if (location == null && document == null && webDocument == null && secureDocument == null && TextUtils.isEmpty(name)) { return; } final String fileName; if (location != null) { fileName = getAttachFileName(location, locationExt); } else if (document != null) { fileName = getAttachFileName(document); } else if (secureDocument != null) { fileName = getAttachFileName(secureDocument); } else if (webDocument != null) { fileName = getAttachFileName(webDocument); } else { fileName = name; } LoadOperationUIObject uiObject = loadOperationPathsUI.remove(fileName); Runnable runnable = uiObject != null ? uiObject.loadInternalRunnable : null; boolean removed = uiObject != null; if (runnable != null) { fileLoaderQueue.cancelRunnable(runnable); } fileLoaderQueue.postRunnable(() -> { FileLoadOperation operation = loadOperationPaths.remove(fileName); if (operation != null) { FileLoaderPriorityQueue queue = operation.getQueue(); queue.cancel(operation); } }); if (removed && document != null) { AndroidUtilities.runOnUIThread(() -> { getNotificationCenter().postNotificationName(NotificationCenter.onDownloadingFilesChanged); }); } } public void changePriority(int priority, final TLRPC.Document document, final SecureDocument secureDocument, final WebFile webDocument, final TLRPC.FileLocation location, final String locationExt, String name) { if (location == null && document == null && webDocument == null && secureDocument == null && TextUtils.isEmpty(name)) { return; } final String fileName; if (location != null) { fileName = getAttachFileName(location, locationExt); } else if (document != null) { fileName = getAttachFileName(document); } else if (secureDocument != null) { fileName = getAttachFileName(secureDocument); } else if (webDocument != null) { fileName = getAttachFileName(webDocument); } else { fileName = name; } fileLoaderQueue.postRunnable(() -> { FileLoadOperation operation = loadOperationPaths.get(fileName); if (operation != null) { int newPriority = getPriorityValue(priority); if (operation.getPriority() == newPriority) { return; } operation.setPriority(newPriority); FileLoaderPriorityQueue queue = operation.getQueue(); queue.remove(operation); queue.add(operation); queue.checkLoadingOperations(); FileLog.d("update priority " + fileName + " position in queue " + operation.getPositionInQueue() + " account=" + currentAccount); } }); } public void cancelLoadAllFiles() { for (String fileName : loadOperationPathsUI.keySet()) { LoadOperationUIObject uiObject = loadOperationPathsUI.get(fileName); Runnable runnable = uiObject != null ? uiObject.loadInternalRunnable : null; boolean removed = uiObject != null; if (runnable != null) { fileLoaderQueue.cancelRunnable(runnable); } fileLoaderQueue.postRunnable(() -> { FileLoadOperation operation = loadOperationPaths.remove(fileName); if (operation != null) { FileLoaderPriorityQueue queue = operation.getQueue(); queue.cancel(operation); } }); // if (removed && document != null) { // AndroidUtilities.runOnUIThread(() -> { // getNotificationCenter().postNotificationName(NotificationCenter.onDownloadingFilesChanged); // }); // } } } public boolean isLoadingFile(final String fileName) { return fileName != null && loadOperationPathsUI.containsKey(fileName); } public float getBufferedProgressFromPosition(final float position, final String fileName) { if (TextUtils.isEmpty(fileName)) { return 0; } FileLoadOperation loadOperation = loadOperationPaths.get(fileName); if (loadOperation != null) { return loadOperation.getDownloadedLengthFromOffset(position); } else { return 0.0f; } } public void loadFile(ImageLocation imageLocation, Object parentObject, String ext, int priority, int cacheType) { if (imageLocation == null) { return; } if (cacheType == 0 && (imageLocation.isEncrypted() || imageLocation.photoSize != null && imageLocation.getSize() == 0)) { cacheType = 1; } loadFile(imageLocation.document, imageLocation.secureDocument, imageLocation.webFile, imageLocation.location, imageLocation, parentObject, ext, imageLocation.getSize(), priority, cacheType); } public void loadFile(SecureDocument secureDocument, int priority) { if (secureDocument == null) { return; } loadFile(null, secureDocument, null, null, null, null, null, 0, priority, 1); } public void loadFile(TLRPC.Document document, Object parentObject, int priority, int cacheType) { if (document == null) { return; } if (cacheType == 0 && document.key != null) { cacheType = 1; } loadFile(document, null, null, null, null, parentObject, null, 0, priority, cacheType); } public void loadFile(WebFile document, int priority, int cacheType) { loadFile(null, null, document, null, null, null, null, 0, priority, cacheType); } private FileLoadOperation loadFileInternal(final TLRPC.Document document, final SecureDocument secureDocument, final WebFile webDocument, TLRPC.TL_fileLocationToBeDeprecated location, final ImageLocation imageLocation, Object parentObject, final String locationExt, final long locationSize, int priority, final FileLoadOperationStream stream, final long streamOffset, boolean streamPriority, final int cacheType) { String fileName; if (location != null) { fileName = getAttachFileName(location, locationExt); } else if (secureDocument != null) { fileName = getAttachFileName(secureDocument); } else if (document != null) { fileName = getAttachFileName(document); } else if (webDocument != null) { fileName = getAttachFileName(webDocument); } else { fileName = null; } if (fileName == null || fileName.contains("" + Integer.MIN_VALUE)) { return null; } if (fileName.startsWith("0_0")) { FileLog.e(new RuntimeException("cant get hash from " + document)); return null; } if (cacheType != 10 && !TextUtils.isEmpty(fileName) && !fileName.contains("" + Integer.MIN_VALUE)) { loadOperationPathsUI.put(fileName, new LoadOperationUIObject()); } if (document != null && parentObject instanceof MessageObject && ((MessageObject) parentObject).putInDownloadsStore && !((MessageObject) parentObject).isAnyKindOfSticker()) { getDownloadController().startDownloadFile(document, (MessageObject) parentObject); } final String finalFileName = fileName; FileLoadOperation operation = loadOperationPaths.get(finalFileName); priority = getPriorityValue(priority); if (operation != null) { if (cacheType != 10 && operation.isPreloadVideoOperation()) { operation.setIsPreloadVideoOperation(false); } operation.setForceRequest(priority > 0); operation.setStream(stream, streamPriority, streamOffset); boolean priorityChanged = false; if (operation.getPriority() != priority) { priorityChanged = true; operation.setPriority(priority); } operation.getQueue().add(operation); operation.updateProgress(); if (priorityChanged) { operation.getQueue().checkLoadingOperations(); } FileLog.d("load operation update position fileName=" + finalFileName + " position in queue " + operation.getPositionInQueue() + " preloadFinish " + operation.isPreloadFinished()); return operation; } File tempDir = getDirectory(MEDIA_DIR_CACHE); File storeDir = tempDir; int type = MEDIA_DIR_CACHE; long documentId = 0; int dcId = 0; if (secureDocument != null) { operation = new FileLoadOperation(secureDocument); type = MEDIA_DIR_DOCUMENT; } else if (location != null) { documentId = location.volume_id; dcId = location.dc_id + (location.local_id << 16); operation = new FileLoadOperation(imageLocation, parentObject, locationExt, locationSize); type = MEDIA_DIR_IMAGE; } else if (document != null) { operation = new FileLoadOperation(document, parentObject); if (MessageObject.isVoiceDocument(document)) { type = MEDIA_DIR_AUDIO; } else if (MessageObject.isVideoDocument(document)) { type = MEDIA_DIR_VIDEO; documentId = document.id; dcId = document.dc_id; } else { type = MEDIA_DIR_DOCUMENT; documentId = document.id; dcId = document.dc_id; } if (MessageObject.isRoundVideoDocument(document)) { documentId = 0; dcId = 0; } } else if (webDocument != null) { operation = new FileLoadOperation(currentAccount, webDocument); if (webDocument.location != null) { type = MEDIA_DIR_CACHE; } else if (MessageObject.isVoiceWebDocument(webDocument)) { type = MEDIA_DIR_AUDIO; } else if (MessageObject.isVideoWebDocument(webDocument)) { type = MEDIA_DIR_VIDEO; } else if (MessageObject.isImageWebDocument(webDocument)) { type = MEDIA_DIR_IMAGE; } else { type = MEDIA_DIR_DOCUMENT; } } FileLoaderPriorityQueue loaderQueue; int index = Utilities.clamp(operation.getDatacenterId() - 1, 4, 0); boolean isStory = parentObject instanceof TLRPC.StoryItem; if (operation.totalBytesCount > 20 * 1024 * 1024 || isStory) { loaderQueue = largeFilesQueue[index]; } else { loaderQueue = smallFilesQueue[index]; } String storeFileName = fileName; if (cacheType == 0 || cacheType == 10 || isStory) { if (documentId != 0) { String path = getFileDatabase().getPath(documentId, dcId, type, true); boolean customPath = false; if (path != null) { File file = new File(path); if (file.exists()) { customPath = true; storeFileName = file.getName(); storeDir = file.getParentFile(); } } if (!customPath) { storeFileName = fileName; storeDir = getDirectory(type); boolean saveCustomPath = false; if (isStory) { File newDir = getDirectory(MEDIA_DIR_STORIES); if (newDir != null) { storeDir = newDir; saveCustomPath = true; } } else if ((type == MEDIA_DIR_IMAGE || type == MEDIA_DIR_VIDEO) && canSaveToPublicStorage(parentObject)) { File newDir; if (type == MEDIA_DIR_IMAGE) { newDir = getDirectory(MEDIA_DIR_IMAGE_PUBLIC); } else { newDir = getDirectory(MEDIA_DIR_VIDEO_PUBLIC); } if (newDir != null) { storeDir = newDir; saveCustomPath = true; } } else if (!TextUtils.isEmpty(getDocumentFileName(document)) && canSaveAsFile(parentObject)) { storeFileName = getDocumentFileName(document); File newDir = getDirectory(MEDIA_DIR_FILES); if (newDir != null) { storeDir = newDir; saveCustomPath = true; } } if (saveCustomPath) { operation.pathSaveData = new FilePathDatabase.PathData(documentId, dcId, type); } } } else { storeDir = getDirectory(type); } } else if (cacheType == 2) { operation.setEncryptFile(true); } operation.setPaths(currentAccount, fileName, loaderQueue, storeDir, tempDir, storeFileName); if (cacheType == 10) { operation.setIsPreloadVideoOperation(true); } final int finalType = type; FileLoadOperation.FileLoadOperationDelegate fileLoadOperationDelegate = new FileLoadOperation.FileLoadOperationDelegate() { @Override public void didPreFinishLoading(FileLoadOperation operation, File finalFile) { FileLoaderPriorityQueue queue = operation.getQueue(); fileLoaderQueue.postRunnable(() -> { operation.preFinished = true; queue.checkLoadingOperations(); }); } @Override public void didFinishLoadingFile(FileLoadOperation operation, File finalFile) { if (!operation.isPreloadVideoOperation() && operation.isPreloadFinished()) { checkDownloadQueue(operation, operation.getQueue(), 0); return; } FilePathDatabase.FileMeta fileMeta = getFileMetadataFromParent(currentAccount, parentObject); if (fileMeta != null) { getFileLoader().getFileDatabase().saveFileDialogId(finalFile, fileMeta); } if (parentObject instanceof MessageObject) { MessageObject messageObject = (MessageObject) parentObject; if (document != null && messageObject.putInDownloadsStore) { getDownloadController().onDownloadComplete(messageObject); } } if (!operation.isPreloadVideoOperation()) { loadOperationPathsUI.remove(fileName); if (delegate != null) { delegate.fileDidLoaded(fileName, finalFile, parentObject, finalType); } } checkDownloadQueue(operation, operation.getQueue(), 0); } @Override public void didFailedLoadingFile(FileLoadOperation operation, int reason) { loadOperationPathsUI.remove(fileName); checkDownloadQueue(operation, operation.getQueue()); if (delegate != null) { delegate.fileDidFailedLoad(fileName, reason); } if (document != null && parentObject instanceof MessageObject && reason == 0) { getDownloadController().onDownloadFail((MessageObject) parentObject, reason); } else if (reason == -1) { LaunchActivity.checkFreeDiscSpaceStatic(2); } } @Override public void didChangedLoadProgress(FileLoadOperation operation, long uploadedSize, long totalSize) { if (delegate != null) { delegate.fileLoadProgressChanged(operation, fileName, uploadedSize, totalSize); } } @Override public void saveFilePath(FilePathDatabase.PathData pathSaveData, File cacheFileFinal) { getFileDatabase().putPath(pathSaveData.id, pathSaveData.dc, pathSaveData.type, 0, cacheFileFinal != null ? cacheFileFinal.toString() : null); } @Override public boolean hasAnotherRefOnFile(String path) { return getFileDatabase().hasAnotherRefOnFile(path); } @Override public boolean isLocallyCreatedFile(String path) { return getFileDatabase().isLocallyCreated(path); } }; operation.setDelegate(fileLoadOperationDelegate); loadOperationPaths.put(finalFileName, operation); operation.setPriority(priority); if (stream != null) { operation.setStream(stream, streamPriority, streamOffset); } loaderQueue.add(operation); loaderQueue.checkLoadingOperations(operation.isStory && priority >= PRIORITY_HIGH); if (BuildVars.LOGS_ENABLED) { FileLog.d("create load operation fileName=" + finalFileName + " documentName=" + getDocumentFileName(document) + "size=" + AndroidUtilities.formatFileSize(operation.totalBytesCount) + " position in queue " + operation.getPositionInQueue() + " account=" + currentAccount); } return operation; } private boolean canSaveAsFile(Object parentObject) { if (parentObject instanceof MessageObject) { MessageObject messageObject = (MessageObject) parentObject; if (!messageObject.isDocument()) { return false; } return true; } return false; } private boolean canSaveToPublicStorage(Object parentObject) { if (BuildVars.NO_SCOPED_STORAGE) { return false; } FilePathDatabase.FileMeta metadata = getFileMetadataFromParent(currentAccount, parentObject); MessageObject messageObject = null; if (metadata != null) { int flag; long dialogId = metadata.dialogId; if (getMessagesController().isChatNoForwards(getMessagesController().getChat(-dialogId)) || DialogObject.isEncryptedDialog(dialogId)) { return false; } if (parentObject instanceof MessageObject) { messageObject = (MessageObject) parentObject; if (messageObject.isRoundVideo() || messageObject.isVoice() || messageObject.isAnyKindOfSticker() || messageObject.messageOwner.noforwards) { return false; } } else { if (metadata.messageType == MessageObject.TYPE_ROUND_VIDEO || metadata.messageType == MessageObject.TYPE_STICKER || metadata.messageType == MessageObject.TYPE_VOICE) { return false; } } if (dialogId >= 0) { flag = SharedConfig.SAVE_TO_GALLERY_FLAG_PEER; } else { if (ChatObject.isChannelAndNotMegaGroup(getMessagesController().getChat(-dialogId))) { flag = SharedConfig.SAVE_TO_GALLERY_FLAG_CHANNELS; } else { flag = SharedConfig.SAVE_TO_GALLERY_FLAG_GROUP; } } if (SaveToGallerySettingsHelper.needSave(flag, metadata, messageObject, currentAccount)) { return true; } } return false; } private void addOperationToQueue(FileLoadOperation operation, LinkedList<FileLoadOperation> queue) { int priority = operation.getPriority(); if (priority > 0) { int index = queue.size(); for (int a = 0, size = queue.size(); a < size; a++) { FileLoadOperation queuedOperation = queue.get(a); if (queuedOperation.getPriority() < priority) { index = a; break; } } queue.add(index, operation); } else { queue.add(operation); } } private void loadFile(final TLRPC.Document document, final SecureDocument secureDocument, final WebFile webDocument, TLRPC.TL_fileLocationToBeDeprecated location, final ImageLocation imageLocation, final Object parentObject, final String locationExt, final long locationSize, final int priority, final int cacheType) { String fileName; if (location != null) { fileName = getAttachFileName(location, locationExt); } else if (document != null) { fileName = getAttachFileName(document); } else if (webDocument != null) { fileName = getAttachFileName(webDocument); } else { fileName = null; } Runnable runnable = () -> loadFileInternal(document, secureDocument, webDocument, location, imageLocation, parentObject, locationExt, locationSize, priority, null, 0, false, cacheType); if (cacheType != 10 && !TextUtils.isEmpty(fileName) && !fileName.contains("" + Integer.MIN_VALUE)) { LoadOperationUIObject uiObject = new FileLoader.LoadOperationUIObject(); uiObject.loadInternalRunnable = runnable; loadOperationPathsUI.put(fileName, uiObject); } fileLoaderQueue.postRunnable(runnable); } protected FileLoadOperation loadStreamFile(final FileLoadOperationStream stream, final TLRPC.Document document, final ImageLocation location, final Object parentObject, final long offset, final boolean priority, int loadingPriority) { final CountDownLatch semaphore = new CountDownLatch(1); final FileLoadOperation[] result = new FileLoadOperation[1]; fileLoaderQueue.postRunnable(() -> { result[0] = loadFileInternal(document, null, null, document == null && location != null ? location.location : null, location, parentObject, document == null && location != null ? "mp4" : null, document == null && location != null ? location.currentSize : 0, loadingPriority, stream, offset, priority, document == null ? 1 : 0); semaphore.countDown(); }); awaitFileLoadOperation(semaphore, true); return result[0]; } /** * Necessary to wait of the FileLoadOperation object, despite the interruption of the thread. * Thread can be interrupted by {@link ImageLoader.CacheOutTask#cancel}. * For cases when two {@link ImageReceiver} require loading of the same file and the first {@link ImageReceiver} decides to cancel the operation. * For example, to autoplay a video after sending a message. */ private void awaitFileLoadOperation(CountDownLatch latch, boolean ignoreInterruption) { try { latch.await(); } catch (Exception e) { FileLog.e(e, false); if (ignoreInterruption) awaitFileLoadOperation(latch, false); } } private void checkDownloadQueue(FileLoadOperation operation, FileLoaderPriorityQueue queue) { checkDownloadQueue(operation, queue, 0); } private void checkDownloadQueue(FileLoadOperation operation, FileLoaderPriorityQueue queue, long delay) { fileLoaderQueue.postRunnable(() -> { if (queue.remove(operation)) { loadOperationPaths.remove(operation.getFileName()); queue.checkLoadingOperations(); } }, delay); } public void setDelegate(FileLoaderDelegate fileLoaderDelegate) { delegate = fileLoaderDelegate; } public static String getMessageFileName(TLRPC.Message message) { if (message == null) { return ""; } if (message instanceof TLRPC.TL_messageService) { if (message.action.photo != null) { ArrayList<TLRPC.PhotoSize> sizes = message.action.photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize()); if (sizeFull != null) { return getAttachFileName(sizeFull); } } } } else { if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaDocument) { return getAttachFileName(MessageObject.getMedia(message).document); } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaPhoto) { ArrayList<TLRPC.PhotoSize> sizes = MessageObject.getMedia(message).photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize(), false, null, true); if (sizeFull != null) { return getAttachFileName(sizeFull); } } } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaWebPage) { if (MessageObject.getMedia(message).webpage.document != null) { return getAttachFileName(MessageObject.getMedia(message).webpage.document); } else if (MessageObject.getMedia(message).webpage.photo != null) { ArrayList<TLRPC.PhotoSize> sizes = MessageObject.getMedia(message).webpage.photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize()); if (sizeFull != null) { return getAttachFileName(sizeFull); } } } } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaInvoice) { TLRPC.WebDocument document = ((TLRPC.TL_messageMediaInvoice) MessageObject.getMedia(message)).webPhoto; if (document != null) { return Utilities.MD5(document.url) + "." + ImageLoader.getHttpUrlExtension(document.url, getMimeTypePart(document.mime_type)); } } } return ""; } public File getPathToMessage(TLRPC.Message message) { return getPathToMessage(message, true); } public File getPathToMessage(TLRPC.Message message, boolean useFileDatabaseQueue) { return getPathToMessage(message, useFileDatabaseQueue, false); } public File getPathToMessage(TLRPC.Message message, boolean useFileDatabaseQueue, boolean saveAsFile) { if (message == null) { return new File(""); } if (message instanceof TLRPC.TL_messageService) { if (message.action.photo != null) { ArrayList<TLRPC.PhotoSize> sizes = message.action.photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize()); if (sizeFull != null) { return getPathToAttach(sizeFull, null, false, useFileDatabaseQueue); } } } } else { if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaDocument) { return getPathToAttach(MessageObject.getMedia(message).document, null,null, MessageObject.getMedia(message).ttl_seconds != 0, useFileDatabaseQueue, saveAsFile); } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaPhoto) { ArrayList<TLRPC.PhotoSize> sizes = MessageObject.getMedia(message).photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize(), false, null, true); if (sizeFull != null) { return getPathToAttach(sizeFull, null, MessageObject.getMedia(message).ttl_seconds != 0, useFileDatabaseQueue); } } } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaWebPage) { if (MessageObject.getMedia(message).webpage.document != null) { return getPathToAttach(MessageObject.getMedia(message).webpage.document, null, false, useFileDatabaseQueue); } else if (MessageObject.getMedia(message).webpage.photo != null) { ArrayList<TLRPC.PhotoSize> sizes = MessageObject.getMedia(message).webpage.photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize()); if (sizeFull != null) { return getPathToAttach(sizeFull, null, false, useFileDatabaseQueue); } } } } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaInvoice) { return getPathToAttach(((TLRPC.TL_messageMediaInvoice) MessageObject.getMedia(message)).photo, null, true, useFileDatabaseQueue); } } return new File(""); } public File getPathToAttach(TLObject attach) { return getPathToAttach(attach, null, false); } public File getPathToAttach(TLObject attach, boolean forceCache) { return getPathToAttach(attach, null, forceCache); } public File getPathToAttach(TLObject attach, String ext, boolean forceCache) { return getPathToAttach(attach, null, ext, forceCache, true, false); } public File getPathToAttach(TLObject attach, String ext, boolean forceCache, boolean useFileDatabaseQueue) { return getPathToAttach(attach, null, ext, forceCache, useFileDatabaseQueue, false); } /** * Return real file name. Used before file.exist() */ public File getPathToAttach(TLObject attach, String size, String ext, boolean forceCache, boolean useFileDatabaseQueue, boolean saveAsFile) { File dir = null; long documentId = 0; int dcId = 0; int type = 0; String fileName = null; if (forceCache) { dir = getDirectory(MEDIA_DIR_CACHE); } else { if (attach instanceof TLRPC.Document) { TLRPC.Document document = (TLRPC.Document) attach; if (!TextUtils.isEmpty(document.localPath)) { return new File(document.localPath); } if (document.key != null) { type = MEDIA_DIR_CACHE; } else { if (MessageObject.isVoiceDocument(document)) { type = MEDIA_DIR_AUDIO; } else if (MessageObject.isVideoDocument(document)) { type = MEDIA_DIR_VIDEO; } else { String documentFileName = getDocumentFileName(document); if (saveAsFile && !TextUtils.isEmpty(documentFileName)) { fileName = documentFileName; type = MEDIA_DIR_FILES; } else { type = MEDIA_DIR_DOCUMENT; } } } documentId = document.id; dcId = document.dc_id; dir = getDirectory(type); } else if (attach instanceof TLRPC.Photo) { TLRPC.PhotoSize photoSize = getClosestPhotoSizeWithSize(((TLRPC.Photo) attach).sizes, AndroidUtilities.getPhotoSize()); return getPathToAttach(photoSize, ext, false, useFileDatabaseQueue); } else if (attach instanceof TLRPC.PhotoSize) { TLRPC.PhotoSize photoSize = (TLRPC.PhotoSize) attach; if (photoSize instanceof TLRPC.TL_photoStrippedSize || photoSize instanceof TLRPC.TL_photoPathSize) { dir = null; } else if (photoSize.location == null || photoSize.location.key != null || photoSize.location.volume_id == Integer.MIN_VALUE && photoSize.location.local_id < 0 || photoSize.size < 0) { dir = getDirectory(type = MEDIA_DIR_CACHE); } else { dir = getDirectory(type = MEDIA_DIR_IMAGE); } documentId = photoSize.location.volume_id; dcId = photoSize.location.dc_id + (photoSize.location.local_id << 16); } else if (attach instanceof TLRPC.TL_videoSize) { TLRPC.TL_videoSize videoSize = (TLRPC.TL_videoSize) attach; if (videoSize.location == null || videoSize.location.key != null || videoSize.location.volume_id == Integer.MIN_VALUE && videoSize.location.local_id < 0 || videoSize.size < 0) { dir = getDirectory(type = MEDIA_DIR_CACHE); } else { dir = getDirectory(type = MEDIA_DIR_IMAGE); } documentId = videoSize.location.volume_id; dcId = videoSize.location.dc_id + (videoSize.location.local_id << 16); } else if (attach instanceof TLRPC.FileLocation) { TLRPC.FileLocation fileLocation = (TLRPC.FileLocation) attach; if (fileLocation.key != null || fileLocation.volume_id == Integer.MIN_VALUE && fileLocation.local_id < 0) { dir = getDirectory(MEDIA_DIR_CACHE); } else { documentId = fileLocation.volume_id; dcId = fileLocation.dc_id + (fileLocation.local_id << 16); dir = getDirectory(type = MEDIA_DIR_IMAGE); } } else if (attach instanceof TLRPC.UserProfilePhoto || attach instanceof TLRPC.ChatPhoto) { if (size == null) { size = "s"; } if ("s".equals(size)) { dir = getDirectory(MEDIA_DIR_CACHE); } else { dir = getDirectory(MEDIA_DIR_IMAGE); } } else if (attach instanceof WebFile) { WebFile document = (WebFile) attach; if (document.mime_type.startsWith("image/")) { dir = getDirectory(MEDIA_DIR_IMAGE); } else if (document.mime_type.startsWith("audio/")) { dir = getDirectory(MEDIA_DIR_AUDIO); } else if (document.mime_type.startsWith("video/")) { dir = getDirectory(MEDIA_DIR_VIDEO); } else { dir = getDirectory(MEDIA_DIR_DOCUMENT); } } else if (attach instanceof TLRPC.TL_secureFile || attach instanceof SecureDocument) { dir = getDirectory(MEDIA_DIR_CACHE); } } if (dir == null) { return new File(""); } if (documentId != 0) { String path = getInstance(UserConfig.selectedAccount).getFileDatabase().getPath(documentId, dcId, type, useFileDatabaseQueue); if (path != null) { return new File(path); } } if (fileName == null) { fileName = getAttachFileName(attach, ext); } return new File(dir, fileName); } public FilePathDatabase getFileDatabase() { return filePathDatabase; } public static TLRPC.PhotoSize getClosestPhotoSizeWithSize(ArrayList<TLRPC.PhotoSize> sizes, int side) { return getClosestPhotoSizeWithSize(sizes, side, false); } public static TLRPC.PhotoSize getClosestPhotoSizeWithSize(ArrayList<TLRPC.PhotoSize> sizes, int side, boolean byMinSide) { return getClosestPhotoSizeWithSize(sizes, side, byMinSide, null, false); } public static TLRPC.PhotoSize getClosestPhotoSizeWithSize(ArrayList<TLRPC.PhotoSize> sizes, int side, boolean byMinSide, TLRPC.PhotoSize toIgnore, boolean ignoreStripped) { if (sizes == null || sizes.isEmpty()) { return null; } int lastSide = 0; TLRPC.PhotoSize closestObject = null; for (int a = 0; a < sizes.size(); a++) { TLRPC.PhotoSize obj = sizes.get(a); if (obj == null || obj == toIgnore || obj instanceof TLRPC.TL_photoSizeEmpty || obj instanceof TLRPC.TL_photoPathSize || ignoreStripped && obj instanceof TLRPC.TL_photoStrippedSize) { continue; } if (byMinSide) { int currentSide = Math.min(obj.h, obj.w); if ( closestObject == null || side > 100 && closestObject.location != null && closestObject.location.dc_id == Integer.MIN_VALUE || obj instanceof TLRPC.TL_photoCachedSize || side > lastSide && lastSide < currentSide ) { closestObject = obj; lastSide = currentSide; } } else { int currentSide = Math.max(obj.w, obj.h); 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; } } } return closestObject; } public static TLRPC.VideoSize getClosestVideoSizeWithSize(ArrayList<TLRPC.VideoSize> sizes, int side) { return getClosestVideoSizeWithSize(sizes, side, false); } public static TLRPC.VideoSize getClosestVideoSizeWithSize(ArrayList<TLRPC.VideoSize> sizes, int side, boolean byMinSide) { return getClosestVideoSizeWithSize(sizes, side, byMinSide, false); } public static TLRPC.VideoSize getClosestVideoSizeWithSize(ArrayList<TLRPC.VideoSize> sizes, int side, boolean byMinSide, boolean ignoreStripped) { if (sizes == null || sizes.isEmpty()) { return null; } int lastSide = 0; TLRPC.VideoSize closestObject = null; for (int a = 0; a < sizes.size(); a++) { TLRPC.VideoSize obj = sizes.get(a); if (obj == null || obj instanceof TLRPC.TL_videoSizeEmojiMarkup || obj instanceof TLRPC.TL_videoSizeStickerMarkup) { continue; } if (byMinSide) { int currentSide = Math.min(obj.h, obj.w); if (closestObject == null || side > 100 && closestObject.location != null && closestObject.location.dc_id == Integer.MIN_VALUE || side > lastSide && lastSide < currentSide) { closestObject = obj; lastSide = currentSide; } } else { int currentSide = Math.max(obj.w, obj.h); if ( closestObject == null || side > 100 && closestObject.location != null && closestObject.location.dc_id == Integer.MIN_VALUE || currentSide <= side && lastSide < currentSide ) { closestObject = obj; lastSide = currentSide; } } } return closestObject; } public static TLRPC.TL_photoPathSize getPathPhotoSize(ArrayList<TLRPC.PhotoSize> sizes) { if (sizes == null || sizes.isEmpty()) { return null; } for (int a = 0; a < sizes.size(); a++) { TLRPC.PhotoSize obj = sizes.get(a); if (obj instanceof TLRPC.TL_photoPathSize) { continue; } return (TLRPC.TL_photoPathSize) obj; } return null; } public static String getFileExtension(File file) { String name = file.getName(); try { return name.substring(name.lastIndexOf('.') + 1); } catch (Exception e) { return ""; } } public static String fixFileName(String fileName) { if (fileName != null) { fileName = fileName.replaceAll("[\u0001-\u001f<>\u202E:\"/\\\\|?*\u007f]+", "").trim(); } return fileName; } public static String getDocumentFileName(TLRPC.Document document) { if (document == null) { return null; } if (document.file_name_fixed != null) { return document.file_name_fixed; } String fileName = null; if (document != null) { if (document.file_name != null) { fileName = document.file_name; } else { for (int a = 0; a < document.attributes.size(); a++) { TLRPC.DocumentAttribute documentAttribute = document.attributes.get(a); if (documentAttribute instanceof TLRPC.TL_documentAttributeFilename) { fileName = documentAttribute.file_name; } } } } fileName = fixFileName(fileName); return fileName != null ? fileName : ""; } public static String getMimeTypePart(String mime) { int index; if ((index = mime.lastIndexOf('/')) != -1) { return mime.substring(index + 1); } return ""; } public static String getExtensionByMimeType(String mime) { if (mime != null) { switch (mime) { case "video/mp4": return ".mp4"; case "video/x-matroska": return ".mkv"; case "audio/ogg": return ".ogg"; } } return ""; } public static File getInternalCacheDir() { return ApplicationLoader.applicationContext.getCacheDir(); } public static String getDocumentExtension(TLRPC.Document document) { String fileName = getDocumentFileName(document); int idx = fileName.lastIndexOf('.'); String ext = null; if (idx != -1) { ext = fileName.substring(idx + 1); } if (ext == null || ext.length() == 0) { ext = document.mime_type; } if (ext == null) { ext = ""; } ext = ext.toUpperCase(); return ext; } public static String getAttachFileName(TLObject attach) { return getAttachFileName(attach, null); } public static String getAttachFileName(TLObject attach, String ext) { return getAttachFileName(attach, null, ext); } /** * file hash. contains docId, dcId, ext. */ public static String getAttachFileName(TLObject attach, String size, String ext) { if (attach instanceof TLRPC.Document) { TLRPC.Document document = (TLRPC.Document) attach; String docExt; docExt = getDocumentFileName(document); int idx; if ((idx = docExt.lastIndexOf('.')) == -1) { docExt = ""; } else { docExt = docExt.substring(idx); } if (docExt.length() <= 1) { docExt = getExtensionByMimeType(document.mime_type); } if (docExt.length() > 1) { return document.dc_id + "_" + document.id + docExt; } else { return document.dc_id + "_" + document.id; } } else if (attach instanceof SecureDocument) { SecureDocument secureDocument = (SecureDocument) attach; return secureDocument.secureFile.dc_id + "_" + secureDocument.secureFile.id + ".jpg"; } else if (attach instanceof TLRPC.TL_secureFile) { TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) attach; return secureFile.dc_id + "_" + secureFile.id + ".jpg"; } else if (attach instanceof WebFile) { WebFile document = (WebFile) attach; return Utilities.MD5(document.url) + "." + ImageLoader.getHttpUrlExtension(document.url, getMimeTypePart(document.mime_type)); } else if (attach instanceof TLRPC.PhotoSize) { TLRPC.PhotoSize photo = (TLRPC.PhotoSize) attach; if (photo.location == null || photo.location instanceof TLRPC.TL_fileLocationUnavailable) { return ""; } return photo.location.volume_id + "_" + photo.location.local_id + "." + (ext != null ? ext : "jpg"); } else if (attach instanceof TLRPC.TL_videoSize) { TLRPC.TL_videoSize video = (TLRPC.TL_videoSize) attach; if (video.location == null || video.location instanceof TLRPC.TL_fileLocationUnavailable) { return ""; } return video.location.volume_id + "_" + video.location.local_id + "." + (ext != null ? ext : "mp4"); } else if (attach instanceof TLRPC.FileLocation) { if (attach instanceof TLRPC.TL_fileLocationUnavailable) { return ""; } TLRPC.FileLocation location = (TLRPC.FileLocation) attach; return location.volume_id + "_" + location.local_id + "." + (ext != null ? ext : "jpg"); } else if (attach instanceof TLRPC.UserProfilePhoto) { if (size == null) { size = "s"; } TLRPC.UserProfilePhoto location = (TLRPC.UserProfilePhoto) attach; if (location.photo_small != null) { if ("s".equals(size)) { return getAttachFileName(location.photo_small, ext); } else { return getAttachFileName(location.photo_big, ext); } } else { return location.photo_id + "_" + size + "." + (ext != null ? ext : "jpg"); } } else if (attach instanceof TLRPC.ChatPhoto) { TLRPC.ChatPhoto location = (TLRPC.ChatPhoto) attach; if (location.photo_small != null) { if ("s".equals(size)) { return getAttachFileName(location.photo_small, ext); } else { return getAttachFileName(location.photo_big, ext); } } else { return location.photo_id + "_" + size + "." + (ext != null ? ext : "jpg"); } } return ""; } public void deleteFiles(final ArrayList<File> files, final int type) { if (files == null || files.isEmpty()) { return; } fileLoaderQueue.postRunnable(() -> { for (int a = 0; a < files.size(); a++) { File file = files.get(a); File encrypted = new File(file.getAbsolutePath() + ".enc"); if (encrypted.exists()) { try { if (!encrypted.delete()) { encrypted.deleteOnExit(); } } catch (Exception e) { FileLog.e(e); } try { File key = new File(FileLoader.getInternalCacheDir(), file.getName() + ".enc.key"); if (!key.delete()) { key.deleteOnExit(); } } catch (Exception e) { FileLog.e(e); } } else if (file.exists()) { try { if (!file.delete()) { file.deleteOnExit(); } } catch (Exception e) { FileLog.e(e); } } try { File qFile = new File(file.getParentFile(), "q_" + file.getName()); if (qFile.exists()) { if (!qFile.delete()) { qFile.deleteOnExit(); } } } catch (Exception e) { FileLog.e(e); } } if (type == 2) { ImageLoader.getInstance().clearMemory(); } }); } public static boolean isVideoMimeType(String mime) { return "video/mp4".equals(mime) || SharedConfig.streamMkv && "video/x-matroska".equals(mime); } public static boolean copyFile(InputStream sourceFile, File destFile) throws IOException { return copyFile(sourceFile, destFile, -1); } public static boolean copyFile(InputStream sourceFile, File destFile, int maxSize) throws IOException { FileOutputStream out = new FileOutputStream(destFile); byte[] buf = new byte[4096]; int len; int totalLen = 0; while ((len = sourceFile.read(buf)) > 0) { Thread.yield(); out.write(buf, 0, len); totalLen += len; if (maxSize > 0 && totalLen >= maxSize) { break; } } out.getFD().sync(); out.close(); return true; } public static boolean isSamePhoto(TLObject photo1, TLObject photo2) { if (photo1 == null && photo2 != null || photo1 != null && photo2 == null) { return false; } if (photo1 == null && photo2 == null) { return true; } if (photo1.getClass() != photo2.getClass()) { return false; } if (photo1 instanceof TLRPC.UserProfilePhoto) { TLRPC.UserProfilePhoto p1 = (TLRPC.UserProfilePhoto) photo1; TLRPC.UserProfilePhoto p2 = (TLRPC.UserProfilePhoto) photo2; return p1.photo_id == p2.photo_id; } else if (photo1 instanceof TLRPC.ChatPhoto) { TLRPC.ChatPhoto p1 = (TLRPC.ChatPhoto) photo1; TLRPC.ChatPhoto p2 = (TLRPC.ChatPhoto) photo2; return p1.photo_id == p2.photo_id; } return false; } public static boolean isSamePhoto(TLRPC.FileLocation location, TLRPC.Photo photo) { if (location == null || !(photo instanceof TLRPC.TL_photo)) { return false; } for (int b = 0, N = photo.sizes.size(); b < N; b++) { TLRPC.PhotoSize size = photo.sizes.get(b); if (size.location != null && size.location.local_id == location.local_id && size.location.volume_id == location.volume_id) { return true; } } if (-location.volume_id == photo.id) { return true; } return false; } public static long getPhotoId(TLObject object) { if (object instanceof TLRPC.Photo) { return ((TLRPC.Photo) object).id; } else if (object instanceof TLRPC.ChatPhoto) { return ((TLRPC.ChatPhoto) object).photo_id; } else if (object instanceof TLRPC.UserProfilePhoto) { return ((TLRPC.UserProfilePhoto) object).photo_id; } return 0; } public void getCurrentLoadingFiles(ArrayList<MessageObject> currentLoadingFiles) { currentLoadingFiles.clear(); currentLoadingFiles.addAll(getDownloadController().downloadingFiles); for (int i = 0; i < currentLoadingFiles.size(); i++) { currentLoadingFiles.get(i).isDownloadingFile = true; } } public void getRecentLoadingFiles(ArrayList<MessageObject> recentLoadingFiles) { recentLoadingFiles.clear(); recentLoadingFiles.addAll(getDownloadController().recentDownloadingFiles); for (int i = 0; i < recentLoadingFiles.size(); i++) { recentLoadingFiles.get(i).isDownloadingFile = true; } } public void checkCurrentDownloadsFiles() { ArrayList<MessageObject> messagesToRemove = new ArrayList<>(); ArrayList<MessageObject> messageObjects = new ArrayList<>(getDownloadController().recentDownloadingFiles); for (int i = 0; i < messageObjects.size(); i++) { messageObjects.get(i).checkMediaExistance(); if (messageObjects.get(i).mediaExists) { messagesToRemove.add(messageObjects.get(i)); } } if (!messagesToRemove.isEmpty()) { AndroidUtilities.runOnUIThread(() -> { getDownloadController().recentDownloadingFiles.removeAll(messagesToRemove); getNotificationCenter().postNotificationName(NotificationCenter.onDownloadingFilesChanged); }); } } /** * optimezed for bulk messages */ public void checkMediaExistance(ArrayList<MessageObject> messageObjects) { getFileDatabase().checkMediaExistance(messageObjects); } public interface FileResolver { File getFile(); } public void clearRecentDownloadedFiles() { getDownloadController().clearRecentDownloadedFiles(); } public void clearFilePaths() { filePathDatabase.clear(); } public static boolean checkUploadFileSize(int currentAccount, long length) { boolean premium = AccountInstance.getInstance(currentAccount).getUserConfig().isPremium(); if (length < DEFAULT_MAX_FILE_SIZE || (length < DEFAULT_MAX_FILE_SIZE_PREMIUM && premium)) { return true; } return false; } private static class LoadOperationUIObject { Runnable loadInternalRunnable; } public static byte[] longToBytes(long x) { ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); buffer.putLong(x); return buffer.array(); } public static long bytesToLong(byte[] bytes) { long l = 0; for (int i = 0; i < 8; i++) { l <<= 8; l ^= bytes[i] & 0xFF; } return l; } Runnable dumpFilesQueueRunnable = () -> { for (int i = 0; i < smallFilesQueue.length; i++) { if (smallFilesQueue[i].getCount() > 0 || largeFilesQueue[i].getCount() > 0) { FileLog.d("download queue: dc" + (i + 1) + " account=" + currentAccount + " small_operations=" + smallFilesQueue[i].getCount() + " large_operations=" + largeFilesQueue[i].getCount()); // if (!largeFilesQueue[i].allOperations.isEmpty()) { // largeFilesQueue[i].allOperations.get(0).dump(); // } } } dumpFilesQueue(); }; public void dumpFilesQueue() { if (!BuildVars.LOGS_ENABLED) { return; } fileLoaderQueue.cancelRunnable(dumpFilesQueueRunnable); fileLoaderQueue.postRunnable(dumpFilesQueueRunnable, 10000); } }
cloudveiltech/CloudVeilMessenger
TMessagesProj/src/main/java/org/telegram/messenger/FileLoader.java
41,663
package org.telegram.messenger.video; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.RectF; import android.graphics.Typeface; import android.opengl.GLES20; import android.opengl.GLUtils; import android.os.Build; import android.text.Layout; import android.text.Spannable; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.util.Log; import android.util.Pair; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.inputmethod.EditorInfo; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import com.google.common.collect.BiMap; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.Bitmaps; import org.telegram.messenger.Emoji; import org.telegram.messenger.FileLog; import org.telegram.messenger.LocaleController; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; import org.telegram.messenger.VideoEditedInfo; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.Components.AnimatedEmojiSpan; import org.telegram.ui.Components.AnimatedFileDrawable; import org.telegram.ui.Components.CubicBezierInterpolator; import org.telegram.ui.Components.Paint.Views.EditTextOutline; import org.telegram.ui.Components.Paint.Views.PaintTextOptionsView; import org.telegram.ui.Components.RLottieDrawable; import java.io.File; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.ArrayList; import javax.microedition.khronos.opengles.GL10; public class WebmEncoder { private static native long createEncoder( String outputPath, int width, int height, int fps, long bitrate ); private static native boolean writeFrame( long ptr, ByteBuffer argbPixels, int width, int height ); public static native void stop(long ptr); public static boolean convert(MediaCodecVideoConvertor.ConvertVideoParams params, int triesLeft) { final int W = params.resultWidth; final int H = params.resultHeight; final long maxFileSize = 255 * 1024; final long ptr = createEncoder(params.cacheFile.getAbsolutePath(), W, H, params.framerate, params.bitrate); if (ptr == 0) { return true; } boolean error = false; Bitmap bitmap = null; try { bitmap = Bitmap.createBitmap(W, H, Bitmap.Config.ARGB_8888); ByteBuffer buffer = ByteBuffer.allocateDirect(bitmap.getByteCount()); Canvas canvas = new Canvas(bitmap); FrameDrawer frameDrawer = new FrameDrawer(params); final int framesCount = (int) Math.ceil(params.framerate * (params.duration / 1000.0)); for (int frame = 0; frame < framesCount; ++frame) { frameDrawer.draw(canvas, frame); bitmap.copyPixelsToBuffer(buffer); buffer.flip(); if (!writeFrame(ptr, buffer, W, H)) { FileLog.d("webm writeFile error at " + frame + "/" + framesCount); return true; } if (params.callback != null) { params.callback.didWriteData(Math.min(maxFileSize, params.cacheFile.length()), (float) frame / framesCount); } if (frame % 3 == 0 && params.callback != null) { params.callback.checkConversionCanceled(); } } } catch (Exception e) { FileLog.e(e); error = true; } finally { stop(ptr); if (bitmap != null) { bitmap.recycle(); } } long fileSize = params.cacheFile.length(); if (triesLeft > 0 && fileSize > maxFileSize) { int oldBitrate = params.bitrate; params.bitrate *= ((float) maxFileSize / fileSize) * .9f; params.cacheFile.delete(); FileLog.d("webm encoded too much, got " + fileSize + ", old bitrate = " + oldBitrate + " new bitrate = " + params.bitrate); return convert(params, triesLeft - 1); } if (params.callback != null) { params.callback.didWriteData(fileSize, 1f); } FileLog.d("webm encoded to " + params.cacheFile + " with size=" + fileSize + " triesLeft=" + triesLeft); return error; } public static class FrameDrawer { private final int W, H; private final int fps; private final Bitmap photo; private final ArrayList<VideoEditedInfo.MediaEntity> mediaEntities = new ArrayList<>(); private final Paint clearPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private final Paint bitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG); private final Path clipPath; public FrameDrawer(MediaCodecVideoConvertor.ConvertVideoParams params) { this.W = params.resultWidth; this.H = params.resultHeight; this.fps = params.framerate; clipPath = new Path(); RectF bounds = new RectF(0, 0, W, H); clipPath.addRoundRect(bounds, W * .125f, H * .125f, Path.Direction.CW); photo = BitmapFactory.decodeFile(params.videoPath); mediaEntities.addAll(params.mediaEntities); for (int a = 0, N = mediaEntities.size(); a < N; a++) { VideoEditedInfo.MediaEntity entity = mediaEntities.get(a); if ( entity.type == VideoEditedInfo.MediaEntity.TYPE_STICKER || entity.type == VideoEditedInfo.MediaEntity.TYPE_PHOTO || entity.type == VideoEditedInfo.MediaEntity.TYPE_ROUND ) { initStickerEntity(entity); } else if (entity.type == VideoEditedInfo.MediaEntity.TYPE_TEXT) { initTextEntity(entity); } } clearPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); } public void draw(Canvas canvas, int frame) { canvas.drawPaint(clearPaint); canvas.save(); canvas.clipPath(clipPath); if (photo != null) { canvas.drawBitmap(photo, 0, 0, null); } final long time = frame * (1_000_000_000L / fps); for (int a = 0, N = mediaEntities.size(); a < N; a++) { VideoEditedInfo.MediaEntity entity = mediaEntities.get(a); drawEntity(canvas, entity, entity.color, time); } canvas.restore(); } private void drawEntity(Canvas canvas, VideoEditedInfo.MediaEntity entity, int textColor, long time) { if (entity.ptr != 0) { if (entity.bitmap == null || entity.W <= 0 || entity.H <= 0) { return; } RLottieDrawable.getFrame(entity.ptr, (int) entity.currentFrame, entity.bitmap, entity.W, entity.H, entity.bitmap.getRowBytes(), true); applyRoundRadius(entity, entity.bitmap, (entity.subType & 8) != 0 ? textColor : 0); canvas.drawBitmap(entity.bitmap, entity.matrix, bitmapPaint); entity.currentFrame += entity.framesPerDraw; if (entity.currentFrame >= entity.metadata[0]) { entity.currentFrame = 0; } } else if (entity.animatedFileDrawable != null) { int lastFrame = (int) entity.currentFrame; float scale = 1f; entity.currentFrame += entity.framesPerDraw; int currentFrame = (int) entity.currentFrame; while (lastFrame != currentFrame) { entity.animatedFileDrawable.getNextFrame(true); currentFrame--; } Bitmap frameBitmap = entity.animatedFileDrawable.getBackgroundBitmap(); if (frameBitmap != null) { canvas.drawBitmap(frameBitmap, entity.matrix, bitmapPaint); } } else { canvas.drawBitmap(entity.bitmap, entity.matrix, bitmapPaint); if (entity.entities != null && !entity.entities.isEmpty()) { for (int i = 0; i < entity.entities.size(); ++i) { VideoEditedInfo.EmojiEntity e = entity.entities.get(i); if (e == null) { continue; } VideoEditedInfo.MediaEntity entity1 = e.entity; if (entity1 == null) { continue; } drawEntity(canvas, entity1, entity.color, time); } } } } private void initTextEntity(VideoEditedInfo.MediaEntity entity) { EditTextOutline editText = new EditTextOutline(ApplicationLoader.applicationContext); editText.getPaint().setAntiAlias(true); editText.drawAnimatedEmojiDrawables = false; editText.setBackgroundColor(Color.TRANSPARENT); editText.setPadding(AndroidUtilities.dp(7), AndroidUtilities.dp(7), AndroidUtilities.dp(7), AndroidUtilities.dp(7)); Typeface typeface; if (entity.textTypeface != null && (typeface = entity.textTypeface.getTypeface()) != null) { editText.setTypeface(typeface); } editText.setTextSize(TypedValue.COMPLEX_UNIT_PX, entity.fontSize); CharSequence text = new SpannableString(entity.text); for (VideoEditedInfo.EmojiEntity e : entity.entities) { if (e.documentAbsolutePath == null) { continue; } e.entity = new VideoEditedInfo.MediaEntity(); e.entity.text = e.documentAbsolutePath; e.entity.subType = e.subType; AnimatedEmojiSpan span = new AnimatedEmojiSpan(0L, 1f, editText.getPaint().getFontMetricsInt()) { @Override public void draw(@NonNull Canvas canvas, CharSequence charSequence, int start, int end, float x, int top, int y, int bottom, @NonNull Paint paint) { super.draw(canvas, charSequence, start, end, x, top, y, bottom, paint); float tcx = entity.x + (editText.getPaddingLeft() + x + measuredSize / 2f) / entity.viewWidth * entity.width; float tcy = entity.y + (editText.getPaddingTop() + top + (bottom - top) / 2f) / entity.viewHeight * entity.height; if (entity.rotation != 0) { float mx = entity.x + entity.width / 2f; float my = entity.y + entity.height / 2f; float ratio = W / (float) H; float x1 = tcx - mx; float y1 = (tcy - my) / ratio; tcx = (float) (x1 * Math.cos(-entity.rotation) - y1 * Math.sin(-entity.rotation)) + mx; tcy = (float) (x1 * Math.sin(-entity.rotation) + y1 * Math.cos(-entity.rotation)) * ratio + my; } e.entity.width = (float) measuredSize / entity.viewWidth * entity.width; e.entity.height = (float) measuredSize / entity.viewHeight * entity.height; e.entity.x = tcx - e.entity.width / 2f; e.entity.y = tcy - e.entity.height / 2f; e.entity.rotation = entity.rotation; if (e.entity.bitmap == null) initStickerEntity(e.entity); } }; ((Spannable) text).setSpan(span, e.offset, e.offset + e.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } text = Emoji.replaceEmoji(text, editText.getPaint().getFontMetricsInt(), (int) (editText.getTextSize() * .8f), false); if (text instanceof Spanned) { Emoji.EmojiSpan[] spans = ((Spanned) text).getSpans(0, text.length(), Emoji.EmojiSpan.class); if (spans != null) { for (int i = 0; i < spans.length; ++i) { spans[i].scale = .85f; } } } editText.setText(text); editText.setTextColor(entity.color); int gravity; switch (entity.textAlign) { default: case PaintTextOptionsView.ALIGN_LEFT: gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL; break; case PaintTextOptionsView.ALIGN_CENTER: gravity = Gravity.CENTER; break; case PaintTextOptionsView.ALIGN_RIGHT: gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL; break; } editText.setGravity(gravity); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { int textAlign; switch (entity.textAlign) { default: case PaintTextOptionsView.ALIGN_LEFT: textAlign = LocaleController.isRTL ? View.TEXT_ALIGNMENT_TEXT_END : View.TEXT_ALIGNMENT_TEXT_START; break; case PaintTextOptionsView.ALIGN_CENTER: textAlign = View.TEXT_ALIGNMENT_CENTER; break; case PaintTextOptionsView.ALIGN_RIGHT: textAlign = LocaleController.isRTL ? View.TEXT_ALIGNMENT_TEXT_START : View.TEXT_ALIGNMENT_TEXT_END; break; } editText.setTextAlignment(textAlign); } editText.setHorizontallyScrolling(false); editText.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI); editText.setFocusableInTouchMode(true); editText.setInputType(editText.getInputType() | EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES); if (Build.VERSION.SDK_INT >= 23) { setBreakStrategy(editText); } if (entity.subType == 0) { editText.setFrameColor(entity.color); editText.setTextColor(AndroidUtilities.computePerceivedBrightness(entity.color) >= .721f ? Color.BLACK : Color.WHITE); } else if (entity.subType == 1) { editText.setFrameColor(AndroidUtilities.computePerceivedBrightness(entity.color) >= .25f ? 0x99000000 : 0x99ffffff); editText.setTextColor(entity.color); } else if (entity.subType == 2) { editText.setFrameColor(AndroidUtilities.computePerceivedBrightness(entity.color) >= .25f ? Color.BLACK : Color.WHITE); editText.setTextColor(entity.color); } else if (entity.subType == 3) { editText.setFrameColor(0); editText.setTextColor(entity.color); } editText.measure(View.MeasureSpec.makeMeasureSpec(entity.viewWidth, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(entity.viewHeight, View.MeasureSpec.EXACTLY)); editText.layout(0, 0, entity.viewWidth, entity.viewHeight); entity.bitmap = Bitmap.createBitmap(entity.viewWidth, entity.viewHeight, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(entity.bitmap); editText.draw(canvas); setupMatrix(entity); } @RequiresApi(api = Build.VERSION_CODES.M) public void setBreakStrategy(EditTextOutline editText) { editText.setBreakStrategy(Layout.BREAK_STRATEGY_SIMPLE); } private void initStickerEntity(VideoEditedInfo.MediaEntity entity) { entity.W = (int) (entity.width * W); entity.H = (int) (entity.height * H); if (entity.W > 512) { entity.H = (int) (entity.H / (float) entity.W * 512); entity.W = 512; } if (entity.H > 512) { entity.W = (int) (entity.W / (float) entity.H * 512); entity.H = 512; } if ((entity.subType & 1) != 0) { if (entity.W <= 0 || entity.H <= 0) { return; } entity.bitmap = Bitmap.createBitmap(entity.W, entity.H, Bitmap.Config.ARGB_8888); entity.metadata = new int[3]; entity.ptr = RLottieDrawable.create(entity.text, null, entity.W, entity.H, entity.metadata, false, null, false, 0); entity.framesPerDraw = (float) entity.metadata[1] / fps; } else if ((entity.subType & 4) != 0) { entity.looped = false; entity.animatedFileDrawable = new AnimatedFileDrawable(new File(entity.text), true, 0, 0, null, null, null, 0, UserConfig.selectedAccount, true, 512, 512, null); entity.framesPerDraw = (float) entity.animatedFileDrawable.getFps() / fps; entity.currentFrame = 1; entity.animatedFileDrawable.getNextFrame(true); if (entity.type == VideoEditedInfo.MediaEntity.TYPE_ROUND) { entity.firstSeek = true; } } else { String path = entity.text; if (!TextUtils.isEmpty(entity.segmentedPath) && (entity.subType & 16) != 0) { path = entity.segmentedPath; } if (Build.VERSION.SDK_INT >= 19) { BitmapFactory.Options opts = new BitmapFactory.Options(); if (entity.type == VideoEditedInfo.MediaEntity.TYPE_PHOTO) { opts.inMutable = true; } entity.bitmap = BitmapFactory.decodeFile(path, opts); } else { try { File filePath = new File(path); RandomAccessFile file = new RandomAccessFile(filePath, "r"); ByteBuffer buffer = file.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, filePath.length()); BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inJustDecodeBounds = true; Utilities.loadWebpImage(null, buffer, buffer.limit(), bmOptions, true); if (entity.type == VideoEditedInfo.MediaEntity.TYPE_PHOTO) { bmOptions.inMutable = true; } entity.bitmap = Bitmaps.createBitmap(bmOptions.outWidth, bmOptions.outHeight, Bitmap.Config.ARGB_8888); Utilities.loadWebpImage(entity.bitmap, buffer, buffer.limit(), null, true); file.close(); } catch (Throwable e) { FileLog.e(e); } } if (entity.type == VideoEditedInfo.MediaEntity.TYPE_PHOTO && entity.bitmap != null) { entity.roundRadius = AndroidUtilities.dp(12) / (float) Math.min(entity.viewWidth, entity.viewHeight); Pair<Integer, Integer> orientation = AndroidUtilities.getImageOrientation(entity.text); entity.rotation -= Math.toRadians(orientation.first); if ((orientation.first / 90 % 2) == 1) { float cx = entity.x + entity.width / 2f, cy = entity.y + entity.height / 2f; float w = entity.width * W / H; entity.width = entity.height * H / W; entity.height = w; entity.x = cx - entity.width / 2f; entity.y = cy - entity.height / 2f; } applyRoundRadius(entity, entity.bitmap, 0); } else if (entity.bitmap != null) { float aspect = entity.bitmap.getWidth() / (float) entity.bitmap.getHeight(); if (aspect > 1) { float h = entity.height / aspect; entity.y += (entity.height - h) / 2; entity.height = h; } else if (aspect < 1) { float w = entity.width * aspect; entity.x += (entity.width - w) / 2; entity.width = w; } } } setupMatrix(entity); } private void setupMatrix(VideoEditedInfo.MediaEntity entity) { entity.matrix = new Matrix(); Bitmap bitmap = entity.bitmap; if (bitmap == null && entity.animatedFileDrawable != null) { bitmap = entity.animatedFileDrawable.getBackgroundBitmap(); } if (bitmap != null) { entity.matrix.postScale(1f / bitmap.getWidth(), 1f / bitmap.getHeight()); } if (entity.type != VideoEditedInfo.MediaEntity.TYPE_TEXT && (entity.subType & 2) != 0) { entity.matrix.postScale(-1, 1, .5f, .5f); } entity.matrix.postScale(entity.width * W, entity.height * H); entity.matrix.postTranslate(entity.x * W, entity.y * H); entity.matrix.postRotate((float) (-entity.rotation / Math.PI * 180), (entity.x + entity.width / 2f) * W, (entity.y + entity.height / 2f) * H); } Path path; Paint xRefPaint; Paint textColorPaint; private void applyRoundRadius(VideoEditedInfo.MediaEntity entity, Bitmap stickerBitmap, int color) { if (stickerBitmap == null || entity == null || entity.roundRadius == 0 && color == 0) { return; } if (entity.roundRadiusCanvas == null) { entity.roundRadiusCanvas = new Canvas(stickerBitmap); } if (entity.roundRadius != 0) { if (path == null) { path = new Path(); } if (xRefPaint == null) { xRefPaint = new Paint(Paint.ANTI_ALIAS_FLAG); xRefPaint.setColor(0xff000000); xRefPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); } float rad = Math.min(stickerBitmap.getWidth(), stickerBitmap.getHeight()) * entity.roundRadius; path.rewind(); RectF rect = new RectF(0, 0, stickerBitmap.getWidth(), stickerBitmap.getHeight()); path.addRoundRect(rect, rad, rad, Path.Direction.CCW); path.toggleInverseFillType(); entity.roundRadiusCanvas.drawPath(path, xRefPaint); } if (color != 0) { if (textColorPaint == null) { textColorPaint = new Paint(Paint.ANTI_ALIAS_FLAG); textColorPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); } textColorPaint.setColor(color); entity.roundRadiusCanvas.drawRect(0, 0, stickerBitmap.getWidth(), stickerBitmap.getHeight(), textColorPaint); } } } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/messenger/video/WebmEncoder.java
41,664
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.messenger.camera; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ImageFormat; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.SurfaceTexture; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.hardware.Camera; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaFormat; import android.media.MediaRecorder; import android.opengl.EGL14; import android.opengl.EGLExt; import android.opengl.GLES11Ext; import android.opengl.GLES20; import android.opengl.GLUtils; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.VibrationEffect; import android.os.Vibrator; import android.view.Gravity; import android.view.HapticFeedbackConstants; import android.view.Surface; import android.view.TextureView; import android.view.View; import android.view.animation.DecelerateInterpolator; import android.widget.FrameLayout; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.core.graphics.ColorUtils; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.BuildVars; import org.telegram.messenger.DispatchQueue; import org.telegram.messenger.FileLog; import org.telegram.messenger.ImageLoader; import org.telegram.messenger.MessagesController; import org.telegram.messenger.R; import org.telegram.messenger.SharedConfig; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; import org.telegram.messenger.video.MP4Builder; import org.telegram.messenger.video.MediaCodecVideoConvertor; import org.telegram.messenger.video.Mp4Movie; import org.telegram.ui.Components.AnimatedFloat; import org.telegram.ui.Components.CubicBezierInterpolator; import org.telegram.ui.Components.InstantCameraView; import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.RLottieDrawable; import java.io.File; import java.io.IOException; import java.lang.ref.WeakReference; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.util.ArrayList; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL; @SuppressLint("NewApi") public class CameraView extends FrameLayout implements TextureView.SurfaceTextureListener, CameraController.ICameraView, CameraController.ErrorCallback { public boolean WRITE_TO_FILE_IN_BACKGROUND = false; public boolean isStory; private float scaleX, scaleY; private Size[] previewSize = new Size[2]; private Size[] pictureSize = new Size[2]; CameraInfo[] info = new CameraInfo[2]; private boolean mirror; private boolean lazy; private TextureView textureView; private ImageView blurredStubView; private boolean inited; private CameraViewDelegate delegate; private int clipTop; private int clipBottom; private boolean isFrontface; private Matrix txform = new Matrix(); private Matrix matrix = new Matrix(); private int focusAreaSize; private Drawable thumbDrawable; private final boolean useCamera2 = false && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && SharedConfig.isUsingCamera2(UserConfig.selectedAccount); private final CameraSessionWrapper[] cameraSession = new CameraSessionWrapper[2]; private CameraSessionWrapper cameraSessionRecording; private boolean useMaxPreview; private long lastDrawTime; private float focusProgress = 1.0f; private float innerAlpha; private float outerAlpha; private boolean initialFrontface; private int cx; private int cy; private Paint outerPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private Paint innerPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private boolean optimizeForBarcode; File recordFile; private DecelerateInterpolator interpolator = new DecelerateInterpolator(); private volatile int surfaceWidth; private volatile int surfaceHeight; private File cameraFile; boolean firstFrameRendered; boolean firstFrame2Rendered; private final Object layoutLock = new Object(); private float[][] mMVPMatrix = new float[2][16]; private float[][] mSTMatrix = new float[2][16]; private float[][] moldSTMatrix = new float[2][16]; private FloatBuffer vertexBuffer; private FloatBuffer textureBuffer; private float[][] cameraMatrix = new float[2][16]; private volatile float lastCrossfadeValue = 0; private final static int audioSampleRate = 44100; public void setRecordFile(File generateVideoPath) { recordFile = generateVideoPath; } Runnable onRecordingFinishRunnable; public boolean startRecording(File path, Runnable onFinished) { cameraSessionRecording = cameraSession[0]; cameraThread.startRecording(path); onRecordingFinishRunnable = onFinished; return true; } public void stopRecording() { cameraThread.stopRecording(); } ValueAnimator flipAnimator; boolean flipHalfReached; boolean flipping = false; private int fpsLimit = -1; long nextFrameTimeNs; public void startSwitchingAnimation() { if (flipAnimator != null) { flipAnimator.cancel(); } blurredStubView.animate().setListener(null).cancel(); if (firstFrameRendered) { Bitmap bitmap = textureView.getBitmap(100, 100); if (bitmap != null) { Utilities.blurBitmap(bitmap, 3, 1, bitmap.getWidth(), bitmap.getHeight(), bitmap.getRowBytes()); Drawable drawable = new BitmapDrawable(bitmap); blurredStubView.setBackground(drawable); } } blurredStubView.setAlpha(1f); blurredStubView.setVisibility(View.VISIBLE); flipHalfReached = false; flipping = true; flipAnimator = ValueAnimator.ofFloat(0, 1f); textureView.setCameraDistance(textureView.getMeasuredHeight() * 4f); blurredStubView.setCameraDistance(blurredStubView.getMeasuredHeight() * 4f); flipAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { float v = (float) valueAnimator.getAnimatedValue(); float rotation; boolean halfReached = false; if (v < 0.5f) { rotation = v; } else { halfReached = true; rotation = v - 1f; } rotation *= 180; textureView.setRotationY(rotation); blurredStubView.setRotationY(rotation); if (halfReached && !flipHalfReached) { // blurredStubView.setAlpha(1f); flipHalfReached = true; } } }); flipAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); flipAnimator = null; textureView.setTranslationY(0); textureView.setRotationX(0); textureView.setRotationY(0); textureView.setScaleX(1f); textureView.setScaleY(1f); blurredStubView.setRotationY(0); if (!flipHalfReached) { // blurredStubView.setAlpha(1f); flipHalfReached = true; } invalidate(); } }); flipAnimator.setDuration(500); flipAnimator.setInterpolator(CubicBezierInterpolator.DEFAULT); flipAnimator.start(); invalidate(); } protected boolean dual; private boolean dualCameraAppeared; private Matrix dualMatrix = new Matrix(); private long toggleDualUntil; private boolean closingDualCamera; private boolean initFirstCameraAfterSecond; public boolean toggledDualAsSave; public boolean isDual() { return dual; } private void enableDualInternal() { if (cameraSession[1] != null) { if (closingDualCamera) { return; } closingDualCamera = true; cameraSession[1].destroy(false, null, () -> { closingDualCamera = false; enableDualInternal(); }); if (cameraSessionRecording == cameraSession[1]) { cameraSessionRecording = null; } cameraSession[1] = null; addToDualWait(400L); return; } if (!isFrontface && "samsung".equalsIgnoreCase(Build.MANUFACTURER) && !toggledDualAsSave && cameraSession[0] != null) { final Handler handler = cameraThread.getHandler(); if (handler != null) { cameraThread.sendMessage(handler.obtainMessage(cameraThread.BLUR_CAMERA1), 0); } cameraSession[0].destroy(false, null, () -> { initFirstCameraAfterSecond = true; updateCameraInfoSize(1); if (handler != null) { cameraThread.sendMessage(handler.obtainMessage(cameraThread.DO_DUAL_START, info[1].cameraId, 0, dualMatrix), 0); } addToDualWait(1200L); }); cameraSession[0] = null; return; } updateCameraInfoSize(1); final Handler handler = cameraThread.getHandler(); if (handler != null) { cameraThread.sendMessage(handler.obtainMessage(cameraThread.DO_DUAL_START, info[1].cameraId, 0, dualMatrix), 0); } addToDualWait(800L); } public void toggleDual() { toggleDual(false); } public void toggleDual(boolean force) { if (!force && (flipping || closingDualCamera || (System.currentTimeMillis() < toggleDualUntil || dual != dualCameraAppeared) && !dual)) { return; } addToDualWait(200L); dual = !dual; if (dual) { if (cameraSession[0] != null) { cameraSession[0].setCurrentFlashMode(Camera.Parameters.FLASH_MODE_OFF); } enableDualInternal(); } else { if (cameraSession[1] == null || !cameraSession[1].isInitiated()) { dual = !dual; return; } if (cameraSession[1] != null) { closingDualCamera = true; if (cameraSessionRecording == cameraSession[1]) { cameraSessionRecording = null; } cameraSession[1].destroy(false, null, () -> { closingDualCamera = false; dualCameraAppeared = false; addToDualWait(400L); final Handler handler = cameraThread.getHandler(); if (handler != null) { cameraThread.sendMessage(handler.obtainMessage(cameraThread.DO_DUAL_END), 0); } }); cameraSession[1] = null; previewSize[1] = null; pictureSize[1] = null; info[1] = null; } else { dualCameraAppeared = false; } if (!closingDualCamera) { final Handler handler = cameraThread.getHandler(); if (handler != null) { cameraThread.sendMessage(handler.obtainMessage(cameraThread.DO_DUAL_END), 0); } } } toggledDualAsSave = false; } private void addToDualWait(long add) { final long now = System.currentTimeMillis(); if (toggleDualUntil < now) { toggleDualUntil = now + add; } else { toggleDualUntil += add; } } public Matrix getDualPosition() { return dualMatrix; } public void updateDualPosition() { if (cameraThread == null) { return; } final Handler handler = cameraThread.getHandler(); if (handler != null) { cameraThread.sendMessage(handler.obtainMessage(cameraThread.DO_DUAL_MOVE, dualMatrix), 0); } } public interface CameraViewDelegate { void onCameraInit(); } public CameraView(Context context, boolean frontface) { this(context, frontface, false); } public CameraView(Context context, boolean frontface, boolean lazy) { super(context, null); CameraController.getInstance().addOnErrorListener(this); initialFrontface = isFrontface = frontface; textureView = new TextureView(context); if (!(this.lazy = lazy)) { initTexture(); } setWillNotDraw(!lazy); blurredStubView = new ImageView(context); addView(blurredStubView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER)); blurredStubView.setVisibility(View.GONE); focusAreaSize = AndroidUtilities.dp(96); outerPaint.setColor(0xffffffff); outerPaint.setStyle(Paint.Style.STROKE); outerPaint.setStrokeWidth(AndroidUtilities.dp(2)); innerPaint.setColor(0x7fffffff); } private boolean textureInited = false; public void initTexture() { if (textureInited) { return; } textureView.setSurfaceTextureListener(this); addView(textureView, 0, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER)); textureInited = true; } public void setOptimizeForBarcode(boolean value) { optimizeForBarcode = value; if (cameraSession[0] != null) { cameraSession[0].setOptimizeForBarcode(true); } } Rect bounds = new Rect(); @Override protected void onDraw(Canvas canvas) { if (thumbDrawable != null) { bounds.set(0, 0, getMeasuredWidth(), getMeasuredHeight()); int W = thumbDrawable.getIntrinsicWidth(), H = thumbDrawable.getIntrinsicHeight(); float scale = 1f / Math.min(W / (float) Math.max(1, bounds.width()), H / (float) Math.max(1, bounds.height())); thumbDrawable.setBounds( (int) (bounds.centerX() - W * scale / 2f), (int) (bounds.centerY() - H * scale / 2f), (int) (bounds.centerX() + W * scale / 2f), (int) (bounds.centerY() + H * scale / 2f) ); thumbDrawable.draw(canvas); } super.onDraw(canvas); } @Override protected boolean verifyDrawable(@NonNull Drawable who) { return who == thumbDrawable || super.verifyDrawable(who); } public void setThumbDrawable(Drawable drawable) { if (thumbDrawable != null) { thumbDrawable.setCallback(null); } thumbDrawable = drawable; if (thumbDrawable != null) { thumbDrawable.setCallback(this); } if (!firstFrameRendered) { blurredStubView.animate().setListener(null).cancel(); blurredStubView.setBackground(thumbDrawable); blurredStubView.setAlpha(1f); blurredStubView.setVisibility(View.VISIBLE); } } private int measurementsCount = 0; @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); measurementsCount = 0; } private int lastWidth = -1, lastHeight = -1; @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = MeasureSpec.getSize(widthMeasureSpec), height = MeasureSpec.getSize(heightMeasureSpec); if (previewSize[0] != null && cameraSession[0] != null) { int frameWidth, frameHeight; if ((lastWidth != width || lastHeight != height) && measurementsCount > 1) { cameraSession[0].updateRotation(); } measurementsCount++; if (cameraSession[0].getWorldAngle() == 90 || cameraSession[0].getWorldAngle() == 270) { frameWidth = previewSize[0].getWidth(); frameHeight = previewSize[0].getHeight(); } else { frameWidth = previewSize[0].getHeight(); frameHeight = previewSize[0].getWidth(); } float s = Math.max(MeasureSpec.getSize(widthMeasureSpec) / (float) frameWidth , MeasureSpec.getSize(heightMeasureSpec) / (float) frameHeight); blurredStubView.getLayoutParams().width = textureView.getLayoutParams().width = (int) (s * frameWidth); blurredStubView.getLayoutParams().height = textureView.getLayoutParams().height = (int) (s * frameHeight); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); checkPreviewMatrix(); lastWidth = width; lastHeight = height; pixelW = getMeasuredWidth(); pixelH = getMeasuredHeight(); if (pixelDualW <= 0) { pixelDualW = getMeasuredWidth(); pixelDualH = getMeasuredHeight(); } } public float getTextureHeight(float width, float height) { if (previewSize[0] == null || cameraSession[0] == null) { return height; } int frameWidth, frameHeight; if (cameraSession[0].getWorldAngle() == 90 || cameraSession[0].getWorldAngle() == 270) { frameWidth = previewSize[0].getWidth(); frameHeight = previewSize[0].getHeight(); } else { frameWidth = previewSize[0].getHeight(); frameHeight = previewSize[0].getWidth(); } float s = Math.max(width / (float) frameWidth , height / (float) frameHeight); return (int) (s * frameHeight); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); checkPreviewMatrix(); } public void setMirror(boolean value) { mirror = value; } public boolean isFrontface() { return isFrontface; } public TextureView getTextureView() { return textureView; } public void setUseMaxPreview(boolean value) { useMaxPreview = value; } public boolean hasFrontFaceCamera() { ArrayList<CameraInfo> cameraInfos = CameraController.getInstance().getCameras(); for (int a = 0; a < cameraInfos.size(); a++) { if (cameraInfos.get(a).frontCamera != 0) { return true; } } return false; } private Integer shape; public void dualToggleShape() { if (flipping || !dual) { return; } Handler handler = cameraThread.getHandler(); if (shape == null) { shape = MessagesController.getGlobalMainSettings().getInt("dualshape", 0); } shape++; MessagesController.getGlobalMainSettings().edit().putInt("dualshape", shape).apply(); if (handler != null) { handler.sendMessage(handler.obtainMessage(cameraThread.DO_DUAL_TOGGLE_SHAPE)); } } public int getDualShape() { if (shape == null) { shape = MessagesController.getGlobalMainSettings().getInt("dualshape", 0); } return shape; } private long lastDualSwitchTime; public void switchCamera() { if (flipping || System.currentTimeMillis() < toggleDualUntil && !dualCameraAppeared) { return; } if (dual) { if (!dualCameraAppeared || System.currentTimeMillis() - lastDualSwitchTime < 420) { return; } lastDualSwitchTime = System.currentTimeMillis(); CameraInfo info0 = info[0]; info[0] = info[1]; info[1] = info0; Size previewSize0 = previewSize[0]; previewSize[0] = previewSize[1]; previewSize[1] = previewSize0; Size pictureSize0 = pictureSize[0]; pictureSize[0] = pictureSize[1]; pictureSize[1] = pictureSize0; CameraSessionWrapper cameraSession0 = cameraSession[0]; cameraSession[0] = cameraSession[1]; cameraSession[1] = cameraSession0; isFrontface = !isFrontface; Handler handler = cameraThread.getHandler(); if (handler != null) { handler.sendMessage(handler.obtainMessage(cameraThread.DO_DUAL_FLIP)); } return; } startSwitchingAnimation(); if (cameraSession[0] != null) { if (cameraSessionRecording == cameraSession[0]) { cameraSessionRecording = null; } cameraSession[0].destroy(false, null, () -> { inited = false; synchronized (layoutLock) { firstFrameRendered = false; } updateCameraInfoSize(0); cameraThread.reinitForNewCamera(); }); cameraSession[0] = null; } isFrontface = !isFrontface; } public void resetCamera() { if (cameraSession[0] != null) { if (cameraSessionRecording == cameraSession[0]) { cameraSessionRecording = null; } final Handler handler = cameraThread.getHandler(); if (handler != null) { cameraThread.sendMessage(handler.obtainMessage(cameraThread.BLUR_CAMERA1), 0); } cameraSession[0].destroy(false, null, () -> { inited = false; synchronized (layoutLock) { firstFrameRendered = false; } updateCameraInfoSize(0); cameraThread.reinitForNewCamera(); }); cameraSession[0] = null; } } public Size getPreviewSize() { return previewSize[0]; } protected CameraGLThread cameraThread; @Override public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { updateCameraInfoSize(0); if (dual) { updateCameraInfoSize(1); } surfaceHeight = height; surfaceWidth = width; if (cameraThread == null && surface != null) { if (BuildVars.LOGS_ENABLED) { FileLog.d("CameraView " + "start create thread"); } cameraThread = new CameraGLThread(surface); checkPreviewMatrix(); } } protected boolean square() { return false; } private void updateCameraInfoSize(int i) { ArrayList<CameraInfo> cameraInfos = CameraController.getInstance().getCameras(); if (cameraInfos == null) { return; } for (int a = 0; a < cameraInfos.size(); a++) { CameraInfo cameraInfo = cameraInfos.get(a); boolean cameraInfoIsFrontface = cameraInfo.frontCamera != 0; boolean shouldBeFrontface = isFrontface; if (i == 1) { shouldBeFrontface = !shouldBeFrontface; } if (cameraInfoIsFrontface == shouldBeFrontface) { info[i] = cameraInfo; break; } } if (info[i] == null) { return; } float size4to3 = 4.0f / 3.0f; float size16to9 = 16.0f / 9.0f; float screenSize = (float) Math.max(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) / Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y); org.telegram.messenger.camera.Size aspectRatio; int wantedWidth; int wantedHeight; int photoMaxWidth; int photoMaxHeight; if (square()) { aspectRatio = new Size(1, 1); photoMaxWidth = wantedWidth = 720; photoMaxHeight = wantedHeight = 720; } else if (initialFrontface) { aspectRatio = new Size(16, 9); photoMaxWidth = wantedWidth = 1280; photoMaxHeight = wantedHeight = 720; } else { if (Math.abs(screenSize - size4to3) < 0.1f) { aspectRatio = new Size(4, 3); wantedWidth = 1280; wantedHeight = 960; if (SharedConfig.getDevicePerformanceClass() == SharedConfig.PERFORMANCE_CLASS_LOW) { photoMaxWidth = 1280; photoMaxHeight = 960; } else { photoMaxWidth = 1920; photoMaxHeight = 1440; } } else { aspectRatio = new Size(16, 9); wantedWidth = 1280; wantedHeight = 720; if (SharedConfig.getDevicePerformanceClass() == SharedConfig.PERFORMANCE_CLASS_LOW) { photoMaxWidth = 1280; photoMaxHeight = 960; } else { photoMaxWidth = isStory ? 1280 : 1920; photoMaxHeight = isStory ? 720 : 1080; } } } previewSize[i] = CameraController.chooseOptimalSize(info[i].getPreviewSizes(), wantedWidth, wantedHeight, aspectRatio, isStory); pictureSize[i] = CameraController.chooseOptimalSize(info[i].getPictureSizes(), photoMaxWidth, photoMaxHeight, aspectRatio, false); if (BuildVars.LOGS_ENABLED) { FileLog.d("camera preview " + previewSize[0]); } requestLayout(); } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int surfaceW, int surfaceH) { surfaceHeight = surfaceH; surfaceWidth = surfaceW; checkPreviewMatrix(); } @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) { if (cameraThread != null) { cameraThread.shutdown(0); cameraThread.postRunnable(() -> this.cameraThread = null); } if (cameraSession[0] != null) { cameraSession[0].destroy(false, null, null); } if (cameraSession[1] != null) { cameraSession[1].destroy(false, null, null); } return false; } @Override public void onSurfaceTextureUpdated(SurfaceTexture surface) { if (!inited && cameraSession[0] != null && cameraSession[0].isInitiated()) { if (delegate != null) { delegate.onCameraInit(); } inited = true; if (lazy) { textureView.setAlpha(0); showTexture(true, true); } } } private ValueAnimator textureViewAnimator; public void showTexture(boolean show, boolean animated) { if (textureView == null) { return; } if (textureViewAnimator != null) { textureViewAnimator.cancel(); textureViewAnimator = null; } if (animated) { textureViewAnimator = ValueAnimator.ofFloat(textureView.getAlpha(), show ? 1 : 0); textureViewAnimator.addUpdateListener(anm -> { final float t = (float) anm.getAnimatedValue(); textureView.setAlpha(t); }); textureViewAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { textureView.setAlpha(show ? 1 : 0); textureViewAnimator = null; } }); textureViewAnimator.start(); } else { textureView.setAlpha(show ? 1 : 0); } } public void setClipTop(int value) { clipTop = value; } public void setClipBottom(int value) { clipBottom = value; } private final Runnable updateRotationMatrix = () -> { final CameraGLThread cameraThread = this.cameraThread; if (cameraThread != null) { for (int i = 0; i < 2; ++i) { if (cameraThread.currentSession[i] != null) { int rotationAngle = cameraThread.currentSession[i].getWorldAngle(); android.opengl.Matrix.setIdentityM(mMVPMatrix[i], 0); if (rotationAngle != 0) { android.opengl.Matrix.rotateM(mMVPMatrix[i], 0, rotationAngle, 0, 0, 1); } } } } }; private void checkPreviewMatrix() { if (previewSize[0] == null || textureView == null) { return; } int viewWidth = textureView.getWidth(); int viewHeight = textureView.getHeight(); Matrix matrix = new Matrix(); if (cameraSession[0] != null) { matrix.postRotate(cameraSession[0].getDisplayOrientation()); } matrix.postScale(viewWidth / 2000f, viewHeight / 2000f); matrix.postTranslate(viewWidth / 2f, viewHeight / 2f); matrix.invert(this.matrix); if (cameraThread != null) { if (!cameraThread.isReady()) { updateRotationMatrix.run(); } else { cameraThread.postRunnable(updateRotationMatrix); } } } private Rect calculateTapArea(float x, float y, float coefficient) { int areaSize = Float.valueOf(focusAreaSize * coefficient).intValue(); int left = clamp((int) x - areaSize / 2, 0, getWidth() - areaSize); int top = clamp((int) y - areaSize / 2, 0, getHeight() - areaSize); RectF rectF = new RectF(left, top, left + areaSize, top + areaSize); matrix.mapRect(rectF); return new Rect(Math.round(rectF.left), Math.round(rectF.top), Math.round(rectF.right), Math.round(rectF.bottom)); } private int clamp(int x, int min, int max) { if (x > max) { return max; } if (x < min) { return min; } return x; } public void focusToPoint(int x, int y, boolean visible) { focusToPoint(0, x, y, x, y, visible); } public void focusToPoint(int i, int x, int y, int vx, int vy, boolean visible) { Rect focusRect = calculateTapArea(x, y, 1f); Rect meteringRect = calculateTapArea(x, y, 1.5f); if (cameraSession[i] != null) { cameraSession[i].focusToRect(focusRect, meteringRect); } if (visible) { focusProgress = 0.0f; innerAlpha = 1.0f; outerAlpha = 1.0f; cx = vx; cy = vy; lastDrawTime = System.currentTimeMillis(); invalidate(); } } public void focusToPoint(int x, int y) { focusToPoint(x, y, true); } public void setZoom(float value) { if (cameraSession[0] != null) { cameraSession[0].setZoom(value); } } public void setDelegate(CameraViewDelegate cameraViewDelegate) { delegate = cameraViewDelegate; } public boolean isInited() { return inited; } public CameraSessionWrapper getCameraSession() { return getCameraSession(0); } public Object getCameraSessionObject() { if (cameraSession[0] == null) return null; return cameraSession[0].getObject(); } public CameraSessionWrapper getCameraSession(int i) { return cameraSession[i]; } public CameraSessionWrapper getCameraSessionRecording() { return cameraSessionRecording; } public void destroy(boolean async, final Runnable beforeDestroyRunnable) { for (int i = 0; i < 2; ++i) { if (cameraSession[i] != null) { cameraSession[i].destroy(async, beforeDestroyRunnable, null); } } CameraController.getInstance().removeOnErrorListener(this); } public Matrix getMatrix() { return txform; } @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { boolean result = super.drawChild(canvas, child, drawingTime); if (focusProgress != 1.0f || innerAlpha != 0.0f || outerAlpha != 0.0f) { int baseRad = AndroidUtilities.dp(30); long newTime = System.currentTimeMillis(); long dt = newTime - lastDrawTime; if (dt < 0 || dt > 17) { dt = 17; } lastDrawTime = newTime; outerPaint.setAlpha((int) (interpolator.getInterpolation(outerAlpha) * 255)); innerPaint.setAlpha((int) (interpolator.getInterpolation(innerAlpha) * 127)); float interpolated = interpolator.getInterpolation(focusProgress); canvas.drawCircle(cx, cy, baseRad + baseRad * (1.0f - interpolated), outerPaint); canvas.drawCircle(cx, cy, baseRad * interpolated, innerPaint); if (focusProgress < 1) { focusProgress += dt / 200.0f; if (focusProgress > 1) { focusProgress = 1; } invalidate(); } else if (innerAlpha != 0) { innerAlpha -= dt / 150.0f; if (innerAlpha < 0) { innerAlpha = 0; } invalidate(); } else if (outerAlpha != 0) { outerAlpha -= dt / 150.0f; if (outerAlpha < 0) { outerAlpha = 0; } invalidate(); } } return result; } private float takePictureProgress = 1f; public void startTakePictureAnimation(boolean haptic) { takePictureProgress = 0; invalidate(); if (haptic) { runHaptic(); } } public void runHaptic() { long[] vibrationWaveFormDurationPattern = {0, 1}; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { final Vibrator vibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE); VibrationEffect vibrationEffect = VibrationEffect.createWaveform(vibrationWaveFormDurationPattern, -1); vibrator.cancel(); vibrator.vibrate(vibrationEffect); } else { performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING); } } @Override protected void dispatchDraw(Canvas canvas) { if (flipAnimator != null) { canvas.drawColor(Color.BLACK); } super.dispatchDraw(canvas); if (takePictureProgress != 1f) { takePictureProgress += 16 / 150f; if (takePictureProgress > 1f) { takePictureProgress = 1f; } else { invalidate(); } canvas.drawColor(ColorUtils.setAlphaComponent(Color.BLACK, (int) ((1f - takePictureProgress) * 150))); } } private int videoWidth; private int videoHeight; public int getVideoWidth() { return videoWidth; } public int getVideoHeight() { return videoHeight; } private int[] position = new int[2]; private int[][] cameraTexture = new int[2][1]; private int[] oldCameraTexture = new int[1]; private VideoRecorder videoEncoder; private volatile float pixelW, pixelH; private volatile float pixelDualW, pixelDualH; private volatile float lastShapeTo; private volatile float shapeValue; public class CameraGLThread extends DispatchQueue { private final static int EGL_CONTEXT_CLIENT_VERSION = 0x3098; private final static int EGL_OPENGL_ES2_BIT = 4; private SurfaceTexture surfaceTexture; private EGL10 egl10; private EGLDisplay eglDisplay; private EGLContext eglContext; private EGLSurface eglSurface; private EGLConfig eglConfig; private boolean initied; private final CameraSessionWrapper currentSession[] = new CameraSessionWrapper[2]; private final SurfaceTexture[] cameraSurface = new SurfaceTexture[2]; private final int DO_RENDER_MESSAGE = 0; private final int DO_SHUTDOWN_MESSAGE = 1; private final int DO_REINIT_MESSAGE = 2; private final int DO_SETSESSION_MESSAGE = 3; private final int DO_START_RECORDING = 4; private final int DO_STOP_RECORDING = 5; private final int DO_DUAL_START = 6; private final int DO_DUAL_MOVE = 7; private final int DO_DUAL_FLIP = 8; private final int DO_DUAL_TOGGLE_SHAPE = 9; private final int DO_DUAL_END = 10; private final int BLUR_CAMERA1 = 11; private int drawProgram; private int vertexMatrixHandle; private int textureMatrixHandle; private int cameraMatrixHandle; private int oppositeCameraMatrixHandle; private int positionHandle; private int textureHandle; private int roundRadiusHandle; private int pixelHandle; private int dualHandle; private int scaleHandle; private int blurHandle; private int alphaHandle; private int crossfadeHandle; private int shapeFromHandle; private int shapeToHandle; private int shapeHandle; private boolean initDual, initDualReverse; private Matrix initDualMatrix; private boolean recording; private boolean needRecord; private int cameraId[] = new int[] { -1, -1 }; private final float[] verticesData = { -1.0f, -1.0f, 0, 1.0f, -1.0f, 0, -1.0f, 1.0f, 0, 1.0f, 1.0f, 0 }; //private InstantCameraView.VideoRecorder videoEncoder; public CameraGLThread(SurfaceTexture surface) { super("CameraGLThread"); surfaceTexture = surface; initDual = dual; initDualReverse = !isFrontface; initDualMatrix = dualMatrix; } private boolean initGL() { if (BuildVars.LOGS_ENABLED) { FileLog.d("CameraView " + "start init gl"); } egl10 = (EGL10) EGLContext.getEGL(); eglDisplay = egl10.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); if (eglDisplay == EGL10.EGL_NO_DISPLAY) { if (BuildVars.LOGS_ENABLED) { FileLog.e("eglGetDisplay failed " + GLUtils.getEGLErrorString(egl10.eglGetError())); } eglDisplay = null; finish(); return false; } int[] version = new int[2]; if (!egl10.eglInitialize(eglDisplay, version)) { if (BuildVars.LOGS_ENABLED) { FileLog.e("eglInitialize failed " + GLUtils.getEGLErrorString(egl10.eglGetError())); } finish(); return false; } int[] configsCount = new int[1]; EGLConfig[] configs = new EGLConfig[1]; int[] configSpec = new int[]{ EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL10.EGL_RED_SIZE, 8, EGL10.EGL_GREEN_SIZE, 8, EGL10.EGL_BLUE_SIZE, 8, EGL10.EGL_ALPHA_SIZE, 0, EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_STENCIL_SIZE, 0, EGL10.EGL_NONE }; if (!egl10.eglChooseConfig(eglDisplay, configSpec, configs, 1, configsCount)) { if (BuildVars.LOGS_ENABLED) { FileLog.e("eglChooseConfig failed " + GLUtils.getEGLErrorString(egl10.eglGetError())); } finish(); return false; } else if (configsCount[0] > 0) { eglConfig = configs[0]; } else { if (BuildVars.LOGS_ENABLED) { FileLog.e("eglConfig not initialized"); } finish(); return false; } int[] attrib_list = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE}; eglContext = egl10.eglCreateContext(eglDisplay, eglConfig, EGL10.EGL_NO_CONTEXT, attrib_list); if (eglContext == null || eglContext == EGL10.EGL_NO_CONTEXT) { eglContext = null; if (BuildVars.LOGS_ENABLED) { FileLog.e("eglCreateContext failed " + GLUtils.getEGLErrorString(egl10.eglGetError())); } finish(); return false; } if (surfaceTexture != null) { eglSurface = egl10.eglCreateWindowSurface(eglDisplay, eglConfig, surfaceTexture, null); } else { finish(); return false; } if (eglSurface == null || eglSurface == EGL10.EGL_NO_SURFACE) { if (BuildVars.LOGS_ENABLED) { FileLog.e("createWindowSurface failed " + GLUtils.getEGLErrorString(egl10.eglGetError())); } finish(); return false; } if (!egl10.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)) { if (BuildVars.LOGS_ENABLED) { FileLog.e("eglMakeCurrent failed " + GLUtils.getEGLErrorString(egl10.eglGetError())); } finish(); return false; } GL gl = eglContext.getGL(); android.opengl.Matrix.setIdentityM(mSTMatrix[0], 0); int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, RLottieDrawable.readRes(null, R.raw.camera_vert)); int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, RLottieDrawable.readRes(null, R.raw.camera_frag)); if (vertexShader != 0 && fragmentShader != 0) { drawProgram = GLES20.glCreateProgram(); GLES20.glAttachShader(drawProgram, vertexShader); GLES20.glAttachShader(drawProgram, fragmentShader); GLES20.glLinkProgram(drawProgram); int[] linkStatus = new int[1]; GLES20.glGetProgramiv(drawProgram, GLES20.GL_LINK_STATUS, linkStatus, 0); if (linkStatus[0] == 0) { if (BuildVars.LOGS_ENABLED) { FileLog.e("failed link shader"); } GLES20.glDeleteProgram(drawProgram); drawProgram = 0; } else { positionHandle = GLES20.glGetAttribLocation(drawProgram, "aPosition"); textureHandle = GLES20.glGetAttribLocation(drawProgram, "aTextureCoord"); vertexMatrixHandle = GLES20.glGetUniformLocation(drawProgram, "uMVPMatrix"); textureMatrixHandle = GLES20.glGetUniformLocation(drawProgram, "uSTMatrix"); cameraMatrixHandle = GLES20.glGetUniformLocation(drawProgram, "cameraMatrix"); oppositeCameraMatrixHandle = GLES20.glGetUniformLocation(drawProgram, "oppositeCameraMatrix"); roundRadiusHandle = GLES20.glGetUniformLocation(drawProgram, "roundRadius"); pixelHandle = GLES20.glGetUniformLocation(drawProgram, "pixelWH"); dualHandle = GLES20.glGetUniformLocation(drawProgram, "dual"); scaleHandle = GLES20.glGetUniformLocation(drawProgram, "scale"); blurHandle = GLES20.glGetUniformLocation(drawProgram, "blur"); alphaHandle = GLES20.glGetUniformLocation(drawProgram, "alpha"); crossfadeHandle = GLES20.glGetUniformLocation(drawProgram, "crossfade"); shapeFromHandle = GLES20.glGetUniformLocation(drawProgram, "shapeFrom"); shapeToHandle = GLES20.glGetUniformLocation(drawProgram, "shapeTo"); shapeHandle = GLES20.glGetUniformLocation(drawProgram, "shapeT"); } } else { if (BuildVars.LOGS_ENABLED) { FileLog.e("failed creating shader"); } finish(); return false; } GLES20.glGenTextures(1, cameraTexture[0], 0); GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, cameraTexture[0][0]); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); GLES20.glEnable(GLES20.GL_BLEND); GLES20.glBlendFuncSeparate(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA, GLES20.GL_ONE, GLES20.GL_ONE_MINUS_SRC_ALPHA); android.opengl.Matrix.setIdentityM(mMVPMatrix[0], 0); if (BuildVars.LOGS_ENABLED) { FileLog.e("gl initied"); } updateScale(0); float tX = 1.0f / scaleX / 2.0f; float tY = 1.0f / scaleY / 2.0f; float[] texData = { 0.5f - tX, 0.5f - tY, 0.5f + tX, 0.5f - tY, 0.5f - tX, 0.5f + tY, 0.5f + tX, 0.5f + tY }; vertexBuffer = ByteBuffer.allocateDirect(verticesData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer(); vertexBuffer.put(verticesData).position(0); textureBuffer = ByteBuffer.allocateDirect(texData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer(); textureBuffer.put(texData).position(0); cameraSurface[0] = new SurfaceTexture(cameraTexture[0][0]); cameraSurface[0].setOnFrameAvailableListener(this::updTex); if (initDual) { GLES20.glGenTextures(1, cameraTexture[1], 0); GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, cameraTexture[1][0]); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); cameraSurface[1] = new SurfaceTexture(cameraTexture[1][0]); cameraSurface[1].setOnFrameAvailableListener(this::updTex); } if (initDual) { if (initDualReverse) { createCamera(cameraSurface[1], 1); createCamera(cameraSurface[0], 0); } else { createCamera(cameraSurface[0], 0); createCamera(cameraSurface[1], 1); } } else { createCamera(cameraSurface[0], 0); } Matrix simpleMatrix = new Matrix(); simpleMatrix.reset(); getValues(simpleMatrix, cameraMatrix[0]); if (initDualMatrix != null) { getValues(initDualMatrix, cameraMatrix[1]); } else { getValues(simpleMatrix, cameraMatrix[1]); } lastShapeTo = shapeTo; return true; } private void updTex(SurfaceTexture surfaceTexture) { if (surfaceTexture == cameraSurface[0]) { if (!ignoreCamera1Upd && System.currentTimeMillis() > camera1AppearedUntil) { camera1Appeared = true; } requestRender(true, false); } else if (surfaceTexture == cameraSurface[1]) { if (!dualAppeared) { synchronized (layoutLock) { dualCameraAppeared = true; addToDualWait(1200L); } } dualAppeared = true; requestRender(false, true); } } public void reinitForNewCamera() { Handler handler = getHandler(); if (handler != null) { sendMessage(handler.obtainMessage(DO_REINIT_MESSAGE, info[0].cameraId), 0); } } public void finish() { if (cameraSurface != null) { for (int i = 0; i < cameraSurface.length; ++i) { if (cameraSurface[i] != null) { cameraSurface[i].setOnFrameAvailableListener(null); cameraSurface[i].release(); cameraSurface[i] = null; } } } if (eglSurface != null) { egl10.eglMakeCurrent(eglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); egl10.eglDestroySurface(eglDisplay, eglSurface); eglSurface = null; } if (eglContext != null) { egl10.eglDestroyContext(eglDisplay, eglContext); eglContext = null; } if (eglDisplay != null) { egl10.eglTerminate(eglDisplay); eglDisplay = null; } } public void setCurrentSession(CameraSessionWrapper session, int i) { Handler handler = getHandler(); if (handler != null) { sendMessage(handler.obtainMessage(DO_SETSESSION_MESSAGE, i, 0, session), 0); } } private boolean crossfading; private final AnimatedFloat crossfade = new AnimatedFloat(() -> this.requestRender(false, false), 560, CubicBezierInterpolator.EASE_OUT_QUINT); private final AnimatedFloat camera1Appear = new AnimatedFloat(1f, () -> this.requestRender(false, false), 0, 420, CubicBezierInterpolator.EASE_OUT_QUINT); private final AnimatedFloat dualAppear = new AnimatedFloat(() -> this.requestRender(false, false), 340, CubicBezierInterpolator.EASE_OUT_QUINT); private final AnimatedFloat shape = new AnimatedFloat(() -> this.requestRender(false, false), 340, CubicBezierInterpolator.EASE_OUT_QUINT); private boolean dualAppeared, camera1Appeared, ignoreCamera1Upd; private long camera1AppearedUntil; private float shapeTo = MessagesController.getGlobalMainSettings().getInt("dualshape", 0); final int array[] = new int[1]; private void onDraw(int cameraId1, int cameraId2, boolean updateTexImage1, boolean updateTexImage2) { if (!initied) { return; } if (!eglContext.equals(egl10.eglGetCurrentContext()) || !eglSurface.equals(egl10.eglGetCurrentSurface(EGL10.EGL_DRAW))) { if (!egl10.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)) { if (BuildVars.LOGS_ENABLED) { FileLog.e("eglMakeCurrent failed " + GLUtils.getEGLErrorString(egl10.eglGetError())); } return; } } final boolean waitingForCamera1; final boolean dual; synchronized (layoutLock) { dual = CameraView.this.dual; waitingForCamera1 = !camera1Appeared; } if ((updateTexImage1 || updateTexImage2) && !waitingForCamera1) { updateTexImage1 = updateTexImage2 = true; } if (updateTexImage1) { try { if (cameraSurface[0] != null && cameraId1 >= 0) { cameraSurface[0].updateTexImage(); } } catch (Throwable e) { FileLog.e(e); } } if (updateTexImage2) { try { if (cameraSurface[1] != null && cameraId2 >= 0) { cameraSurface[1].updateTexImage(); } } catch (Throwable e) { FileLog.e(e); } } final boolean shouldRenderFrame; synchronized (layoutLock) { if (fpsLimit <= 0) { shouldRenderFrame = true; } else { final long currentTimeNs = System.nanoTime(); if (currentTimeNs < nextFrameTimeNs) { shouldRenderFrame = false; } else { nextFrameTimeNs += (long) (TimeUnit.SECONDS.toNanos(1) / fpsLimit);; // The time for the next frame should always be in the future. nextFrameTimeNs = Math.max(nextFrameTimeNs, currentTimeNs); shouldRenderFrame = true; } } } if (currentSession[0] == null || currentSession[0].getCameraId() != cameraId1) { return; } if (recording && videoEncoder != null && (updateTexImage1 || updateTexImage2)) { videoEncoder.frameAvailable(cameraSurface[0], cameraId1, System.nanoTime()); } if (!shouldRenderFrame) { return; } egl10.eglQuerySurface(eglDisplay, eglSurface, EGL10.EGL_WIDTH, array); int drawnWidth = array[0]; egl10.eglQuerySurface(eglDisplay, eglSurface, EGL10.EGL_HEIGHT, array); int drawnHeight = array[0]; GLES20.glViewport(0, 0, drawnWidth, drawnHeight); if (dual) { GLES20.glClearColor(0.f, 0.f, 0.f, 1.f); GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); } shapeValue = shape.set(shapeTo); final float crossfade = lastCrossfadeValue = this.crossfade.set(0f); final float dualScale = dualAppear.set(dualAppeared ? 1f : 0f); final float camera1Blur = 1f - camera1Appear.set(camera1Appeared); if (crossfade <= 0) { crossfading = false; } for (int a = -1; a < 2; ++a) { if (a == -1 && !crossfading) { continue; } final int i = a < 0 ? 1 : a; if (cameraSurface[i] == null) { continue; } if (i != 0 && (currentSession[i] == null || !currentSession[i].isInitiated()) || i == 0 && cameraId1 < 0 && !dual || i == 1 && cameraId2 < 0) { continue; } if (i == 0 && updateTexImage1 || i == 1 && updateTexImage2) { cameraSurface[i].getTransformMatrix(mSTMatrix[i]); } GLES20.glUseProgram(drawProgram); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, cameraTexture[i][0]); GLES20.glVertexAttribPointer(positionHandle, 3, GLES20.GL_FLOAT, false, 12, vertexBuffer); GLES20.glEnableVertexAttribArray(positionHandle); GLES20.glVertexAttribPointer(textureHandle, 2, GLES20.GL_FLOAT, false, 8, textureBuffer); GLES20.glEnableVertexAttribArray(textureHandle); GLES20.glUniformMatrix4fv(cameraMatrixHandle, 1, false, cameraMatrix[i], 0); GLES20.glUniformMatrix4fv(oppositeCameraMatrixHandle, 1, false, cameraMatrix[1 - i], 0); GLES20.glUniformMatrix4fv(textureMatrixHandle, 1, false, mSTMatrix[i], 0); GLES20.glUniformMatrix4fv(vertexMatrixHandle, 1, false, mMVPMatrix[i], 0); if (i == 0) { GLES20.glUniform2f(pixelHandle, pixelW, pixelH); GLES20.glUniform1f(dualHandle, dual ? 1 : 0); } else { GLES20.glUniform2f(pixelHandle, pixelDualW, pixelDualH); GLES20.glUniform1f(dualHandle, 1f); } GLES20.glUniform1f(blurHandle, i == 0 ? camera1Blur : 0f); if (i == 1) { GLES20.glUniform1f(alphaHandle, 1); if (a < 0) { GLES20.glUniform1f(roundRadiusHandle, 0); GLES20.glUniform1f(scaleHandle, 1); GLES20.glUniform1f(shapeFromHandle, 2); GLES20.glUniform1f(shapeToHandle, 2); GLES20.glUniform1f(shapeHandle, 0); GLES20.glUniform1f(crossfadeHandle, 1); } else if (!crossfading) { GLES20.glUniform1f(roundRadiusHandle, AndroidUtilities.dp(16)); GLES20.glUniform1f(scaleHandle, dualScale); GLES20.glUniform1f(shapeFromHandle, (float) Math.floor(shapeValue)); GLES20.glUniform1f(shapeToHandle, (float) Math.ceil(shapeValue)); GLES20.glUniform1f(shapeHandle, shapeValue - (float) Math.floor(shapeValue)); GLES20.glUniform1f(crossfadeHandle, 0); } else { GLES20.glUniform1f(roundRadiusHandle, AndroidUtilities.dp(16)); GLES20.glUniform1f(scaleHandle, 1f - crossfade); GLES20.glUniform1f(shapeFromHandle, (float) Math.floor(shapeValue)); GLES20.glUniform1f(shapeToHandle, (float) Math.ceil(shapeValue)); GLES20.glUniform1f(shapeHandle, shapeValue - (float) Math.floor(shapeValue)); GLES20.glUniform1f(shapeHandle, crossfade); GLES20.glUniform1f(crossfadeHandle, 0); } } else { GLES20.glUniform1f(alphaHandle, 1f); if (crossfading) { GLES20.glUniform1f(roundRadiusHandle, AndroidUtilities.lerp(AndroidUtilities.dp(12), AndroidUtilities.dp(16), crossfade)); GLES20.glUniform1f(scaleHandle, 1f); GLES20.glUniform1f(shapeFromHandle, shapeTo); GLES20.glUniform1f(shapeToHandle, 2); GLES20.glUniform1f(shapeHandle, Utilities.clamp((1f - crossfade), 1, 0)); GLES20.glUniform1f(crossfadeHandle, crossfade); } else { GLES20.glUniform1f(roundRadiusHandle, 0); GLES20.glUniform1f(scaleHandle, 1f); GLES20.glUniform1f(shapeFromHandle, 2f); GLES20.glUniform1f(shapeToHandle, 2f); GLES20.glUniform1f(shapeHandle, 0f); GLES20.glUniform1f(crossfadeHandle, 0f); } } GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); GLES20.glDisableVertexAttribArray(positionHandle); GLES20.glDisableVertexAttribArray(textureHandle); GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0); GLES20.glUseProgram(0); } egl10.eglSwapBuffers(eglDisplay, eglSurface); synchronized (layoutLock) { if (!firstFrameRendered && !waitingForCamera1) { firstFrameRendered = true; AndroidUtilities.runOnUIThread(() -> { onFirstFrameRendered(0); }); } if (!firstFrame2Rendered && dualAppeared) { firstFrame2Rendered = true; AndroidUtilities.runOnUIThread(() -> { onFirstFrameRendered(1); }); } } } @Override public void run() { initied = initGL(); super.run(); } @Override public void handleMessage(Message inputMessage) { int what = inputMessage.what; switch (what) { case DO_RENDER_MESSAGE: onDraw(inputMessage.arg1, inputMessage.arg2, inputMessage.obj == updateTexBoth || inputMessage.obj == updateTex1, inputMessage.obj == updateTexBoth || inputMessage.obj == updateTex2); break; case DO_SHUTDOWN_MESSAGE: finish(); if (recording) { videoEncoder.stopRecording(inputMessage.arg1); } Looper looper = Looper.myLooper(); if (looper != null) { looper.quit(); } break; case DO_DUAL_START: case DO_REINIT_MESSAGE: { final int i = what == DO_REINIT_MESSAGE ? 0 : 1; if (!egl10.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)) { if (BuildVars.LOGS_ENABLED) { FileLog.d("CameraView " + "eglMakeCurrent failed " + GLUtils.getEGLErrorString(egl10.eglGetError())); } return; } if (cameraSurface[i] != null) { cameraSurface[i].getTransformMatrix(moldSTMatrix[i]); cameraSurface[i].setOnFrameAvailableListener(null); cameraSurface[i].release(); cameraSurface[i] = null; } if (cameraTexture[i][0] == 0) { GLES20.glGenTextures(1, cameraTexture[i], 0); } cameraId[i] = inputMessage.arg1; GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, cameraTexture[i][0]); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); if (i == 1) { applyDualMatrix((Matrix) inputMessage.obj); } cameraSurface[i] = new SurfaceTexture(cameraTexture[i][0]); cameraSurface[i].setOnFrameAvailableListener(this::updTex); if (ignoreCamera1Upd) { camera1Appeared = false; camera1AppearedUntil = System.currentTimeMillis() + 60L; ignoreCamera1Upd = false; } createCamera(cameraSurface[i], i); updateScale(i); float tX = 1.0f / scaleX / 2.0f; float tY = 1.0f / scaleY / 2.0f; float[] texData = { 0.5f - tX, 0.5f - tY, 0.5f + tX, 0.5f - tY, 0.5f - tX, 0.5f + tY, 0.5f + tX, 0.5f + tY }; textureBuffer = ByteBuffer.allocateDirect(texData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer(); textureBuffer.put(texData).position(0); if (i == 1) { dualAppeared = false; synchronized (layoutLock) { dualCameraAppeared = false; firstFrame2Rendered = false; } dualAppear.set(0f, true); } break; } case DO_SETSESSION_MESSAGE: { final int i = inputMessage.arg1; CameraSessionWrapper newSession = (CameraSessionWrapper) inputMessage.obj; if (newSession == null) { return; } if (currentSession[i] != newSession) { currentSession[i] = newSession; cameraId[i] = newSession.getCameraId(); } // currentSession[i].updateRotation(); int rotationAngle = currentSession[i].getWorldAngle(); if (BuildVars.LOGS_ENABLED) { FileLog.d("CameraView " + "set gl renderer session " + i + " angle=" + rotationAngle); } android.opengl.Matrix.setIdentityM(mMVPMatrix[i], 0); if (rotationAngle != 0) { android.opengl.Matrix.rotateM(mMVPMatrix[i], 0, rotationAngle, 0, 0, 1); } break; } case DO_START_RECORDING: { if (!initied) { return; } recordFile = (File) inputMessage.obj; videoEncoder = new VideoRecorder(); recording = true; videoEncoder.startRecording(recordFile, EGL14.eglGetCurrentContext()); break; } case DO_STOP_RECORDING: { if (videoEncoder != null) { videoEncoder.stopRecording(0); videoEncoder = null; } recording = false; break; } case DO_DUAL_END: { if (!egl10.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)) { if (BuildVars.LOGS_ENABLED) { FileLog.d("CameraView " + "eglMakeCurrent failed " + GLUtils.getEGLErrorString(egl10.eglGetError())); } return; } if (cameraSurface[1] != null) { cameraSurface[1].getTransformMatrix(moldSTMatrix[1]); cameraSurface[1].setOnFrameAvailableListener(null); cameraSurface[1].release(); cameraSurface[1] = null; } if (cameraTexture[1][0] != 0) { GLES20.glDeleteTextures(1, cameraTexture[1], 0); cameraTexture[1][0] = 0; } currentSession[1] = null; cameraId[1] = -1; requestRender(false, false); break; } case DO_DUAL_MOVE: { applyDualMatrix((Matrix) inputMessage.obj); requestRender(false, false); break; } case DO_DUAL_TOGGLE_SHAPE: { shapeTo++; lastShapeTo = shapeTo; requestRender(false, false); break; } case DO_DUAL_FLIP: { int cameraId0 = cameraId[0]; cameraId[0] = cameraId[1]; cameraId[1] = cameraId0; CameraSessionWrapper cameraSession0 = currentSession[0]; currentSession[0] = currentSession[1]; currentSession[1] = cameraSession0; int[] cameraTexture0 = cameraTexture[0]; cameraTexture[0] = cameraTexture[1]; cameraTexture[1] = cameraTexture0; SurfaceTexture cameraSurface0 = cameraSurface[0]; cameraSurface[0] = cameraSurface[1]; cameraSurface[1] = cameraSurface0; float[] mMVPMatrix0 = mMVPMatrix[0]; mMVPMatrix[0] = mMVPMatrix[1]; mMVPMatrix[1] = mMVPMatrix0; float[] mSTMatrix0 = mSTMatrix[0]; mSTMatrix[0] = mSTMatrix[1]; mSTMatrix[1] = mSTMatrix0; float[] moldSTMatrix0 = moldSTMatrix[0]; moldSTMatrix[0] = moldSTMatrix[1]; moldSTMatrix[1] = moldSTMatrix0; crossfading = true; lastCrossfadeValue = 1f; crossfade.set(1f, true); requestRender(true, true); break; } case BLUR_CAMERA1: { camera1Appeared = false; ignoreCamera1Upd = true; camera1AppearedUntil = System.currentTimeMillis() + 60L; requestRender(false, false); break; } } } private void updateScale(int surfaceIndex) { int width, height; if (previewSize[surfaceIndex] != null) { width = previewSize[surfaceIndex].getWidth(); height = previewSize[surfaceIndex].getHeight(); } else { return; } float scale = surfaceWidth / (float) Math.min(width, height); width *= scale; height *= scale; if (width == height) { scaleX = 1f; scaleY = 1f; } else if (width > height) { scaleX = height / (float) surfaceWidth; scaleY = 1.0f; } else { scaleX = 1.0f; scaleY = width / (float) surfaceHeight; } FileLog.d("CameraView camera scaleX = " + scaleX + " scaleY = " + scaleY); } // private final float[] tempVertices = new float[6]; private void applyDualMatrix(Matrix matrix) { // tempVertices[0] = tempVertices[1] = 0; // tempVertices[2] = pixelW; // tempVertices[3] = 0; // tempVertices[4] = 0; // tempVertices[5] = pixelH; // matrix.mapPoints(tempVertices); // pixelDualW = MathUtils.distance(tempVertices[0], tempVertices[1], tempVertices[2], tempVertices[3]); // pixelDualH = MathUtils.distance(tempVertices[0], tempVertices[1], tempVertices[4], tempVertices[5]); getValues(matrix, cameraMatrix[1]); } private float[] m3x3; private void getValues(Matrix matrix3x3, float[] m4x4) { if (m3x3 == null) { m3x3 = new float[9]; } matrix3x3.getValues(m3x3); m4x4[0] = m3x3[0]; m4x4[1] = m3x3[3]; m4x4[2] = 0; m4x4[3] = m3x3[6]; m4x4[4] = m3x3[1]; m4x4[5] = m3x3[4]; m4x4[6] = 0; m4x4[7] = m3x3[7]; m4x4[8] = 0; m4x4[9] = 0; m4x4[10] = 1; m4x4[11] = 0; m4x4[12] = m3x3[2]; m4x4[13] = m3x3[5]; m4x4[14] = 0; m4x4[15] = m3x3[8]; } public void shutdown(int send) { Handler handler = getHandler(); if (handler != null) { sendMessage(handler.obtainMessage(DO_SHUTDOWN_MESSAGE, send, 0), 0); } } private long pausedTime; public void pause(long duration) { pausedTime = System.currentTimeMillis() + duration; } private final Object updateTex1 = new Object(); private final Object updateTex2 = new Object(); private final Object updateTexBoth = new Object(); public void requestRender(boolean updateTexImage1, boolean updateTexImage2) { if (pausedTime > 0 && System.currentTimeMillis() < pausedTime) { return; } if (!updateTexImage1 && !updateTexImage2 && recording) { // todo: currently video timestamps are messed up in that case return; } Handler handler = getHandler(); if (handler != null) { if ((updateTexImage1 || updateTexImage2) && handler.hasMessages(DO_RENDER_MESSAGE, updateTexBoth)) { return; } if (!updateTexImage1 && handler.hasMessages(DO_RENDER_MESSAGE, updateTex1)) { updateTexImage1 = true; } if (!updateTexImage2 && handler.hasMessages(DO_RENDER_MESSAGE, updateTex2)) { updateTexImage2 = true; } handler.removeMessages(DO_RENDER_MESSAGE); sendMessage(handler.obtainMessage(DO_RENDER_MESSAGE, cameraId[0], cameraId[1], updateTexImage1 && updateTexImage2 ? updateTexBoth : (updateTexImage1 ? updateTex1 : updateTex2)), 0); } } public boolean startRecording(File path) { Handler handler = getHandler(); if (handler != null) { sendMessage(handler.obtainMessage(DO_START_RECORDING, path), 0); return false; } return true; } public void stopRecording() { Handler handler = getHandler(); if (handler != null) { sendMessage(handler.obtainMessage(DO_STOP_RECORDING), 0); } } } private void onFirstFrameRendered(int i) { if (i == 0) { flipping = false; if (blurredStubView.getVisibility() == View.VISIBLE) { blurredStubView.animate().alpha(0).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); blurredStubView.setVisibility(View.GONE); } }).setDuration(120).start(); } } else { onDualCameraSuccess(); } } protected void onDualCameraSuccess() { } private int loadShader(int type, String shaderCode) { int shader = GLES20.glCreateShader(type); GLES20.glShaderSource(shader, shaderCode); GLES20.glCompileShader(shader); int[] compileStatus = new int[1]; GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compileStatus, 0); if (compileStatus[0] == 0) { if (BuildVars.LOGS_ENABLED) { FileLog.e(GLES20.glGetShaderInfoLog(shader)); } GLES20.glDeleteShader(shader); shader = 0; } return shader; } private void createCamera(final SurfaceTexture surfaceTexture, int i) { AndroidUtilities.runOnUIThread(() -> { CameraGLThread cameraThread = this.cameraThread; if (cameraThread == null) { return; } if (BuildVars.LOGS_ENABLED) { FileLog.d("CameraView " + "create camera"+(useCamera2 ? "2" : "")+" session " + i); } if (useCamera2) { Camera2Session session = Camera2Session.create(i == 0 ? isFrontface : !isFrontface, surfaceWidth, surfaceHeight); if (session == null) return; cameraSession[i] = CameraSessionWrapper.of(session); previewSize[i] = new Size(session.getPreviewWidth(), session.getPreviewHeight()); cameraThread.setCurrentSession(cameraSession[i], i); session.whenDone(() -> { requestLayout(); if (dual && i == 1 && initFirstCameraAfterSecond) { initFirstCameraAfterSecond = false; AndroidUtilities.runOnUIThread(() -> { updateCameraInfoSize(0); cameraThread.reinitForNewCamera(); addToDualWait(350L); }); } }); session.open(surfaceTexture); } else { if (previewSize[i] == null) { updateCameraInfoSize(i); } if (previewSize[i] == null) { return; } surfaceTexture.setDefaultBufferSize(previewSize[i].getWidth(), previewSize[i].getHeight()); CameraSession session = new CameraSession(info[i], previewSize[i], pictureSize[i], ImageFormat.JPEG, false); session.setCurrentFlashMode(Camera.Parameters.FLASH_MODE_OFF); cameraSession[i] = CameraSessionWrapper.of(session); cameraThread.setCurrentSession(cameraSession[i], i); requestLayout(); CameraController.getInstance().open(session, surfaceTexture, () -> { if (cameraSession[i] != null) { if (BuildVars.LOGS_ENABLED) { FileLog.d("CameraView " + "camera initied " + i); } session.setInitied(); requestLayout(); } if (dual && i == 1 && initFirstCameraAfterSecond) { initFirstCameraAfterSecond = false; AndroidUtilities.runOnUIThread(() -> { updateCameraInfoSize(0); cameraThread.reinitForNewCamera(); addToDualWait(350L); }); } }, () -> cameraThread.setCurrentSession(cameraSession[i], i)); } }); } protected void receivedAmplitude(double amplitude) { } private class VideoRecorder implements Runnable { private static final String VIDEO_MIME_TYPE = "video/hevc"; private static final String AUDIO_MIME_TYPE = "audio/mp4a-latm"; private static final int FRAME_RATE = 30; private static final int IFRAME_INTERVAL = 1; private File videoFile; private File fileToWrite; private boolean writingToDifferentFile; private int videoBitrate; private boolean videoConvertFirstWrite = true; private boolean blendEnabled; private Surface surface; private android.opengl.EGLDisplay eglDisplay = EGL14.EGL_NO_DISPLAY; private android.opengl.EGLContext eglContext = EGL14.EGL_NO_CONTEXT; private android.opengl.EGLContext sharedEglContext; private android.opengl.EGLConfig eglConfig; private android.opengl.EGLSurface eglSurface = EGL14.EGL_NO_SURFACE; private MediaCodec videoEncoder; private MediaCodec audioEncoder; private int prependHeaderSize; private boolean firstEncode; private MediaCodec.BufferInfo videoBufferInfo; private MediaCodec.BufferInfo audioBufferInfo; private MP4Builder mediaMuxer; private ArrayList<InstantCameraView.AudioBufferInfo> buffersToWrite = new ArrayList<>(); private int videoTrackIndex = -5; private int audioTrackIndex = -5; private long lastCommitedFrameTime; private long audioStartTime = -1; private long currentTimestamp = 0; private long lastTimestamp = -1; private volatile EncoderHandler handler; private final Object sync = new Object(); private boolean ready; private volatile boolean running; private volatile int sendWhenDone; private long skippedTime; private boolean skippedFirst; private long desyncTime; private long videoFirst = -1; private long videoLast; private long audioFirst = -1; private boolean audioStopedByTime; private int drawProgram; private int vertexMatrixHandle; private int textureMatrixHandle; private int cameraMatrixHandle; private int oppositeCameraMatrixHandle; private int positionHandle; private int textureHandle; private int roundRadiusHandle; private int pixelHandle; private int dualHandle; private int crossfadeHandle; private int shapeFromHandle, shapeToHandle, shapeHandle; private int alphaHandle; private int scaleHandle; private int blurHandle; private int zeroTimeStamps; private Integer lastCameraId = 0; private AudioRecord audioRecorder; private FloatBuffer textureBuffer; private ArrayBlockingQueue<InstantCameraView.AudioBufferInfo> buffers = new ArrayBlockingQueue<>(10); private ArrayList<Bitmap> keyframeThumbs = new ArrayList<>(); DispatchQueue fileWriteQueue; private Runnable recorderRunnable = new Runnable() { @Override public void run() { long audioPresentationTimeUs = -1; int readResult; boolean done = false; while (!done) { if (!running && audioRecorder.getRecordingState() != AudioRecord.RECORDSTATE_STOPPED) { try { audioRecorder.stop(); } catch (Exception e) { done = true; } if (sendWhenDone == 0) { break; } } InstantCameraView.AudioBufferInfo buffer; if (buffers.isEmpty()) { buffer = new InstantCameraView.AudioBufferInfo(); } else { buffer = buffers.poll(); } buffer.lastWroteBuffer = 0; buffer.results = InstantCameraView.AudioBufferInfo.MAX_SAMPLES; for (int a = 0; a < InstantCameraView.AudioBufferInfo.MAX_SAMPLES; a++) { if (audioPresentationTimeUs == -1) { audioPresentationTimeUs = System.nanoTime() / 1000; } ByteBuffer byteBuffer = buffer.buffer[a]; byteBuffer.rewind(); readResult = audioRecorder.read(byteBuffer, 2048); if (readResult > 0 && a % 2 == 0) { byteBuffer.limit(readResult); double s = 0; for (int i = 0; i < readResult / 2; i++) { short p = byteBuffer.getShort(); s += p * p; } double amplitude = Math.sqrt(s / readResult / 2); AndroidUtilities.runOnUIThread(() -> receivedAmplitude(amplitude)); byteBuffer.position(0); } if (readResult <= 0) { buffer.results = a; if (!running) { buffer.last = true; } break; } buffer.offset[a] = audioPresentationTimeUs; buffer.read[a] = readResult; int bufferDurationUs = 1000000 * readResult / audioSampleRate / 2; audioPresentationTimeUs += bufferDurationUs; } if (buffer.results >= 0 || buffer.last) { if (!running && buffer.results < InstantCameraView.AudioBufferInfo.MAX_SAMPLES) { done = true; } handler.sendMessage(handler.obtainMessage(MSG_AUDIOFRAME_AVAILABLE, buffer)); } else { if (!running) { done = true; } else { try { buffers.put(buffer); } catch (Exception ignore) { } } } } try { audioRecorder.release(); } catch (Exception e) { FileLog.e(e); } handler.sendMessage(handler.obtainMessage(MSG_STOP_RECORDING, sendWhenDone, 0)); } }; private String outputMimeType; public void startRecording(File outputFile, android.opengl.EGLContext sharedContext) { String model = Build.DEVICE; if (model == null) { model = ""; } Size pictureSize; int bitrate; pictureSize = previewSize[0]; if (Math.min(pictureSize.mHeight, pictureSize.mWidth) >= 720) { bitrate = 3500000; } else { bitrate = 1800000; } videoFile = outputFile; if (cameraSession[0].getWorldAngle() == 90 || cameraSession[0].getWorldAngle() == 270) { videoWidth = pictureSize.getWidth(); videoHeight = pictureSize.getHeight(); } else { videoWidth = pictureSize.getHeight(); videoHeight = pictureSize.getWidth(); } videoBitrate = bitrate; sharedEglContext = sharedContext; synchronized (sync) { if (running) { return; } running = true; Thread thread = new Thread(this, "TextureMovieEncoder"); thread.setPriority(Thread.MAX_PRIORITY); thread.start(); while (!ready) { try { sync.wait(); } catch (InterruptedException ie) { // ignore } } } fileWriteQueue = new DispatchQueue("VR_FileWriteQueue"); fileWriteQueue.setPriority(Thread.MAX_PRIORITY); keyframeThumbs.clear(); handler.sendMessage(handler.obtainMessage(MSG_START_RECORDING)); } public void stopRecording(int send) { handler.sendMessage(handler.obtainMessage(MSG_STOP_RECORDING, send, 0)); } public void frameAvailable(SurfaceTexture st, Integer cameraId, long timestampInternal) { synchronized (sync) { if (!ready) { return; } } long timestamp = st.getTimestamp(); if (timestamp == 0) { zeroTimeStamps++; if (zeroTimeStamps > 1) { if (BuildVars.LOGS_ENABLED) { FileLog.d("CameraView " + "fix timestamp enabled"); } timestamp = timestampInternal; } else { return; } } else { zeroTimeStamps = 0; } handler.sendMessage(handler.obtainMessage(MSG_VIDEOFRAME_AVAILABLE, (int) (timestamp >> 32), (int) timestamp, cameraId)); } @Override public void run() { Looper.prepare(); synchronized (sync) { handler = new EncoderHandler(this); ready = true; sync.notify(); } Looper.loop(); synchronized (sync) { ready = false; } } private void handleAudioFrameAvailable(InstantCameraView.AudioBufferInfo input) { if (audioStopedByTime) { return; } buffersToWrite.add(input); if (audioFirst == -1) { if (videoFirst == -1) { if (BuildVars.LOGS_ENABLED) { FileLog.d("CameraView " + "video record not yet started"); } return; } while (true) { boolean ok = false; for (int a = 0; a < input.results; a++) { if (a == 0 && Math.abs(videoFirst - input.offset[a]) > 10000000L) { desyncTime = videoFirst - input.offset[a]; audioFirst = input.offset[a]; ok = true; if (BuildVars.LOGS_ENABLED) { FileLog.d("CameraView " + "detected desync between audio and video " + desyncTime); } break; } if (input.offset[a] >= videoFirst) { input.lastWroteBuffer = a; audioFirst = input.offset[a]; ok = true; if (BuildVars.LOGS_ENABLED) { FileLog.d("CameraView " + "found first audio frame at " + a + " timestamp = " + input.offset[a]); } break; } else { if (BuildVars.LOGS_ENABLED) { FileLog.d("CameraView " + "ignore first audio frame at " + a + " timestamp = " + input.offset[a]); } } } if (!ok) { if (BuildVars.LOGS_ENABLED) { FileLog.d("CameraView " + "first audio frame not found, removing buffers " + input.results); } buffersToWrite.remove(input); } else { break; } if (!buffersToWrite.isEmpty()) { input = buffersToWrite.get(0); } else { return; } } } if (audioStartTime == -1) { audioStartTime = input.offset[input.lastWroteBuffer]; } if (buffersToWrite.size() > 1) { input = buffersToWrite.get(0); } try { drainEncoder(false); } catch (Exception e) { FileLog.e(e); } try { boolean isLast = false; while (input != null) { int inputBufferIndex = audioEncoder.dequeueInputBuffer(0); if (inputBufferIndex >= 0) { ByteBuffer inputBuffer; if (Build.VERSION.SDK_INT >= 21) { inputBuffer = audioEncoder.getInputBuffer(inputBufferIndex); } else { ByteBuffer[] inputBuffers = audioEncoder.getInputBuffers(); inputBuffer = inputBuffers[inputBufferIndex]; inputBuffer.clear(); } long startWriteTime = input.offset[input.lastWroteBuffer]; for (int a = input.lastWroteBuffer; a <= input.results; a++) { if (a < input.results) { if (!running && input.offset[a] >= videoLast - desyncTime) { if (BuildVars.LOGS_ENABLED) { FileLog.d("CameraView " + "stop audio encoding because of stoped video recording at " + input.offset[a] + " last video " + videoLast); } audioStopedByTime = true; isLast = true; input = null; buffersToWrite.clear(); break; } if (inputBuffer.remaining() < input.read[a]) { input.lastWroteBuffer = a; input = null; break; } inputBuffer.put(input.buffer[a]); } if (a >= input.results - 1) { buffersToWrite.remove(input); if (running) { buffers.put(input); } if (!buffersToWrite.isEmpty()) { input = buffersToWrite.get(0); } else { isLast = input.last; input = null; break; } } } audioEncoder.queueInputBuffer(inputBufferIndex, 0, inputBuffer.position(), startWriteTime == 0 ? 0 : startWriteTime - audioStartTime, isLast ? MediaCodec.BUFFER_FLAG_END_OF_STREAM : 0); } } } catch (Throwable e) { FileLog.e(e); } } private void handleVideoFrameAvailable(long timestampNanos, Integer cameraId) { try { drainEncoder(false); } catch (Exception e) { FileLog.e(e); } long dt; long currentTime = System.currentTimeMillis(); if (!lastCameraId.equals(cameraId)) { lastTimestamp = -1; lastCameraId = cameraId; } if (lastTimestamp == -1) { lastTimestamp = timestampNanos; if (currentTimestamp != 0) { dt = (currentTime - lastCommitedFrameTime) * 1000000; } else { dt = 0; } } else { dt = (timestampNanos - lastTimestamp); lastTimestamp = timestampNanos; } lastCommitedFrameTime = currentTime; if (!skippedFirst) { skippedTime += dt; if (skippedTime < 200000000) { return; } skippedFirst = true; } currentTimestamp += dt; if (videoFirst == -1) { videoFirst = timestampNanos / 1000; if (BuildVars.LOGS_ENABLED) { FileLog.d("CameraView " + "first video frame was at " + videoFirst); } } videoLast = timestampNanos; if (cameraTexture[1][0] != 0 && !blendEnabled) { GLES20.glEnable(GLES20.GL_BLEND); blendEnabled = true; } final boolean isDual = dual; if (isDual) { GLES20.glClearColor(0.f, 0.f, 0.f, 1.f); GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); } final float crossfade = lastCrossfadeValue; final boolean crossfading = crossfade > 0; for (int a = -1; a < 2; ++a) { if (a == -1 && !crossfading) { continue; } final int i = a < 0 ? 1 : a; if (cameraTexture[i][0] == 0) { continue; } GLES20.glUseProgram(drawProgram); GLES20.glVertexAttribPointer(positionHandle, 3, GLES20.GL_FLOAT, false, 12, vertexBuffer); GLES20.glEnableVertexAttribArray(positionHandle); GLES20.glVertexAttribPointer(textureHandle, 2, GLES20.GL_FLOAT, false, 8, textureBuffer); GLES20.glEnableVertexAttribArray(textureHandle); GLES20.glUniformMatrix4fv(vertexMatrixHandle, 1, false, mMVPMatrix[i], 0); GLES20.glUniformMatrix4fv(cameraMatrixHandle, 1, false, cameraMatrix[i], 0); GLES20.glUniformMatrix4fv(oppositeCameraMatrixHandle, 1, false, cameraMatrix[1 - i], 0); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glUniformMatrix4fv(textureMatrixHandle, 1, false, mSTMatrix[i], 0); GLES20.glUniform1f(blurHandle, 0); if (i == 0) { GLES20.glUniform2f(pixelHandle, pixelW, pixelH); GLES20.glUniform1f(dualHandle, isDual ? 1f : 0f); } else { GLES20.glUniform2f(pixelHandle, pixelDualW, pixelDualH); GLES20.glUniform1f(dualHandle, 1f); } if (i == 1) { GLES20.glUniform1f(alphaHandle, 1); if (a < 0) { GLES20.glUniform1f(roundRadiusHandle, 0); GLES20.glUniform1f(scaleHandle, 1); GLES20.glUniform1f(shapeFromHandle, 2); GLES20.glUniform1f(shapeToHandle, 2); GLES20.glUniform1f(shapeHandle, 0); GLES20.glUniform1f(crossfadeHandle, 1); } else if (!crossfading) { GLES20.glUniform1f(roundRadiusHandle, AndroidUtilities.dp(16)); GLES20.glUniform1f(scaleHandle, 1f); GLES20.glUniform1f(shapeFromHandle, (float) Math.floor(shapeValue)); GLES20.glUniform1f(shapeToHandle, (float) Math.ceil(shapeValue)); GLES20.glUniform1f(shapeHandle, shapeValue - (float) Math.floor(shapeValue)); GLES20.glUniform1f(crossfadeHandle, 0); } else { GLES20.glUniform1f(roundRadiusHandle, AndroidUtilities.dp(16)); GLES20.glUniform1f(scaleHandle, 1f - crossfade); GLES20.glUniform1f(shapeFromHandle, (float) Math.floor(shapeValue)); GLES20.glUniform1f(shapeToHandle, (float) Math.ceil(shapeValue)); GLES20.glUniform1f(shapeHandle, shapeValue - (float) Math.floor(shapeValue)); GLES20.glUniform1f(shapeHandle, crossfade); GLES20.glUniform1f(crossfadeHandle, 0); } } else { GLES20.glUniform1f(alphaHandle, 1f); if (crossfading) { GLES20.glUniform1f(roundRadiusHandle, AndroidUtilities.lerp(AndroidUtilities.dp(12), AndroidUtilities.dp(16), crossfade)); GLES20.glUniform1f(scaleHandle, 1f); GLES20.glUniform1f(shapeFromHandle, lastShapeTo); GLES20.glUniform1f(shapeToHandle, 2); GLES20.glUniform1f(shapeHandle, Utilities.clamp((1f - crossfade), 1, 0)); GLES20.glUniform1f(crossfadeHandle, crossfade); } else { GLES20.glUniform1f(roundRadiusHandle, 0); GLES20.glUniform1f(scaleHandle, 1f); GLES20.glUniform1f(shapeFromHandle, 2); GLES20.glUniform1f(shapeToHandle, 2); GLES20.glUniform1f(shapeHandle, 0); GLES20.glUniform1f(crossfadeHandle, 0f); } } GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, cameraTexture[i][0]); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); GLES20.glDisableVertexAttribArray(positionHandle); GLES20.glDisableVertexAttribArray(textureHandle); GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0); GLES20.glUseProgram(0); } EGLExt.eglPresentationTimeANDROID(eglDisplay, eglSurface, currentTimestamp); EGL14.eglSwapBuffers(eglDisplay, eglSurface); } private void handleStopRecording(final int send) { if (running) { sendWhenDone = send; running = false; return; } try { drainEncoder(true); } catch (Exception e) { FileLog.e(e); } if (videoEncoder != null) { try { videoEncoder.stop(); videoEncoder.release(); videoEncoder = null; } catch (Exception e) { FileLog.e(e); } } if (audioEncoder != null) { try { audioEncoder.stop(); audioEncoder.release(); audioEncoder = null; } catch (Exception e) { FileLog.e(e); } } CountDownLatch countDownLatch = new CountDownLatch(1); fileWriteQueue.postRunnable(() -> { try { mediaMuxer.finishMovie(); } catch (Exception e) { e.printStackTrace(); } countDownLatch.countDown(); }); try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } if (writingToDifferentFile) { if (!fileToWrite.renameTo(videoFile)) { FileLog.e("unable to rename file, try move file"); try { AndroidUtilities.copyFile(fileToWrite, videoFile); fileToWrite.delete(); } catch (IOException e) { FileLog.e(e); FileLog.e("unable to move file"); } } } EGL14.eglDestroySurface(eglDisplay, eglSurface); eglSurface = EGL14.EGL_NO_SURFACE; if (surface != null) { surface.release(); surface = null; } if (eglDisplay != EGL14.EGL_NO_DISPLAY) { EGL14.eglMakeCurrent(eglDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT); EGL14.eglDestroyContext(eglDisplay, eglContext); EGL14.eglReleaseThread(); EGL14.eglTerminate(eglDisplay); } eglDisplay = EGL14.EGL_NO_DISPLAY; eglContext = EGL14.EGL_NO_CONTEXT; eglConfig = null; handler.exit(); AndroidUtilities.runOnUIThread(() -> { if (cameraSession[0] != null) { cameraSession[0].stopVideoRecording(); } if (cameraSession[1] != null) { cameraSession[1].stopVideoRecording(); } onRecordingFinishRunnable.run(); }); } private void prepareEncoder() { try { int recordBufferSize = AudioRecord.getMinBufferSize(audioSampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT); if (recordBufferSize <= 0) { recordBufferSize = 3584; } int bufferSize = 2048 * 24; if (bufferSize < recordBufferSize) { bufferSize = ((recordBufferSize / 2048) + 1) * 2048 * 2; } for (int a = 0; a < 3; a++) { buffers.add(new InstantCameraView.AudioBufferInfo()); } audioRecorder = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, audioSampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize); audioRecorder.startRecording(); if (BuildVars.LOGS_ENABLED) { FileLog.d("CameraView " + "initied audio record with channels " + audioRecorder.getChannelCount() + " sample rate = " + audioRecorder.getSampleRate() + " bufferSize = " + bufferSize); } Thread thread = new Thread(recorderRunnable); thread.setPriority(Thread.MAX_PRIORITY); thread.start(); audioBufferInfo = new MediaCodec.BufferInfo(); videoBufferInfo = new MediaCodec.BufferInfo(); MediaFormat audioFormat = new MediaFormat(); audioFormat.setString(MediaFormat.KEY_MIME, AUDIO_MIME_TYPE); audioFormat.setInteger(MediaFormat.KEY_SAMPLE_RATE, audioSampleRate); audioFormat.setInteger(MediaFormat.KEY_CHANNEL_COUNT, 1); audioFormat.setInteger(MediaFormat.KEY_BIT_RATE, 32000); audioFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 2048 * InstantCameraView.AudioBufferInfo.MAX_SAMPLES); audioEncoder = MediaCodec.createEncoderByType(AUDIO_MIME_TYPE); audioEncoder.configure(audioFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); audioEncoder.start(); boolean shouldUseHevc = isStory; outputMimeType = shouldUseHevc ? "video/hevc" : "video/avc"; try { if (shouldUseHevc) { String encoderName = SharedConfig.findGoodHevcEncoder(); if (encoderName != null) { videoEncoder = MediaCodec.createByCodecName(encoderName); } } else { outputMimeType = "video/avc"; videoEncoder = MediaCodec.createEncoderByType(outputMimeType); } if (outputMimeType.equals("video/hevc") && videoEncoder != null && !videoEncoder.getCodecInfo().isHardwareAccelerated()) { FileLog.e("hevc encoder isn't hardware accelerated"); videoEncoder.release(); videoEncoder = null; } } catch (Throwable e) { FileLog.e("can't get hevc encoder"); FileLog.e(e); } if (videoEncoder == null && outputMimeType.equals("video/hevc")) { outputMimeType = "video/avc"; videoEncoder = MediaCodec.createEncoderByType(outputMimeType); } firstEncode = true; MediaFormat format = MediaFormat.createVideoFormat(outputMimeType, videoWidth, videoHeight); format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface); format.setInteger(MediaFormat.KEY_BIT_RATE, videoBitrate); format.setInteger(MediaFormat.KEY_FRAME_RATE, FRAME_RATE); format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, IFRAME_INTERVAL); videoEncoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); surface = videoEncoder.createInputSurface(); videoEncoder.start(); boolean isSdCard = ImageLoader.isSdCardPath(videoFile); fileToWrite = videoFile; if (isSdCard) { try { fileToWrite = new File(ApplicationLoader.getFilesDirFixed(), "camera_tmp.mp4"); if (fileToWrite.exists()) { fileToWrite.delete(); } writingToDifferentFile = true; } catch (Throwable e) { FileLog.e(e); fileToWrite = videoFile; writingToDifferentFile = false; } } Mp4Movie movie = new Mp4Movie(); movie.setCacheFile(fileToWrite); movie.setRotation(0); movie.setSize(videoWidth, videoHeight); mediaMuxer = new MP4Builder().createMovie(movie, false, false); mediaMuxer.setAllowSyncFiles(false); } catch (Exception ioe) { throw new RuntimeException(ioe); } if (eglDisplay != EGL14.EGL_NO_DISPLAY) { throw new RuntimeException("EGL already set up"); } eglDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY); if (eglDisplay == EGL14.EGL_NO_DISPLAY) { throw new RuntimeException("unable to get EGL14 display"); } int[] version = new int[2]; if (!EGL14.eglInitialize(eglDisplay, version, 0, version, 1)) { eglDisplay = null; throw new RuntimeException("unable to initialize EGL14"); } if (eglContext == EGL14.EGL_NO_CONTEXT) { int renderableType = EGL14.EGL_OPENGL_ES2_BIT; int[] attribList = { EGL14.EGL_RED_SIZE, 8, EGL14.EGL_GREEN_SIZE, 8, EGL14.EGL_BLUE_SIZE, 8, EGL14.EGL_ALPHA_SIZE, 8, EGL14.EGL_RENDERABLE_TYPE, renderableType, 0x3142, 1, EGL14.EGL_NONE }; android.opengl.EGLConfig[] configs = new android.opengl.EGLConfig[1]; int[] numConfigs = new int[1]; if (!EGL14.eglChooseConfig(eglDisplay, attribList, 0, configs, 0, configs.length, numConfigs, 0)) { throw new RuntimeException("Unable to find a suitable EGLConfig"); } int[] attrib2_list = { EGL14.EGL_CONTEXT_CLIENT_VERSION, 2, EGL14.EGL_NONE }; eglContext = EGL14.eglCreateContext(eglDisplay, configs[0], sharedEglContext, attrib2_list, 0); eglConfig = configs[0]; } int[] values = new int[1]; EGL14.eglQueryContext(eglDisplay, eglContext, EGL14.EGL_CONTEXT_CLIENT_VERSION, values, 0); if (eglSurface != EGL14.EGL_NO_SURFACE) { throw new IllegalStateException("surface already created"); } int[] surfaceAttribs = { EGL14.EGL_NONE }; eglSurface = EGL14.eglCreateWindowSurface(eglDisplay, eglConfig, surface, surfaceAttribs, 0); if (eglSurface == null) { throw new RuntimeException("surface was null"); } if (!EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)) { if (BuildVars.LOGS_ENABLED) { FileLog.e("eglMakeCurrent failed " + GLUtils.getEGLErrorString(EGL14.eglGetError())); } throw new RuntimeException("eglMakeCurrent failed"); } GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); float tX = 1.0f / scaleX / 2.0f; float tY = 1.0f / scaleY / 2.0f; float[] texData = { 0.5f - tX, 0.5f - tY, 0.5f + tX, 0.5f - tY, 0.5f - tX, 0.5f + tY, 0.5f + tX, 0.5f + tY }; textureBuffer = ByteBuffer.allocateDirect(texData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer(); textureBuffer.put(texData).position(0); int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, RLottieDrawable.readRes(null, R.raw.camera_vert)); int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, RLottieDrawable.readRes(null, R.raw.camera_frag)); if (vertexShader != 0 && fragmentShader != 0) { drawProgram = GLES20.glCreateProgram(); GLES20.glAttachShader(drawProgram, vertexShader); GLES20.glAttachShader(drawProgram, fragmentShader); GLES20.glLinkProgram(drawProgram); int[] linkStatus = new int[1]; GLES20.glGetProgramiv(drawProgram, GLES20.GL_LINK_STATUS, linkStatus, 0); if (linkStatus[0] == 0) { GLES20.glDeleteProgram(drawProgram); drawProgram = 0; } else { positionHandle = GLES20.glGetAttribLocation(drawProgram, "aPosition"); textureHandle = GLES20.glGetAttribLocation(drawProgram, "aTextureCoord"); vertexMatrixHandle = GLES20.glGetUniformLocation(drawProgram, "uMVPMatrix"); textureMatrixHandle = GLES20.glGetUniformLocation(drawProgram, "uSTMatrix"); cameraMatrixHandle = GLES20.glGetUniformLocation(drawProgram, "cameraMatrix"); oppositeCameraMatrixHandle = GLES20.glGetUniformLocation(drawProgram, "oppositeCameraMatrix"); roundRadiusHandle = GLES20.glGetUniformLocation(drawProgram, "roundRadius"); pixelHandle = GLES20.glGetUniformLocation(drawProgram, "pixelWH"); dualHandle = GLES20.glGetUniformLocation(drawProgram, "dual"); scaleHandle = GLES20.glGetUniformLocation(drawProgram, "scale"); blurHandle = GLES20.glGetUniformLocation(drawProgram, "blur"); alphaHandle = GLES20.glGetUniformLocation(drawProgram, "alpha"); crossfadeHandle = GLES20.glGetUniformLocation(drawProgram, "crossfade"); shapeFromHandle = GLES20.glGetUniformLocation(drawProgram, "shapeFrom"); shapeToHandle = GLES20.glGetUniformLocation(drawProgram, "shapeTo"); shapeHandle = GLES20.glGetUniformLocation(drawProgram, "shapeT"); } } } public Surface getInputSurface() { return surface; } public void drainEncoder(boolean endOfStream) throws Exception { if (endOfStream) { videoEncoder.signalEndOfInputStream(); } ByteBuffer[] encoderOutputBuffers = null; if (Build.VERSION.SDK_INT < 21) { encoderOutputBuffers = videoEncoder.getOutputBuffers(); } while (true) { int encoderStatus = videoEncoder.dequeueOutputBuffer(videoBufferInfo, 10000); if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) { if (!endOfStream) { break; } } else if (encoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) { if (Build.VERSION.SDK_INT < 21) { encoderOutputBuffers = videoEncoder.getOutputBuffers(); } } else if (encoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { MediaFormat newFormat = videoEncoder.getOutputFormat(); if (videoTrackIndex == -5) { videoTrackIndex = mediaMuxer.addTrack(newFormat, false); if (newFormat.containsKey(MediaFormat.KEY_PREPEND_HEADER_TO_SYNC_FRAMES) && newFormat.getInteger(MediaFormat.KEY_PREPEND_HEADER_TO_SYNC_FRAMES) == 1) { ByteBuffer spsBuff = newFormat.getByteBuffer("csd-0"); ByteBuffer ppsBuff = newFormat.getByteBuffer("csd-1"); prependHeaderSize = (spsBuff == null ? 0 : spsBuff.limit()) + (ppsBuff == null ? 0 : ppsBuff.limit()); } } } else if (encoderStatus >= 0) { ByteBuffer encodedData; if (Build.VERSION.SDK_INT < 21) { encodedData = encoderOutputBuffers[encoderStatus]; } else { encodedData = videoEncoder.getOutputBuffer(encoderStatus); } if (encodedData == null) { throw new RuntimeException("encoderOutputBuffer " + encoderStatus + " was null"); } if (videoBufferInfo.size > 1) { if ((videoBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) == 0) { if (prependHeaderSize != 0 && (videoBufferInfo.flags & MediaCodec.BUFFER_FLAG_KEY_FRAME) != 0) { videoBufferInfo.offset += prependHeaderSize; videoBufferInfo.size -= prependHeaderSize; } if (firstEncode && (videoBufferInfo.flags & MediaCodec.BUFFER_FLAG_KEY_FRAME) != 0) { MediaCodecVideoConvertor.cutOfNalData(outputMimeType, encodedData, videoBufferInfo); firstEncode = false; } MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo(); bufferInfo.size = videoBufferInfo.size; bufferInfo.offset = videoBufferInfo.offset; bufferInfo.flags = videoBufferInfo.flags; bufferInfo.presentationTimeUs = videoBufferInfo.presentationTimeUs; ByteBuffer byteBuffer = AndroidUtilities.cloneByteBuffer(encodedData); fileWriteQueue.postRunnable(() -> { try { mediaMuxer.writeSampleData(videoTrackIndex, byteBuffer, bufferInfo, true); } catch (Exception e) { FileLog.e(e); } }); } else if (videoTrackIndex == -5) { if (outputMimeType.equals("video/hevc")) { throw new RuntimeException("need fix parsing csd data"); } byte[] csd = new byte[videoBufferInfo.size]; encodedData.limit(videoBufferInfo.offset + videoBufferInfo.size); encodedData.position(videoBufferInfo.offset); encodedData.get(csd); ByteBuffer sps = null; ByteBuffer pps = null; for (int a = videoBufferInfo.size - 1; a >= 0; a--) { if (a > 3) { if (csd[a] == 1 && csd[a - 1] == 0 && csd[a - 2] == 0 && csd[a - 3] == 0) { sps = ByteBuffer.allocate(a - 3); pps = ByteBuffer.allocate(videoBufferInfo.size - (a - 3)); sps.put(csd, 0, a - 3).position(0); pps.put(csd, a - 3, videoBufferInfo.size - (a - 3)).position(0); break; } } else { break; } } MediaFormat newFormat = MediaFormat.createVideoFormat("video/avc", videoWidth, videoHeight); if (sps != null && pps != null) { newFormat.setByteBuffer("csd-0", sps); newFormat.setByteBuffer("csd-1", pps); } videoTrackIndex = mediaMuxer.addTrack(newFormat, false); } } videoEncoder.releaseOutputBuffer(encoderStatus, false); if ((videoBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { break; } } } if (Build.VERSION.SDK_INT < 21) { encoderOutputBuffers = audioEncoder.getOutputBuffers(); } boolean encoderOutputAvailable = true; while (true) { int encoderStatus = audioEncoder.dequeueOutputBuffer(audioBufferInfo, 0); if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) { if (!endOfStream || !running && sendWhenDone == 0) { break; } } else if (encoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) { if (Build.VERSION.SDK_INT < 21) { encoderOutputBuffers = audioEncoder.getOutputBuffers(); } } else if (encoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { MediaFormat newFormat = audioEncoder.getOutputFormat(); if (audioTrackIndex == -5) { audioTrackIndex = mediaMuxer.addTrack(newFormat, true); } } else if (encoderStatus >= 0) { ByteBuffer encodedData; if (Build.VERSION.SDK_INT < 21) { encodedData = encoderOutputBuffers[encoderStatus]; } else { encodedData = audioEncoder.getOutputBuffer(encoderStatus); } if (encodedData == null) { throw new RuntimeException("encoderOutputBuffer " + encoderStatus + " was null"); } if ((audioBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) { audioBufferInfo.size = 0; } if (audioBufferInfo.size != 0) { MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo(); bufferInfo.size = audioBufferInfo.size; bufferInfo.offset = audioBufferInfo.offset; bufferInfo.flags = audioBufferInfo.flags; bufferInfo.presentationTimeUs = audioBufferInfo.presentationTimeUs; ByteBuffer byteBuffer = AndroidUtilities.cloneByteBuffer(encodedData); fileWriteQueue.postRunnable(() -> { try { mediaMuxer.writeSampleData(audioTrackIndex, byteBuffer, bufferInfo, false); } catch (Exception e) { FileLog.e(e); } }); } audioEncoder.releaseOutputBuffer(encoderStatus, false); if ((audioBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { break; } } } } @Override protected void finalize() throws Throwable { if (fileWriteQueue != null) { fileWriteQueue.recycle(); fileWriteQueue = null; } try { if (eglDisplay != EGL14.EGL_NO_DISPLAY) { EGL14.eglMakeCurrent(eglDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT); EGL14.eglDestroyContext(eglDisplay, eglContext); EGL14.eglReleaseThread(); EGL14.eglTerminate(eglDisplay); eglDisplay = EGL14.EGL_NO_DISPLAY; eglContext = EGL14.EGL_NO_CONTEXT; eglConfig = null; } } finally { super.finalize(); } } } private static final int MSG_START_RECORDING = 0; private static final int MSG_STOP_RECORDING = 1; private static final int MSG_VIDEOFRAME_AVAILABLE = 2; private static final int MSG_AUDIOFRAME_AVAILABLE = 3; private static class EncoderHandler extends Handler { private WeakReference<VideoRecorder> mWeakEncoder; public EncoderHandler(VideoRecorder encoder) { mWeakEncoder = new WeakReference<>(encoder); } @Override public void handleMessage(Message inputMessage) { int what = inputMessage.what; Object obj = inputMessage.obj; VideoRecorder encoder = mWeakEncoder.get(); if (encoder == null) { return; } switch (what) { case MSG_START_RECORDING: { try { if (BuildVars.LOGS_ENABLED) { FileLog.e("start encoder"); } encoder.prepareEncoder(); } catch (Exception e) { FileLog.e(e); encoder.handleStopRecording(0); Looper.myLooper().quit(); } break; } case MSG_STOP_RECORDING: { if (BuildVars.LOGS_ENABLED) { FileLog.e("stop encoder"); } encoder.handleStopRecording(inputMessage.arg1); break; } case MSG_VIDEOFRAME_AVAILABLE: { long timestamp = (((long) inputMessage.arg1) << 32) | (((long) inputMessage.arg2) & 0xffffffffL); Integer cameraId = (Integer) inputMessage.obj; encoder.handleVideoFrameAvailable(timestamp, cameraId); break; } case MSG_AUDIOFRAME_AVAILABLE: { encoder.handleAudioFrameAvailable((InstantCameraView.AudioBufferInfo) inputMessage.obj); break; } } } public void exit() { Looper.myLooper().quit(); } } public void setFpsLimit(int fpsLimit) { this.fpsLimit = fpsLimit; } public void pauseAsTakingPicture() { if (cameraThread != null) { cameraThread.pause(600); } } @Override public void onError(int errorId, Camera camera, CameraSessionWrapper cameraSession) { } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/messenger/camera/CameraView.java
41,665
/* * Copyright 2017 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ package org.webrtc; import androidx.annotation.Nullable; /** * Interface for a video encoder that can be used with WebRTC. All calls will be made on the * encoding thread. The encoder may be constructed on a different thread and changing thread after * calling release is allowed. */ public interface VideoEncoder { /** Settings passed to the encoder by WebRTC. */ public class Settings { public final int numberOfCores; public final int width; public final int height; public final int startBitrate; // Kilobits per second. public final int maxFramerate; public final int numberOfSimulcastStreams; public final boolean automaticResizeOn; public final Capabilities capabilities; // TODO(bugs.webrtc.org/10720): Remove. @Deprecated public Settings(int numberOfCores, int width, int height, int startBitrate, int maxFramerate, int numberOfSimulcastStreams, boolean automaticResizeOn) { this(numberOfCores, width, height, startBitrate, maxFramerate, numberOfSimulcastStreams, automaticResizeOn, new VideoEncoder.Capabilities(false /* lossNotification */)); } @CalledByNative("Settings") public Settings(int numberOfCores, int width, int height, int startBitrate, int maxFramerate, int numberOfSimulcastStreams, boolean automaticResizeOn, Capabilities capabilities) { this.numberOfCores = numberOfCores; this.width = width; this.height = height; this.startBitrate = startBitrate; this.maxFramerate = maxFramerate; this.numberOfSimulcastStreams = numberOfSimulcastStreams; this.automaticResizeOn = automaticResizeOn; this.capabilities = capabilities; } } /** Capabilities (loss notification, etc.) passed to the encoder by WebRTC. */ public class Capabilities { /** * The remote side has support for the loss notification RTCP feedback message format, and will * be sending these feedback messages if necessary. */ public final boolean lossNotification; @CalledByNative("Capabilities") public Capabilities(boolean lossNotification) { this.lossNotification = lossNotification; } } /** Additional info for encoding. */ public class EncodeInfo { public final EncodedImage.FrameType[] frameTypes; @CalledByNative("EncodeInfo") public EncodeInfo(EncodedImage.FrameType[] frameTypes) { this.frameTypes = frameTypes; } } // TODO(sakal): Add values to these classes as necessary. /** Codec specific information about the encoded frame. */ public class CodecSpecificInfo {} public class CodecSpecificInfoVP8 extends CodecSpecificInfo {} public class CodecSpecificInfoVP9 extends CodecSpecificInfo {} public class CodecSpecificInfoH264 extends CodecSpecificInfo {} public class CodecSpecificInfoAV1 extends CodecSpecificInfo {} /** * Represents bitrate allocated for an encoder to produce frames. Bitrate can be divided between * spatial and temporal layers. */ public class BitrateAllocation { // First index is the spatial layer and second the temporal layer. public final int[][] bitratesBbs; /** * Initializes the allocation with a two dimensional array of bitrates. The first index of the * array is the spatial layer and the second index in the temporal layer. */ @CalledByNative("BitrateAllocation") public BitrateAllocation(int[][] bitratesBbs) { this.bitratesBbs = bitratesBbs; } /** * Gets the total bitrate allocated for all layers. */ public int getSum() { int sum = 0; for (int[] spatialLayer : bitratesBbs) { for (int bitrate : spatialLayer) { sum += bitrate; } } return sum; } } /** Settings for WebRTC quality based scaling. */ public class ScalingSettings { public final boolean on; @Nullable public final Integer low; @Nullable public final Integer high; /** * Settings to disable quality based scaling. */ public static final ScalingSettings OFF = new ScalingSettings(); /** * Creates settings to enable quality based scaling. * * @param low Average QP at which to scale up the resolution. * @param high Average QP at which to scale down the resolution. */ public ScalingSettings(int low, int high) { this.on = true; this.low = low; this.high = high; } private ScalingSettings() { this.on = false; this.low = null; this.high = null; } // TODO(bugs.webrtc.org/8830): Below constructors are deprecated. // Default thresholds are going away, so thresholds have to be set // when scaling is on. /** * Creates quality based scaling setting. * * @param on True if quality scaling is turned on. */ @Deprecated public ScalingSettings(boolean on) { this.on = on; this.low = null; this.high = null; } /** * Creates quality based scaling settings with custom thresholds. * * @param on True if quality scaling is turned on. * @param low Average QP at which to scale up the resolution. * @param high Average QP at which to scale down the resolution. */ @Deprecated public ScalingSettings(boolean on, int low, int high) { this.on = on; this.low = low; this.high = high; } @Override public String toString() { return on ? "[ " + low + ", " + high + " ]" : "OFF"; } } /** * Bitrate limits for resolution. */ public class ResolutionBitrateLimits { /** * Maximum size of video frame, in pixels, the bitrate limits are intended for. */ public final int frameSizePixels; /** * Recommended minimum bitrate to start encoding. */ public final int minStartBitrateBps; /** * Recommended minimum bitrate. */ public final int minBitrateBps; /** * Recommended maximum bitrate. */ public final int maxBitrateBps; public ResolutionBitrateLimits( int frameSizePixels, int minStartBitrateBps, int minBitrateBps, int maxBitrateBps) { this.frameSizePixels = frameSizePixels; this.minStartBitrateBps = minStartBitrateBps; this.minBitrateBps = minBitrateBps; this.maxBitrateBps = maxBitrateBps; } @CalledByNative("ResolutionBitrateLimits") public int getFrameSizePixels() { return frameSizePixels; } @CalledByNative("ResolutionBitrateLimits") public int getMinStartBitrateBps() { return minStartBitrateBps; } @CalledByNative("ResolutionBitrateLimits") public int getMinBitrateBps() { return minBitrateBps; } @CalledByNative("ResolutionBitrateLimits") public int getMaxBitrateBps() { return maxBitrateBps; } } /** Rate control parameters. */ public class RateControlParameters { /** * Adjusted target bitrate, per spatial/temporal layer. May be lower or higher than the target * depending on encoder behaviour. */ public final BitrateAllocation bitrate; /** * Target framerate, in fps. A value <= 0.0 is invalid and should be interpreted as framerate * target not available. In this case the encoder should fall back to the max framerate * specified in `codec_settings` of the last InitEncode() call. */ public final double framerateFps; @CalledByNative("RateControlParameters") public RateControlParameters(BitrateAllocation bitrate, double framerateFps) { this.bitrate = bitrate; this.framerateFps = framerateFps; } } /** * Metadata about the Encoder. */ public class EncoderInfo { /** * The width and height of the incoming video frames should be divisible by * |requested_resolution_alignment| */ public final int requestedResolutionAlignment; /** * Same as above but if true, each simulcast layer should also be divisible by * |requested_resolution_alignment|. */ public final boolean applyAlignmentToAllSimulcastLayers; public EncoderInfo( int requestedResolutionAlignment, boolean applyAlignmentToAllSimulcastLayers) { this.requestedResolutionAlignment = requestedResolutionAlignment; this.applyAlignmentToAllSimulcastLayers = applyAlignmentToAllSimulcastLayers; } @CalledByNative("EncoderInfo") public int getRequestedResolutionAlignment() { return requestedResolutionAlignment; } @CalledByNative("EncoderInfo") public boolean getApplyAlignmentToAllSimulcastLayers() { return applyAlignmentToAllSimulcastLayers; } } public interface Callback { /** * Old encoders assume that the byte buffer held by `frame` is not accessed after the call to * this method returns. If the pipeline downstream needs to hold on to the buffer, it then has * to make its own copy. We want to move to a model where no copying is needed, and instead use * retain()/release() to signal to the encoder when it is safe to reuse the buffer. * * Over the transition, implementations of this class should use the maybeRetain() method if * they want to keep a reference to the buffer, and fall back to copying if that method returns * false. */ void onEncodedFrame(EncodedImage frame, CodecSpecificInfo info); } /** * The encoder implementation backing this interface is either 1) a Java * encoder (e.g., an Android platform encoder), or alternatively 2) a native * encoder (e.g., a software encoder or a C++ encoder adapter). * * For case 1), createNativeVideoEncoder() should return zero. * In this case, we expect the native library to call the encoder through * JNI using the Java interface declared below. * * For case 2), createNativeVideoEncoder() should return a non-zero value. * In this case, we expect the native library to treat the returned value as * a raw pointer of type webrtc::VideoEncoder* (ownership is transferred to * the caller). The native library should then directly call the * webrtc::VideoEncoder interface without going through JNI. All calls to * the Java interface methods declared below should thus throw an * UnsupportedOperationException. */ @CalledByNative default long createNativeVideoEncoder() { return 0; } /** * Returns true if the encoder is backed by hardware. */ @CalledByNative default boolean isHardwareEncoder() { return true; } /** * Initializes the encoding process. Call before any calls to encode. */ @CalledByNative VideoCodecStatus initEncode(Settings settings, Callback encodeCallback); /** * Releases the encoder. No more calls to encode will be made after this call. */ @CalledByNative VideoCodecStatus release(); /** * Requests the encoder to encode a frame. */ @CalledByNative VideoCodecStatus encode(VideoFrame frame, EncodeInfo info); /** Sets the bitrate allocation and the target framerate for the encoder. */ VideoCodecStatus setRateAllocation(BitrateAllocation allocation, int framerate); /** Sets the bitrate allocation and the target framerate for the encoder. */ default @CalledByNative VideoCodecStatus setRates(RateControlParameters rcParameters) { // Round frame rate up to avoid overshoots. int framerateFps = (int) Math.ceil(rcParameters.framerateFps); return setRateAllocation(rcParameters.bitrate, framerateFps); } /** Any encoder that wants to use WebRTC provided quality scaler must implement this method. */ @CalledByNative ScalingSettings getScalingSettings(); /** Returns the list of bitrate limits. */ @CalledByNative default ResolutionBitrateLimits[] getResolutionBitrateLimits() { // TODO(ssilkin): Update downstream projects and remove default implementation. ResolutionBitrateLimits bitrate_limits[] = {}; return bitrate_limits; } /** * Should return a descriptive name for the implementation. Gets called once and cached. May be * called from arbitrary thread. */ @CalledByNative String getImplementationName(); @CalledByNative default EncoderInfo getEncoderInfo() { return new EncoderInfo( /* requestedResolutionAlignment= */ 1, /* applyAlignmentToAllSimulcastLayers= */ false); } }
NekoX-Dev/NekoX
TMessagesProj/src/main/java/org/webrtc/VideoEncoder.java
41,666
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.grid.node.docker; import static java.util.Optional.ofNullable; import static org.openqa.selenium.docker.ContainerConfig.image; import static org.openqa.selenium.remote.Dialect.W3C; import static org.openqa.selenium.remote.http.Contents.string; import static org.openqa.selenium.remote.http.HttpMethod.GET; import static org.openqa.selenium.remote.tracing.Tags.EXCEPTION; import java.io.IOException; import java.io.UncheckedIOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.time.Duration; import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.TimeZone; import java.util.function.Predicate; import java.util.logging.Level; import java.util.logging.Logger; import org.openqa.selenium.Capabilities; import org.openqa.selenium.Dimension; import org.openqa.selenium.ImmutableCapabilities; import org.openqa.selenium.PersistentCapabilities; import org.openqa.selenium.RetrySessionRequestException; import org.openqa.selenium.SessionNotCreatedException; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.docker.Container; import org.openqa.selenium.docker.ContainerConfig; import org.openqa.selenium.docker.ContainerInfo; import org.openqa.selenium.docker.Device; import org.openqa.selenium.docker.Docker; import org.openqa.selenium.docker.Image; import org.openqa.selenium.docker.Port; import org.openqa.selenium.grid.data.CreateSessionRequest; import org.openqa.selenium.grid.node.ActiveSession; import org.openqa.selenium.grid.node.SessionFactory; import org.openqa.selenium.internal.Either; import org.openqa.selenium.internal.Require; import org.openqa.selenium.json.Json; import org.openqa.selenium.net.PortProber; import org.openqa.selenium.remote.Command; import org.openqa.selenium.remote.Dialect; import org.openqa.selenium.remote.DriverCommand; import org.openqa.selenium.remote.ProtocolHandshake; import org.openqa.selenium.remote.Response; import org.openqa.selenium.remote.SessionId; import org.openqa.selenium.remote.http.ClientConfig; import org.openqa.selenium.remote.http.HttpClient; import org.openqa.selenium.remote.http.HttpRequest; import org.openqa.selenium.remote.http.HttpResponse; import org.openqa.selenium.remote.tracing.AttributeKey; import org.openqa.selenium.remote.tracing.AttributeMap; import org.openqa.selenium.remote.tracing.Span; import org.openqa.selenium.remote.tracing.Status; import org.openqa.selenium.remote.tracing.Tracer; import org.openqa.selenium.support.ui.FluentWait; import org.openqa.selenium.support.ui.Wait; public class DockerSessionFactory implements SessionFactory { private static final Logger LOG = Logger.getLogger(DockerSessionFactory.class.getName()); private final Tracer tracer; private final HttpClient.Factory clientFactory; private final Duration sessionTimeout; private final Docker docker; private final URI dockerUri; private final Image browserImage; private final Capabilities stereotype; private final List<Device> devices; private final Image videoImage; private final DockerAssetsPath assetsPath; private final String networkName; private final boolean runningInDocker; private final Predicate<Capabilities> predicate; private final Map<String, Object> hostConfig; private final List<String> hostConfigKeys; public DockerSessionFactory( Tracer tracer, HttpClient.Factory clientFactory, Duration sessionTimeout, Docker docker, URI dockerUri, Image browserImage, Capabilities stereotype, List<Device> devices, Image videoImage, DockerAssetsPath assetsPath, String networkName, boolean runningInDocker, Predicate<Capabilities> predicate, Map<String, Object> hostConfig, List<String> hostConfigKeys) { this.tracer = Require.nonNull("Tracer", tracer); this.clientFactory = Require.nonNull("HTTP client", clientFactory); this.sessionTimeout = Require.nonNull("Session timeout", sessionTimeout); this.docker = Require.nonNull("Docker command", docker); this.dockerUri = Require.nonNull("Docker URI", dockerUri); this.browserImage = Require.nonNull("Docker browser image", browserImage); this.networkName = Require.nonNull("Docker network name", networkName); this.stereotype = ImmutableCapabilities.copyOf(Require.nonNull("Stereotype", stereotype)); this.devices = Require.nonNull("Container devices", devices); this.videoImage = videoImage; this.assetsPath = assetsPath; this.runningInDocker = runningInDocker; this.predicate = Require.nonNull("Accepted capabilities predicate", predicate); this.hostConfig = Require.nonNull("Container host config", hostConfig); this.hostConfigKeys = Require.nonNull("Browser container host config keys", hostConfigKeys); } @Override public Capabilities getStereotype() { return stereotype; } @Override public boolean test(Capabilities capabilities) { return predicate.test(capabilities); } @Override public Either<WebDriverException, ActiveSession> apply(CreateSessionRequest sessionRequest) { LOG.info("Starting session for " + sessionRequest.getDesiredCapabilities()); int port = runningInDocker ? 4444 : PortProber.findFreePort(); try (Span span = tracer.getCurrentContext().createSpan("docker_session_factory.apply")) { AttributeMap attributeMap = tracer.createAttributeMap(); attributeMap.put(AttributeKey.LOGGER_CLASS.getKey(), this.getClass().getName()); String logMessage = runningInDocker ? "Creating container..." : "Creating container, mapping container port 4444 to " + port; LOG.info(logMessage); Container container = createBrowserContainer(port, sessionRequest.getDesiredCapabilities()); container.start(); ContainerInfo containerInfo = container.inspect(); String containerIp = containerInfo.getIp(); URL remoteAddress = getUrl(port, containerIp); ClientConfig clientConfig = ClientConfig.defaultConfig().baseUrl(remoteAddress).readTimeout(sessionTimeout); HttpClient client = clientFactory.createClient(clientConfig); attributeMap.put("docker.browser.image", browserImage.toString()); attributeMap.put("container.port", port); attributeMap.put("container.id", container.getId().toString()); attributeMap.put("container.ip", containerIp); attributeMap.put("docker.server.url", remoteAddress.toString()); LOG.info( String.format( "Waiting for server to start (container id: %s, url %s)", container.getId(), remoteAddress)); try { waitForServerToStart(client, Duration.ofMinutes(1)); } catch (TimeoutException e) { span.setAttribute(AttributeKey.ERROR.getKey(), true); span.setStatus(Status.CANCELLED); EXCEPTION.accept(attributeMap, e); attributeMap.put( AttributeKey.EXCEPTION_MESSAGE.getKey(), "Unable to connect to docker server. Stopping container: " + e.getMessage()); span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap); container.stop(Duration.ofMinutes(1)); String message = String.format( "Unable to connect to docker server (container id: %s)", container.getId()); LOG.warning(message); return Either.left(new RetrySessionRequestException(message)); } LOG.info(String.format("Server is ready (container id: %s)", container.getId())); Command command = new Command(null, DriverCommand.NEW_SESSION(sessionRequest.getDesiredCapabilities())); ProtocolHandshake.Result result; Response response; try { result = new ProtocolHandshake().createSession(client, command); response = result.createResponse(); attributeMap.put(AttributeKey.DRIVER_RESPONSE.getKey(), response.toString()); } catch (IOException | RuntimeException e) { span.setAttribute(AttributeKey.ERROR.getKey(), true); span.setStatus(Status.CANCELLED); EXCEPTION.accept(attributeMap, e); attributeMap.put( AttributeKey.EXCEPTION_MESSAGE.getKey(), "Unable to create session. Stopping and container: " + e.getMessage()); span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap); container.stop(Duration.ofMinutes(1)); String message = "Unable to create session: " + e.getMessage(); LOG.log(Level.WARNING, message, e); return Either.left(new SessionNotCreatedException(message)); } SessionId id = new SessionId(response.getSessionId()); Capabilities capabilities = new ImmutableCapabilities((Map<?, ?>) response.getValue()); Capabilities mergedCapabilities = sessionRequest.getDesiredCapabilities().merge(capabilities); mergedCapabilities = addForwardCdpEndpoint(mergedCapabilities, containerIp, port, id.toString()); Container videoContainer = null; Optional<DockerAssetsPath> path = ofNullable(this.assetsPath); if (path.isPresent()) { // Seems we can store session assets String containerPath = path.get().getContainerPath(id); saveSessionCapabilities(mergedCapabilities, containerPath); String hostPath = path.get().getHostPath(id); videoContainer = startVideoContainer(mergedCapabilities, containerIp, hostPath); } Dialect downstream = sessionRequest.getDownstreamDialects().contains(result.getDialect()) ? result.getDialect() : W3C; attributeMap.put(AttributeKey.DOWNSTREAM_DIALECT.getKey(), downstream.toString()); attributeMap.put(AttributeKey.DRIVER_RESPONSE.getKey(), response.toString()); span.addEvent("Docker driver service created session", attributeMap); LOG.fine( String.format( "Created session: %s - %s (container id: %s)", id, mergedCapabilities, container.getId())); return Either.right( new DockerSession( container, videoContainer, tracer, client, id, remoteAddress, stereotype, mergedCapabilities, downstream, result.getDialect(), Instant.now(), assetsPath)); } } private Capabilities addForwardCdpEndpoint( Capabilities sessionCapabilities, String containerIp, int port, String sessionId) { // We add this endpoint to go around the situation where a user wants to do CDP over // Dynamic Grid. In a conventional Grid setup, this is not needed because the browser will // be running on the same host where the Node is running. However, in Dynamic Grid, the Docker // Node is running on a different host/container. Therefore, we need to forward the websocket // connection to the container where the actual browser is running. String forwardCdpPath = String.format("ws://%s:%s/session/%s/se/fwd", containerIp, port, sessionId); return new PersistentCapabilities(sessionCapabilities) .setCapability("se:forwardCdp", forwardCdpPath); } private Container createBrowserContainer(int port, Capabilities sessionCapabilities) { Map<String, String> browserContainerEnvVars = getBrowserContainerEnvVars(sessionCapabilities); long browserContainerShmMemorySize = 2147483648L; // 2GB ContainerConfig containerConfig = image(browserImage) .env(browserContainerEnvVars) .shmMemorySize(browserContainerShmMemorySize) .network(networkName) .devices(devices) .applyHostConfig(hostConfig, hostConfigKeys); if (!runningInDocker) { containerConfig = containerConfig.map(Port.tcp(4444), Port.tcp(port)); } LOG.fine("Container config: " + containerConfig); return docker.create(containerConfig); } private Map<String, String> getBrowserContainerEnvVars(Capabilities sessionRequestCapabilities) { Map<String, String> envVars = new HashMap<>(); // Passing env vars set to the child container setEnvVarsToContainer(envVars); // Capabilities set to env vars with higher precedence setCapsToEnvVars(sessionRequestCapabilities, envVars); return envVars; } private void setEnvVarsToContainer(Map<String, String> envVars) { Map<String, String> seEnvVars = System.getenv(); seEnvVars.entrySet().stream() .filter( entry -> entry.getKey().startsWith("SE_") || entry.getKey().equalsIgnoreCase("LANGUAGE")) .forEach(entry -> envVars.put(entry.getKey(), entry.getValue())); } private void setCapsToEnvVars( Capabilities sessionRequestCapabilities, Map<String, String> envVars) { Optional<Dimension> screenResolution = ofNullable(getScreenResolution(sessionRequestCapabilities)); screenResolution.ifPresent( dimension -> { envVars.put("SE_SCREEN_WIDTH", String.valueOf(dimension.getWidth())); envVars.put("SE_SCREEN_HEIGHT", String.valueOf(dimension.getHeight())); }); Optional<TimeZone> timeZone = ofNullable(getTimeZone(sessionRequestCapabilities)); timeZone.ifPresent(zone -> envVars.put("TZ", zone.getID())); } private Container startVideoContainer( Capabilities sessionCapabilities, String browserContainerIp, String hostPath) { if (!recordVideoForSession(sessionCapabilities)) { return null; } int videoPort = 9000; Map<String, String> envVars = getVideoContainerEnvVars(sessionCapabilities, browserContainerIp); Map<String, String> volumeBinds = Collections.singletonMap(hostPath, "/videos"); ContainerConfig containerConfig = image(videoImage).env(envVars).bind(volumeBinds).network(networkName); if (!runningInDocker) { videoPort = PortProber.findFreePort(); containerConfig = containerConfig.map(Port.tcp(9000), Port.tcp(videoPort)); } Container videoContainer = docker.create(containerConfig); videoContainer.start(); String videoContainerIp = runningInDocker ? videoContainer.inspect().getIp() : "localhost"; try { URL videoContainerUrl = new URL(String.format("http://%s:%s", videoContainerIp, videoPort)); HttpClient videoClient = clientFactory.createClient(videoContainerUrl); LOG.fine(String.format("Waiting for video recording... (id: %s)", videoContainer.getId())); waitForServerToStart(videoClient, Duration.ofMinutes(1)); } catch (Exception e) { videoContainer.stop(Duration.ofSeconds(10)); String message = String.format( "Unable to verify video recording started (container id: %s), %s", videoContainer.getId(), e.getMessage()); LOG.warning(message); } LOG.info(String.format("Video container started (id: %s)", videoContainer.getId())); return videoContainer; } private Map<String, String> getVideoContainerEnvVars( Capabilities sessionRequestCapabilities, String containerIp) { Map<String, String> envVars = new HashMap<>(); // Passing env vars set to the child container setEnvVarsToContainer(envVars); // Capabilities set to env vars with higher precedence setCapsToEnvVars(sessionRequestCapabilities, envVars); envVars.put("DISPLAY_CONTAINER_NAME", containerIp); Optional<String> testName = ofNullable(getTestName(sessionRequestCapabilities)); testName.ifPresent(name -> envVars.put("SE_VIDEO_FILE_NAME", String.format("%s.mp4", name))); return envVars; } private String getTestName(Capabilities sessionRequestCapabilities) { Optional<Object> testName = ofNullable(sessionRequestCapabilities.getCapability("se:name")); if (testName.isPresent()) { String name = testName.get().toString(); if (!name.isEmpty()) { name = name.replaceAll(" ", "_").replaceAll("[^a-zA-Z0-9_-]", ""); if (name.length() > 251) { name = name.substring(0, 251); } return name; } } return null; } private TimeZone getTimeZone(Capabilities sessionRequestCapabilities) { Optional<Object> timeZone = ofNullable(sessionRequestCapabilities.getCapability("se:timeZone")); if (timeZone.isPresent()) { String tz = timeZone.get().toString(); if (Arrays.asList(TimeZone.getAvailableIDs()).contains(tz)) { return TimeZone.getTimeZone(tz); } } String envTz = System.getenv("TZ"); if (Arrays.asList(TimeZone.getAvailableIDs()).contains(envTz)) { return TimeZone.getTimeZone(envTz); } return null; } private Dimension getScreenResolution(Capabilities sessionRequestCapabilities) { Optional<Object> screenResolution = ofNullable(sessionRequestCapabilities.getCapability("se:screenResolution")); if (!screenResolution.isPresent()) { return null; } try { String[] resolution = screenResolution.get().toString().split("x"); int screenWidth = Integer.parseInt(resolution[0]); int screenHeight = Integer.parseInt(resolution[1]); if (screenWidth > 0 && screenHeight > 0) { return new Dimension(screenWidth, screenHeight); } else { LOG.warning( "One of the values provided for screenResolution is negative, " + "defaults will be used. Received value: " + screenResolution); } } catch (Exception e) { LOG.warning( "Values provided for screenResolution are not valid integers or " + "either width or height are missing, defaults will be used." + "Received value: " + screenResolution); } return null; } private boolean recordVideoForSession(Capabilities sessionRequestCapabilities) { Optional<Object> recordVideo = ofNullable(sessionRequestCapabilities.getCapability("se:recordVideo")); return recordVideo.isPresent() && Boolean.parseBoolean(recordVideo.get().toString()); } private void saveSessionCapabilities(Capabilities sessionRequestCapabilities, String path) { String capsToJson = new Json().toJson(sessionRequestCapabilities); try { Files.createDirectories(Paths.get(path)); Files.write( Paths.get(path, "sessionCapabilities.json"), capsToJson.getBytes(Charset.defaultCharset())); } catch (IOException e) { LOG.log(Level.WARNING, "Failed to save session capabilities", e); } } private void waitForServerToStart(HttpClient client, Duration duration) { Wait<Object> wait = new FluentWait<>(new Object()).withTimeout(duration).ignoring(UncheckedIOException.class); wait.until( obj -> { HttpResponse response = client.execute(new HttpRequest(GET, "/status")); LOG.fine(string(response)); return 200 == response.getStatus(); }); } private URL getUrl(int port, String containerIp) { try { String host = "localhost"; if (runningInDocker) { host = containerIp; } else { if (dockerUri.getScheme().startsWith("tcp") || dockerUri.getScheme().startsWith("http")) { host = dockerUri.getHost(); } } return new URL(String.format("http://%s:%s/wd/hub", host, port)); } catch (MalformedURLException e) { throw new SessionNotCreatedException(e.getMessage(), e); } } }
SeleniumHQ/selenium
java/src/org/openqa/selenium/grid/node/docker/DockerSessionFactory.java
41,667
/* * This is the source code of Telegram for Android v. 1.3.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-2018. */ package org.telegram.messenger; import android.Manifest; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.annotation.SuppressLint; import android.app.Activity; import android.app.DownloadManager; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothProfile; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.Point; import android.graphics.SurfaceTexture; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.media.AudioDeviceInfo; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioRecord; import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaCodecList; import android.media.MediaExtractor; import android.media.MediaFormat; import android.media.MediaMetadataRetriever; import android.media.MediaRecorder; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.os.PowerManager; import android.os.SystemClock; import android.provider.MediaStore; import android.provider.OpenableColumns; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Pair; import android.util.SparseArray; import android.view.HapticFeedbackConstants; import android.view.TextureView; import android.view.View; import android.view.WindowManager; import android.webkit.MimeTypeMap; import android.widget.FrameLayout; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.ExoPlayer; import com.google.android.exoplayer2.ui.AspectRatioFrameLayout; import org.telegram.messenger.audioinfo.AudioInfo; import org.telegram.messenger.video.MediaCodecVideoConvertor; import org.telegram.messenger.voip.VoIPService; import org.telegram.tgnet.AbstractSerializedData; import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import org.telegram.tgnet.tl.TL_stories; import org.telegram.ui.ActionBar.AlertDialog; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.Adapters.FiltersView; import org.telegram.ui.ChatActivity; import org.telegram.ui.Components.EmbedBottomSheet; import org.telegram.ui.Components.PhotoFilterView; import org.telegram.ui.Components.PipRoundVideoView; import org.telegram.ui.Components.Reactions.ReactionsLayoutInBubble; import org.telegram.ui.Components.VideoPlayer; import org.telegram.ui.LaunchActivity; import org.telegram.ui.PhotoViewer; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Method; import java.net.URLEncoder; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; public class MediaController implements AudioManager.OnAudioFocusChangeListener, NotificationCenter.NotificationCenterDelegate, SensorEventListener { private native int startRecord(String path, int sampleRate); private native int resumeRecord(String path, int sampleRate); private native int writeFrame(ByteBuffer frame, int len); private native void stopRecord(boolean allowResuming); public static native int isOpusFile(String path); public static native byte[] getWaveform(String path); public native byte[] getWaveform2(short[] array, int length); public boolean isBuffering() { if (audioPlayer != null) { return audioPlayer.isBuffering(); } return false; } public VideoConvertMessage getCurrentForegroundConverMessage() { return currentForegroundConvertingVideo; } private static class AudioBuffer { public AudioBuffer(int capacity) { buffer = ByteBuffer.allocateDirect(capacity); bufferBytes = new byte[capacity]; } ByteBuffer buffer; byte[] bufferBytes; int size; int finished; long pcmOffset; } private static final String[] projectionPhotos = { MediaStore.Images.Media._ID, MediaStore.Images.Media.BUCKET_ID, MediaStore.Images.Media.BUCKET_DISPLAY_NAME, MediaStore.Images.Media.DATA, Build.VERSION.SDK_INT > 28 ? MediaStore.Images.Media.DATE_MODIFIED : MediaStore.Images.Media.DATE_TAKEN, MediaStore.Images.Media.ORIENTATION, MediaStore.Images.Media.WIDTH, MediaStore.Images.Media.HEIGHT, MediaStore.Images.Media.SIZE }; private static final String[] projectionVideo = { MediaStore.Video.Media._ID, MediaStore.Video.Media.BUCKET_ID, MediaStore.Video.Media.BUCKET_DISPLAY_NAME, MediaStore.Video.Media.DATA, Build.VERSION.SDK_INT > 28 ? MediaStore.Images.Media.DATE_MODIFIED : MediaStore.Video.Media.DATE_TAKEN, MediaStore.Video.Media.DURATION, MediaStore.Video.Media.WIDTH, MediaStore.Video.Media.HEIGHT, MediaStore.Video.Media.SIZE }; public static class AudioEntry { public long id; public String author; public String title; public String genre; public int duration; public String path; public MessageObject messageObject; } public static class AlbumEntry { public int bucketId; public boolean videoOnly; public String bucketName; public PhotoEntry coverPhoto; public ArrayList<PhotoEntry> photos = new ArrayList<>(); public SparseArray<PhotoEntry> photosByIds = new SparseArray<>(); public AlbumEntry(int bucketId, String bucketName, PhotoEntry coverPhoto) { this.bucketId = bucketId; this.bucketName = bucketName; this.coverPhoto = coverPhoto; } public void addPhoto(PhotoEntry photoEntry) { photos.add(photoEntry); photosByIds.put(photoEntry.imageId, photoEntry); } } public static class SavedFilterState { public float enhanceValue; public float softenSkinValue; public float exposureValue; public float contrastValue; public float warmthValue; public float saturationValue; public float fadeValue; public int tintShadowsColor; public int tintHighlightsColor; public float highlightsValue; public float shadowsValue; public float vignetteValue; public float grainValue; public int blurType; public float sharpenValue; public PhotoFilterView.CurvesToolValue curvesToolValue = new PhotoFilterView.CurvesToolValue(); public float blurExcludeSize; public org.telegram.ui.Components.Point blurExcludePoint; public float blurExcludeBlurSize; public float blurAngle; public void serializeToStream(AbstractSerializedData stream) { stream.writeFloat(enhanceValue); stream.writeFloat(softenSkinValue); stream.writeFloat(exposureValue); stream.writeFloat(contrastValue); stream.writeFloat(warmthValue); stream.writeFloat(saturationValue); stream.writeFloat(fadeValue); stream.writeInt32(tintShadowsColor); stream.writeInt32(tintHighlightsColor); stream.writeFloat(highlightsValue); stream.writeFloat(shadowsValue); stream.writeFloat(vignetteValue); stream.writeFloat(grainValue); stream.writeInt32(blurType); stream.writeFloat(sharpenValue); curvesToolValue.serializeToStream(stream); stream.writeFloat(blurExcludeSize); if (blurExcludePoint == null) { stream.writeInt32(0x56730bcc); } else { stream.writeInt32(0xDEADBEEF); stream.writeFloat(blurExcludePoint.x); stream.writeFloat(blurExcludePoint.y); } stream.writeFloat(blurExcludeBlurSize); stream.writeFloat(blurAngle); } public void readParams(AbstractSerializedData stream, boolean exception) { enhanceValue = stream.readFloat(exception); softenSkinValue = stream.readFloat(exception); exposureValue = stream.readFloat(exception); contrastValue = stream.readFloat(exception); warmthValue = stream.readFloat(exception); saturationValue = stream.readFloat(exception); fadeValue = stream.readFloat(exception); tintShadowsColor = stream.readInt32(exception); tintHighlightsColor = stream.readInt32(exception); highlightsValue = stream.readFloat(exception); shadowsValue = stream.readFloat(exception); vignetteValue = stream.readFloat(exception); grainValue = stream.readFloat(exception); blurType = stream.readInt32(exception); sharpenValue = stream.readFloat(exception); curvesToolValue.readParams(stream, exception); blurExcludeSize = stream.readFloat(exception); int magic = stream.readInt32(exception); if (magic == 0x56730bcc) { blurExcludePoint = null; } else { if (blurExcludePoint == null) { blurExcludePoint = new org.telegram.ui.Components.Point(); } blurExcludePoint.x = stream.readFloat(exception); blurExcludePoint.y = stream.readFloat(exception); } blurExcludeBlurSize = stream.readFloat(exception); blurAngle = stream.readFloat(exception); } public boolean isEmpty() { return ( Math.abs(enhanceValue) < 0.1f && Math.abs(softenSkinValue) < 0.1f && Math.abs(exposureValue) < 0.1f && Math.abs(contrastValue) < 0.1f && Math.abs(warmthValue) < 0.1f && Math.abs(saturationValue) < 0.1f && Math.abs(fadeValue) < 0.1f && tintShadowsColor == 0 && tintHighlightsColor == 0 && Math.abs(highlightsValue) < 0.1f && Math.abs(shadowsValue) < 0.1f && Math.abs(vignetteValue) < 0.1f && Math.abs(grainValue) < 0.1f && blurType == 0 && Math.abs(sharpenValue) < 0.1f ); } } public static class CropState { public float cropPx; public float cropPy; public float cropScale = 1; public float cropRotate; public float cropPw = 1; public float cropPh = 1; public int transformWidth; public int transformHeight; public int transformRotation; public boolean mirrored; public float stateScale; public float scale; public Matrix matrix; public int width; public int height; public boolean freeform; public float lockedAspectRatio; public Matrix useMatrix; public boolean initied; @Override public CropState clone() { CropState cloned = new CropState(); cloned.cropPx = this.cropPx; cloned.cropPy = this.cropPy; cloned.cropScale = this.cropScale; cloned.cropRotate = this.cropRotate; cloned.cropPw = this.cropPw; cloned.cropPh = this.cropPh; cloned.transformWidth = this.transformWidth; cloned.transformHeight = this.transformHeight; cloned.transformRotation = this.transformRotation; cloned.mirrored = this.mirrored; cloned.stateScale = this.stateScale; cloned.scale = this.scale; cloned.matrix = this.matrix; cloned.width = this.width; cloned.height = this.height; cloned.freeform = this.freeform; cloned.lockedAspectRatio = this.lockedAspectRatio; cloned.initied = this.initied; cloned.useMatrix = this.useMatrix; return cloned; } public boolean isEmpty() { return (matrix == null || matrix.isIdentity()) && (useMatrix == null || useMatrix.isIdentity()) && cropPw == 1 && cropPh == 1 && cropScale == 1 && cropRotate == 0 && transformWidth == 0 && transformHeight == 0 && transformRotation == 0 && !mirrored && stateScale == 0 && scale == 0 && width == 0 && height == 0 && !freeform && lockedAspectRatio == 0; } } public static class MediaEditState { public CharSequence caption; public String thumbPath; public String imagePath; public String filterPath; public String paintPath; public String croppedPaintPath; public String fullPaintPath; public ArrayList<TLRPC.MessageEntity> entities; public SavedFilterState savedFilterState; public ArrayList<VideoEditedInfo.MediaEntity> mediaEntities; public ArrayList<VideoEditedInfo.MediaEntity> croppedMediaEntities; public ArrayList<TLRPC.InputDocument> stickers; public VideoEditedInfo editedInfo; public long averageDuration; public boolean isFiltered; public boolean isPainted; public boolean isCropped; public int ttl; public CropState cropState; public String getPath() { return null; } public void reset() { caption = null; thumbPath = null; filterPath = null; imagePath = null; paintPath = null; croppedPaintPath = null; isFiltered = false; isPainted = false; isCropped = false; ttl = 0; mediaEntities = null; editedInfo = null; entities = null; savedFilterState = null; stickers = null; cropState = null; } public void copyFrom(MediaEditState state) { caption = state.caption; thumbPath = state.thumbPath; imagePath = state.imagePath; filterPath = state.filterPath; paintPath = state.paintPath; croppedPaintPath = state.croppedPaintPath; fullPaintPath = state.fullPaintPath; entities = state.entities; savedFilterState = state.savedFilterState; mediaEntities = state.mediaEntities; croppedMediaEntities = state.croppedMediaEntities; stickers = state.stickers; editedInfo = state.editedInfo; averageDuration = state.averageDuration; isFiltered = state.isFiltered; isPainted = state.isPainted; isCropped = state.isCropped; ttl = state.ttl; cropState = state.cropState; } } public static class PhotoEntry extends MediaEditState { public int bucketId; public int imageId; public long dateTaken; public int duration; public int width; public int height; public long size; public String path; public int orientation; public int invert; public boolean isVideo; public boolean isMuted; public boolean canDeleteAfter; public boolean hasSpoiler; public String emoji; public boolean isChatPreviewSpoilerRevealed; public boolean isAttachSpoilerRevealed; public TLRPC.VideoSize emojiMarkup; public int gradientTopColor, gradientBottomColor; public PhotoEntry(int bucketId, int imageId, long dateTaken, String path, int orientationOrDuration, boolean isVideo, int width, int height, long size) { this.bucketId = bucketId; this.imageId = imageId; this.dateTaken = dateTaken; this.path = path; this.width = width; this.height = height; this.size = size; if (isVideo) { this.duration = orientationOrDuration; } else { this.orientation = orientationOrDuration; } this.isVideo = isVideo; } public PhotoEntry setOrientation(Pair<Integer, Integer> rotationAndInvert) { this.orientation = rotationAndInvert.first; this.invert = rotationAndInvert.second; return this; } public PhotoEntry setOrientation(int rotation, int invert) { this.orientation = rotation; this.invert = invert; return this; } @Override public void copyFrom(MediaEditState state) { super.copyFrom(state); this.hasSpoiler = state instanceof PhotoEntry && ((PhotoEntry) state).hasSpoiler; } public PhotoEntry clone() { PhotoEntry photoEntry = new PhotoEntry(bucketId, imageId, dateTaken, path, isVideo ? duration : orientation, isVideo, width, height, size); photoEntry.invert = invert; photoEntry.isMuted = isMuted; photoEntry.canDeleteAfter = canDeleteAfter; photoEntry.hasSpoiler = hasSpoiler; photoEntry.isChatPreviewSpoilerRevealed = isChatPreviewSpoilerRevealed; photoEntry.isAttachSpoilerRevealed = isAttachSpoilerRevealed; photoEntry.emojiMarkup = emojiMarkup; photoEntry.gradientTopColor = gradientTopColor; photoEntry.gradientBottomColor = gradientBottomColor; photoEntry.copyFrom(this); return photoEntry; } @Override public String getPath() { return path; } @Override public void reset() { if (isVideo) { if (filterPath != null) { new File(filterPath).delete(); filterPath = null; } } hasSpoiler = false; super.reset(); } public void deleteAll() { if (path != null) { try { new File(path).delete(); } catch (Exception ignore) {} } if (fullPaintPath != null) { try { new File(fullPaintPath).delete(); } catch (Exception ignore) {} } if (paintPath != null) { try { new File(paintPath).delete(); } catch (Exception ignore) {} } if (imagePath != null) { try { new File(imagePath).delete(); } catch (Exception ignore) {} } if (filterPath != null) { try { new File(filterPath).delete(); } catch (Exception ignore) {} } if (croppedPaintPath != null) { try { new File(croppedPaintPath).delete(); } catch (Exception ignore) {} } } } public static class SearchImage extends MediaEditState { public String id; public String imageUrl; public String thumbUrl; public int width; public int height; public int size; public int type; public int date; public CharSequence caption; public TLRPC.Document document; public TLRPC.Photo photo; public TLRPC.PhotoSize photoSize; public TLRPC.PhotoSize thumbPhotoSize; public TLRPC.BotInlineResult inlineResult; public HashMap<String, String> params; @Override public String getPath() { if (photoSize != null) { return FileLoader.getInstance(UserConfig.selectedAccount).getPathToAttach(photoSize, true).getAbsolutePath(); } else if (document != null) { return FileLoader.getInstance(UserConfig.selectedAccount).getPathToAttach(document, true).getAbsolutePath(); } else { return ImageLoader.getHttpFilePath(imageUrl, "jpg").getAbsolutePath(); } } @Override public void reset() { super.reset(); } public String getAttachName() { if (photoSize != null) { return FileLoader.getAttachFileName(photoSize); } else if (document != null) { return FileLoader.getAttachFileName(document); } return Utilities.MD5(imageUrl) + "." + ImageLoader.getHttpUrlExtension(imageUrl, "jpg"); } public String getPathToAttach() { if (photoSize != null) { return FileLoader.getInstance(UserConfig.selectedAccount).getPathToAttach(photoSize, true).getAbsolutePath(); } else if (document != null) { return FileLoader.getInstance(UserConfig.selectedAccount).getPathToAttach(document, true).getAbsolutePath(); } else { return imageUrl; } } public SearchImage clone() { SearchImage searchImage = new SearchImage(); searchImage.id = id; searchImage.imageUrl = imageUrl; searchImage.thumbUrl = thumbUrl; searchImage.width = width; searchImage.height = height; searchImage.size = size; searchImage.type = type; searchImage.date = date; searchImage.caption = caption; searchImage.document = document; searchImage.photo = photo; searchImage.photoSize = photoSize; searchImage.thumbPhotoSize = thumbPhotoSize; searchImage.inlineResult = inlineResult; searchImage.params = params; return searchImage; } } AudioManager.OnAudioFocusChangeListener audioRecordFocusChangedListener = focusChange -> { if (focusChange != AudioManager.AUDIOFOCUS_GAIN) { hasRecordAudioFocus = false; } }; public final static int VIDEO_BITRATE_1080 = 6800_000; public final static int VIDEO_BITRATE_720 = 2621_440; public final static int VIDEO_BITRATE_480 = 1000_000; public final static int VIDEO_BITRATE_360 = 750_000; public final static String VIDEO_MIME_TYPE = "video/avc"; public final static String AUDIO_MIME_TYPE = "audio/mp4a-latm"; private final Object videoConvertSync = new Object(); private SensorManager sensorManager; private boolean ignoreProximity; private PowerManager.WakeLock proximityWakeLock; private Sensor proximitySensor; private Sensor accelerometerSensor; private Sensor linearSensor; private Sensor gravitySensor; private boolean raiseToEarRecord; private ChatActivity raiseChat; private boolean accelerometerVertical; private long lastAccelerometerDetected; private int raisedToTop; private int raisedToTopSign; private int raisedToBack; private int countLess; private long timeSinceRaise; private long lastTimestamp = 0; private boolean proximityTouched; private boolean proximityHasDifferentValues; private float lastProximityValue = -100; private boolean useFrontSpeaker; private boolean inputFieldHasText; private boolean allowStartRecord; private boolean ignoreOnPause; private boolean sensorsStarted; private float previousAccValue; private float[] gravity = new float[3]; private float[] gravityFast = new float[3]; private float[] linearAcceleration = new float[3]; private int hasAudioFocus; private boolean hasRecordAudioFocus; private boolean callInProgress; private int audioFocus = AUDIO_NO_FOCUS_NO_DUCK; private boolean resumeAudioOnFocusGain; private static final float VOLUME_DUCK = 0.2f; private static final float VOLUME_NORMAL = 1.0f; private static final int AUDIO_NO_FOCUS_NO_DUCK = 0; private static final int AUDIO_NO_FOCUS_CAN_DUCK = 1; private static final int AUDIO_FOCUSED = 2; private static final ConcurrentHashMap<String, Integer> cachedEncoderBitrates = new ConcurrentHashMap<>(); private ArrayList<VideoConvertMessage> foregroundConvertingMessages = new ArrayList<>(); private VideoConvertMessage currentForegroundConvertingVideo; public static class VideoConvertMessage { public MessageObject messageObject; public VideoEditedInfo videoEditedInfo; public int currentAccount; public boolean foreground; public VideoConvertMessage(MessageObject object, VideoEditedInfo info, boolean foreground) { messageObject = object; currentAccount = messageObject.currentAccount; videoEditedInfo = info; this.foreground = foreground; } } private ArrayList<VideoConvertMessage> videoConvertQueue = new ArrayList<>(); private final Object videoQueueSync = new Object(); private HashMap<String, MessageObject> generatingWaveform = new HashMap<>(); private boolean voiceMessagesPlaylistUnread; private ArrayList<MessageObject> voiceMessagesPlaylist; private SparseArray<MessageObject> voiceMessagesPlaylistMap; private static Runnable refreshGalleryRunnable; public static AlbumEntry allMediaAlbumEntry; public static AlbumEntry allPhotosAlbumEntry; public static AlbumEntry allVideosAlbumEntry; public static ArrayList<AlbumEntry> allMediaAlbums = new ArrayList<>(); public static ArrayList<AlbumEntry> allPhotoAlbums = new ArrayList<>(); private static Runnable broadcastPhotosRunnable; public boolean isSilent = false; private boolean isPaused = false; private boolean wasPlayingAudioBeforePause = false; private VideoPlayer audioPlayer = null; private VideoPlayer emojiSoundPlayer = null; private int emojiSoundPlayerNum = 0; private boolean isStreamingCurrentAudio; private int playerNum; private String shouldSavePositionForCurrentAudio; private long lastSaveTime; private float currentPlaybackSpeed = 1.0f; private float currentMusicPlaybackSpeed = 1.0f; private float fastPlaybackSpeed = 1.0f; private float fastMusicPlaybackSpeed = 1.0f; private float seekToProgressPending; private long lastProgress = 0; private MessageObject playingMessageObject; private MessageObject goingToShowMessageObject; private boolean manualRecording; private Timer progressTimer = null; private final Object progressTimerSync = new Object(); private boolean downloadingCurrentMessage; private boolean playMusicAgain; private PlaylistGlobalSearchParams playlistGlobalSearchParams; private AudioInfo audioInfo; private VideoPlayer videoPlayer; private boolean playerWasReady; private TextureView currentTextureView; private PipRoundVideoView pipRoundVideoView; private int pipSwitchingState; private Activity baseActivity; private BaseFragment flagSecureFragment; private View feedbackView; private AspectRatioFrameLayout currentAspectRatioFrameLayout; private boolean isDrawingWasReady; private FrameLayout currentTextureViewContainer; private int currentAspectRatioFrameLayoutRotation; private float currentAspectRatioFrameLayoutRatio; private boolean currentAspectRatioFrameLayoutReady; private ArrayList<MessageObject> playlist = new ArrayList<>(); private HashMap<Integer, MessageObject> playlistMap = new HashMap<>(); private ArrayList<MessageObject> shuffledPlaylist = new ArrayList<>(); private int currentPlaylistNum; private boolean forceLoopCurrentPlaylist; private boolean[] playlistEndReached = new boolean[]{false, false}; private boolean loadingPlaylist; private long playlistMergeDialogId; private int playlistClassGuid; private int[] playlistMaxId = new int[]{Integer.MAX_VALUE, Integer.MAX_VALUE}; private Runnable setLoadingRunnable = new Runnable() { @Override public void run() { if (playingMessageObject == null) { return; } FileLoader.getInstance(playingMessageObject.currentAccount).setLoadingVideo(playingMessageObject.getDocument(), true, false); } }; private boolean audioRecorderPaused; private AudioRecord audioRecorder; public TLRPC.TL_document recordingAudio; private int recordingGuid = -1; private int recordingCurrentAccount; private File recordingAudioFile; private long recordStartTime; public long recordTimeCount; public int writedFrame; private long writedFileLenght; private long recordDialogId; private long recordTopicId; private MessageObject recordReplyingMsg; private MessageObject recordReplyingTopMsg; private TL_stories.StoryItem recordReplyingStory; private String recordQuickReplyShortcut; private int recordQuickReplyShortcutId; public short[] recordSamples = new short[1024]; public long samplesCount; private final Object sync = new Object(); private ArrayList<ByteBuffer> recordBuffers = new ArrayList<>(); private ByteBuffer fileBuffer; public int recordBufferSize = 1280; public int sampleRate = 48000; private int sendAfterDone; private boolean sendAfterDoneNotify; private int sendAfterDoneScheduleDate; private boolean sendAfterDoneOnce; private Runnable recordStartRunnable; private DispatchQueue recordQueue; private DispatchQueue fileEncodingQueue; private Runnable recordRunnable = new Runnable() { @Override public void run() { if (audioRecorder != null) { ByteBuffer buffer; if (!recordBuffers.isEmpty()) { buffer = recordBuffers.get(0); recordBuffers.remove(0); } else { buffer = ByteBuffer.allocateDirect(recordBufferSize); buffer.order(ByteOrder.nativeOrder()); } buffer.rewind(); int len = audioRecorder.read(buffer, buffer.capacity()); if (len > 0) { buffer.limit(len); double sum = 0; try { long newSamplesCount = samplesCount + len / 2; int currentPart = (int) (((double) samplesCount / (double) newSamplesCount) * recordSamples.length); int newPart = recordSamples.length - currentPart; float sampleStep; if (currentPart != 0) { sampleStep = (float) recordSamples.length / (float) currentPart; float currentNum = 0; for (int a = 0; a < currentPart; a++) { recordSamples[a] = recordSamples[(int) currentNum]; currentNum += sampleStep; } } int currentNum = currentPart; float nextNum = 0; sampleStep = (float) len / 2 / (float) newPart; for (int i = 0; i < len / 2; i++) { short peak = buffer.getShort(); if (Build.VERSION.SDK_INT < 21) { if (peak > 2500) { sum += peak * peak; } } else { sum += peak * peak; } if (i == (int) nextNum && currentNum < recordSamples.length) { recordSamples[currentNum] = peak; nextNum += sampleStep; currentNum++; } } samplesCount = newSamplesCount; } catch (Exception e) { FileLog.e(e); } buffer.position(0); final double amplitude = Math.sqrt(sum / len / 2); final ByteBuffer finalBuffer = buffer; final boolean flush = len != buffer.capacity(); fileEncodingQueue.postRunnable(() -> { while (finalBuffer.hasRemaining()) { int oldLimit = -1; if (finalBuffer.remaining() > fileBuffer.remaining()) { oldLimit = finalBuffer.limit(); finalBuffer.limit(fileBuffer.remaining() + finalBuffer.position()); } fileBuffer.put(finalBuffer); if (fileBuffer.position() == fileBuffer.limit() || flush) { if (writeFrame(fileBuffer, !flush ? fileBuffer.limit() : finalBuffer.position()) != 0) { fileBuffer.rewind(); recordTimeCount += fileBuffer.limit() / 2 / (sampleRate / 1000); writedFrame++; } else { FileLog.e("writing frame failed"); } } if (oldLimit != -1) { finalBuffer.limit(oldLimit); } } recordQueue.postRunnable(() -> recordBuffers.add(finalBuffer)); }); recordQueue.postRunnable(recordRunnable); AndroidUtilities.runOnUIThread(() -> NotificationCenter.getInstance(recordingCurrentAccount).postNotificationName(NotificationCenter.recordProgressChanged, recordingGuid, amplitude)); } else { recordBuffers.add(buffer); if (sendAfterDone != 3 && sendAfterDone != 4) { stopRecordingInternal(sendAfterDone, sendAfterDoneNotify, sendAfterDoneScheduleDate, sendAfterDoneOnce); } } } } }; private float audioVolume; private ValueAnimator audioVolumeAnimator; private final ValueAnimator.AnimatorUpdateListener audioVolumeUpdateListener = new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { audioVolume = (float) valueAnimator.getAnimatedValue(); setPlayerVolume(); } }; private class InternalObserver extends ContentObserver { public InternalObserver() { super(null); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); processMediaObserver(MediaStore.Images.Media.INTERNAL_CONTENT_URI); } } private class ExternalObserver extends ContentObserver { public ExternalObserver() { super(null); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); processMediaObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI); } } private static class GalleryObserverInternal extends ContentObserver { public GalleryObserverInternal() { super(null); } private void scheduleReloadRunnable() { AndroidUtilities.runOnUIThread(refreshGalleryRunnable = () -> { if (PhotoViewer.getInstance().isVisible()) { scheduleReloadRunnable(); return; } refreshGalleryRunnable = null; loadGalleryPhotosAlbums(0); }, 2000); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); if (refreshGalleryRunnable != null) { AndroidUtilities.cancelRunOnUIThread(refreshGalleryRunnable); } scheduleReloadRunnable(); } } private static class GalleryObserverExternal extends ContentObserver { public GalleryObserverExternal() { super(null); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); if (refreshGalleryRunnable != null) { AndroidUtilities.cancelRunOnUIThread(refreshGalleryRunnable); } AndroidUtilities.runOnUIThread(refreshGalleryRunnable = () -> { refreshGalleryRunnable = null; loadGalleryPhotosAlbums(0); }, 2000); } } public static void checkGallery() { if (Build.VERSION.SDK_INT < 24 || allPhotosAlbumEntry == null) { return; } final int prevSize = allPhotosAlbumEntry.photos.size(); Utilities.globalQueue.postRunnable(() -> { int count = 0; Cursor cursor = null; try { final Context context = ApplicationLoader.applicationContext; if ( Build.VERSION.SDK_INT >= 33 && ( context.checkSelfPermission(Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED || context.checkSelfPermission(Manifest.permission.READ_MEDIA_VIDEO) == PackageManager.PERMISSION_GRANTED || context.checkSelfPermission(Manifest.permission.READ_MEDIA_AUDIO) == PackageManager.PERMISSION_GRANTED ) || context.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED ) { cursor = MediaStore.Images.Media.query(context.getContentResolver(), MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{"COUNT(_id)"}, null, null, null); if (cursor != null) { if (cursor.moveToNext()) { count += cursor.getInt(0); } } } } catch (Throwable e) { FileLog.e(e); } finally { if (cursor != null) { cursor.close(); } } try { final Context context = ApplicationLoader.applicationContext; if ( Build.VERSION.SDK_INT >= 33 && ( context.checkSelfPermission(Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED || context.checkSelfPermission(Manifest.permission.READ_MEDIA_VIDEO) == PackageManager.PERMISSION_GRANTED || context.checkSelfPermission(Manifest.permission.READ_MEDIA_AUDIO) == PackageManager.PERMISSION_GRANTED ) || context.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED ) { cursor = MediaStore.Images.Media.query(context.getContentResolver(), MediaStore.Video.Media.EXTERNAL_CONTENT_URI, new String[]{"COUNT(_id)"}, null, null, null); if (cursor != null) { if (cursor.moveToNext()) { count += cursor.getInt(0); } } } } catch (Throwable e) { FileLog.e(e); } finally { if (cursor != null) { cursor.close(); } } if (prevSize != count) { if (refreshGalleryRunnable != null) { AndroidUtilities.cancelRunOnUIThread(refreshGalleryRunnable); refreshGalleryRunnable = null; } loadGalleryPhotosAlbums(0); } }, 2000); } private ExternalObserver externalObserver; private InternalObserver internalObserver; private long lastChatEnterTime; private int lastChatAccount; private long lastChatLeaveTime; private long lastMediaCheckTime; private TLRPC.EncryptedChat lastSecretChat; private TLRPC.User lastUser; private int lastMessageId; private ArrayList<Long> lastChatVisibleMessages; private int startObserverToken; private StopMediaObserverRunnable stopMediaObserverRunnable; private final class StopMediaObserverRunnable implements Runnable { public int currentObserverToken = 0; @Override public void run() { if (currentObserverToken == startObserverToken) { try { if (internalObserver != null) { ApplicationLoader.applicationContext.getContentResolver().unregisterContentObserver(internalObserver); internalObserver = null; } } catch (Exception e) { FileLog.e(e); } try { if (externalObserver != null) { ApplicationLoader.applicationContext.getContentResolver().unregisterContentObserver(externalObserver); externalObserver = null; } } catch (Exception e) { FileLog.e(e); } } } } private String[] mediaProjections; private static volatile MediaController Instance; public static MediaController getInstance() { MediaController localInstance = Instance; if (localInstance == null) { synchronized (MediaController.class) { localInstance = Instance; if (localInstance == null) { Instance = localInstance = new MediaController(); } } } return localInstance; } public MediaController() { recordQueue = new DispatchQueue("recordQueue"); recordQueue.setPriority(Thread.MAX_PRIORITY); fileEncodingQueue = new DispatchQueue("fileEncodingQueue"); fileEncodingQueue.setPriority(Thread.MAX_PRIORITY); recordQueue.postRunnable(() -> { try { sampleRate = 48000; int minBuferSize = AudioRecord.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT); if (minBuferSize <= 0) { minBuferSize = 1280; } recordBufferSize = minBuferSize; for (int a = 0; a < 5; a++) { ByteBuffer buffer = ByteBuffer.allocateDirect(recordBufferSize); buffer.order(ByteOrder.nativeOrder()); recordBuffers.add(buffer); } } catch (Exception e) { FileLog.e(e); } }); Utilities.globalQueue.postRunnable(() -> { try { currentPlaybackSpeed = MessagesController.getGlobalMainSettings().getFloat("playbackSpeed", 1.0f); currentMusicPlaybackSpeed = MessagesController.getGlobalMainSettings().getFloat("musicPlaybackSpeed", 1.0f); fastPlaybackSpeed = MessagesController.getGlobalMainSettings().getFloat("fastPlaybackSpeed", 1.8f); fastMusicPlaybackSpeed = MessagesController.getGlobalMainSettings().getFloat("fastMusicPlaybackSpeed", 1.8f); sensorManager = (SensorManager) ApplicationLoader.applicationContext.getSystemService(Context.SENSOR_SERVICE); linearSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION); gravitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY); if (linearSensor == null || gravitySensor == null) { if (BuildVars.LOGS_ENABLED) { FileLog.d("gravity or linear sensor not found"); } accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); linearSensor = null; gravitySensor = null; } proximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY); PowerManager powerManager = (PowerManager) ApplicationLoader.applicationContext.getSystemService(Context.POWER_SERVICE); proximityWakeLock = powerManager.newWakeLock(0x00000020, "telegram:proximity_lock"); } catch (Exception e) { FileLog.e(e); } try { PhoneStateListener phoneStateListener = new PhoneStateListener() { @Override public void onCallStateChanged(final int state, String incomingNumber) { AndroidUtilities.runOnUIThread(() -> { if (state == TelephonyManager.CALL_STATE_RINGING) { if (isPlayingMessage(playingMessageObject) && !isMessagePaused()) { pauseMessage(playingMessageObject); } else if (recordStartRunnable != null || recordingAudio != null) { stopRecording(2, false, 0, false); } EmbedBottomSheet embedBottomSheet = EmbedBottomSheet.getInstance(); if (embedBottomSheet != null) { embedBottomSheet.pause(); } callInProgress = true; } else if (state == TelephonyManager.CALL_STATE_IDLE) { callInProgress = false; } else if (state == TelephonyManager.CALL_STATE_OFFHOOK) { EmbedBottomSheet embedBottomSheet = EmbedBottomSheet.getInstance(); if (embedBottomSheet != null) { embedBottomSheet.pause(); } callInProgress = true; } }); } }; TelephonyManager mgr = (TelephonyManager) ApplicationLoader.applicationContext.getSystemService(Context.TELEPHONY_SERVICE); if (mgr != null) { mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); } } catch (Exception e) { FileLog.e(e); } }); fileBuffer = ByteBuffer.allocateDirect(1920); AndroidUtilities.runOnUIThread(() -> { for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) { NotificationCenter.getInstance(a).addObserver(MediaController.this, NotificationCenter.fileLoaded); NotificationCenter.getInstance(a).addObserver(MediaController.this, NotificationCenter.httpFileDidLoad); NotificationCenter.getInstance(a).addObserver(MediaController.this, NotificationCenter.didReceiveNewMessages); NotificationCenter.getInstance(a).addObserver(MediaController.this, NotificationCenter.messagesDeleted); NotificationCenter.getInstance(a).addObserver(MediaController.this, NotificationCenter.removeAllMessagesFromDialog); NotificationCenter.getInstance(a).addObserver(MediaController.this, NotificationCenter.musicDidLoad); NotificationCenter.getInstance(a).addObserver(MediaController.this, NotificationCenter.mediaDidLoad); NotificationCenter.getGlobalInstance().addObserver(MediaController.this, NotificationCenter.playerDidStartPlaying); } }); mediaProjections = new String[]{ MediaStore.Images.ImageColumns.DATA, MediaStore.Images.ImageColumns.DISPLAY_NAME, MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, Build.VERSION.SDK_INT > 28 ? MediaStore.Images.ImageColumns.DATE_MODIFIED : MediaStore.Images.ImageColumns.DATE_TAKEN, MediaStore.Images.ImageColumns.TITLE, MediaStore.Images.ImageColumns.WIDTH, MediaStore.Images.ImageColumns.HEIGHT }; ContentResolver contentResolver = ApplicationLoader.applicationContext.getContentResolver(); try { contentResolver.registerContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true, new GalleryObserverExternal()); } catch (Exception e) { FileLog.e(e); } try { contentResolver.registerContentObserver(MediaStore.Images.Media.INTERNAL_CONTENT_URI, true, new GalleryObserverInternal()); } catch (Exception e) { FileLog.e(e); } try { contentResolver.registerContentObserver(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, true, new GalleryObserverExternal()); } catch (Exception e) { FileLog.e(e); } try { contentResolver.registerContentObserver(MediaStore.Video.Media.INTERNAL_CONTENT_URI, true, new GalleryObserverInternal()); } catch (Exception e) { FileLog.e(e); } } @Override public void onAudioFocusChange(int focusChange) { AndroidUtilities.runOnUIThread(() -> { if (focusChange == AudioManager.AUDIOFOCUS_LOSS) { if (isPlayingMessage(getPlayingMessageObject()) && !isMessagePaused()) { pauseMessage(playingMessageObject); } hasAudioFocus = 0; audioFocus = AUDIO_NO_FOCUS_NO_DUCK; } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) { audioFocus = AUDIO_FOCUSED; if (resumeAudioOnFocusGain) { resumeAudioOnFocusGain = false; if (isPlayingMessage(getPlayingMessageObject()) && isMessagePaused()) { playMessage(getPlayingMessageObject()); } } } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) { audioFocus = AUDIO_NO_FOCUS_CAN_DUCK; } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) { audioFocus = AUDIO_NO_FOCUS_NO_DUCK; if (isPlayingMessage(getPlayingMessageObject()) && !isMessagePaused()) { pauseMessage(playingMessageObject); resumeAudioOnFocusGain = true; } } setPlayerVolume(); }); } private void setPlayerVolume() { try { float volume; if (isSilent) { volume = 0; } else if (audioFocus != AUDIO_NO_FOCUS_CAN_DUCK) { volume = VOLUME_NORMAL; } else { volume = VOLUME_DUCK; } if (audioPlayer != null) { audioPlayer.setVolume(volume * audioVolume); } else if (videoPlayer != null) { videoPlayer.setVolume(volume); } } catch (Exception e) { FileLog.e(e); } } public VideoPlayer getVideoPlayer() { return videoPlayer; } private void startProgressTimer(final MessageObject currentPlayingMessageObject) { synchronized (progressTimerSync) { if (progressTimer != null) { try { progressTimer.cancel(); progressTimer = null; } catch (Exception e) { FileLog.e(e); } } final String fileName = currentPlayingMessageObject.getFileName(); progressTimer = new Timer(); progressTimer.schedule(new TimerTask() { @Override public void run() { synchronized (sync) { AndroidUtilities.runOnUIThread(() -> { if ((audioPlayer != null || videoPlayer != null) && !isPaused) { try { long duration; long progress; float value; float bufferedValue; if (videoPlayer != null) { duration = videoPlayer.getDuration(); progress = videoPlayer.getCurrentPosition(); if (progress < 0 || duration <= 0) { return; } bufferedValue = videoPlayer.getBufferedPosition() / (float) duration; value = progress / (float) duration; if (value >= 1) { return; } } else { duration = audioPlayer.getDuration(); progress = audioPlayer.getCurrentPosition(); value = duration >= 0 ? (progress / (float) duration) : 0.0f; bufferedValue = audioPlayer.getBufferedPosition() / (float) duration; if (duration == C.TIME_UNSET || progress < 0 || seekToProgressPending != 0) { return; } } lastProgress = progress; currentPlayingMessageObject.audioPlayerDuration = (int) (duration / 1000); currentPlayingMessageObject.audioProgress = value; currentPlayingMessageObject.audioProgressSec = (int) (lastProgress / 1000); currentPlayingMessageObject.bufferedProgress = bufferedValue; if (value >= 0 && shouldSavePositionForCurrentAudio != null && SystemClock.elapsedRealtime() - lastSaveTime >= 1000) { final String saveFor = shouldSavePositionForCurrentAudio; lastSaveTime = SystemClock.elapsedRealtime(); Utilities.globalQueue.postRunnable(() -> { SharedPreferences.Editor editor = ApplicationLoader.applicationContext.getSharedPreferences("media_saved_pos", Activity.MODE_PRIVATE).edit(); editor.putFloat(saveFor, value).commit(); }); } NotificationCenter.getInstance(currentPlayingMessageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingProgressDidChanged, currentPlayingMessageObject.getId(), value); } catch (Exception e) { FileLog.e(e); } } }); } } }, 0, 17); } } private void stopProgressTimer() { synchronized (progressTimerSync) { if (progressTimer != null) { try { progressTimer.cancel(); progressTimer = null; } catch (Exception e) { FileLog.e(e); } } } } public void cleanup() { cleanupPlayer(true, true); audioInfo = null; playMusicAgain = false; for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) { DownloadController.getInstance(a).cleanup(); } videoConvertQueue.clear(); generatingWaveform.clear(); voiceMessagesPlaylist = null; voiceMessagesPlaylistMap = null; clearPlaylist(); cancelVideoConvert(null); } private void clearPlaylist() { playlist.clear(); playlistMap.clear(); shuffledPlaylist.clear(); playlistClassGuid = 0; playlistEndReached[0] = playlistEndReached[1] = false; playlistMergeDialogId = 0; playlistMaxId[0] = playlistMaxId[1] = Integer.MAX_VALUE; loadingPlaylist = false; playlistGlobalSearchParams = null; } public void startMediaObserver() { ApplicationLoader.applicationHandler.removeCallbacks(stopMediaObserverRunnable); startObserverToken++; try { if (internalObserver == null) { ApplicationLoader.applicationContext.getContentResolver().registerContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, false, externalObserver = new ExternalObserver()); } } catch (Exception e) { FileLog.e(e); } try { if (externalObserver == null) { ApplicationLoader.applicationContext.getContentResolver().registerContentObserver(MediaStore.Images.Media.INTERNAL_CONTENT_URI, false, internalObserver = new InternalObserver()); } } catch (Exception e) { FileLog.e(e); } } public void stopMediaObserver() { if (stopMediaObserverRunnable == null) { stopMediaObserverRunnable = new StopMediaObserverRunnable(); } stopMediaObserverRunnable.currentObserverToken = startObserverToken; ApplicationLoader.applicationHandler.postDelayed(stopMediaObserverRunnable, 5000); } private void processMediaObserver(Uri uri) { Cursor cursor = null; try { Point size = AndroidUtilities.getRealScreenSize(); cursor = ApplicationLoader.applicationContext.getContentResolver().query(uri, mediaProjections, null, null, "date_added DESC LIMIT 1"); final ArrayList<Long> screenshotDates = new ArrayList<>(); if (cursor != null) { while (cursor.moveToNext()) { String val = ""; String data = cursor.getString(0); String display_name = cursor.getString(1); String album_name = cursor.getString(2); long date = cursor.getLong(3); String title = cursor.getString(4); int photoW = cursor.getInt(5); int photoH = cursor.getInt(6); if (data != null && data.toLowerCase().contains("screenshot") || display_name != null && display_name.toLowerCase().contains("screenshot") || album_name != null && album_name.toLowerCase().contains("screenshot") || title != null && title.toLowerCase().contains("screenshot")) { try { if (photoW == 0 || photoH == 0) { BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(data, bmOptions); photoW = bmOptions.outWidth; photoH = bmOptions.outHeight; } if (photoW <= 0 || photoH <= 0 || (photoW == size.x && photoH == size.y || photoH == size.x && photoW == size.y)) { screenshotDates.add(date); } } catch (Exception e) { screenshotDates.add(date); } } } cursor.close(); } if (!screenshotDates.isEmpty()) { AndroidUtilities.runOnUIThread(() -> { NotificationCenter.getInstance(lastChatAccount).postNotificationName(NotificationCenter.screenshotTook); checkScreenshots(screenshotDates); }); } } catch (Exception e) { FileLog.e(e); } finally { try { if (cursor != null) { cursor.close(); } } catch (Exception ignore) { } } } private void checkScreenshots(ArrayList<Long> dates) { if (dates == null || dates.isEmpty() || lastChatEnterTime == 0 || (lastUser == null && !(lastSecretChat instanceof TLRPC.TL_encryptedChat))) { return; } long dt = 2000; boolean send = false; for (int a = 0; a < dates.size(); a++) { Long date = dates.get(a); if (lastMediaCheckTime != 0 && date <= lastMediaCheckTime) { continue; } if (date >= lastChatEnterTime) { if (lastChatLeaveTime == 0 || date <= lastChatLeaveTime + dt) { lastMediaCheckTime = Math.max(lastMediaCheckTime, date); send = true; } } } if (send) { if (lastSecretChat != null) { SecretChatHelper.getInstance(lastChatAccount).sendScreenshotMessage(lastSecretChat, lastChatVisibleMessages, null); } else { SendMessagesHelper.getInstance(lastChatAccount).sendScreenshotMessage(lastUser, lastMessageId, null); } } } public void setLastVisibleMessageIds(int account, long enterTime, long leaveTime, TLRPC.User user, TLRPC.EncryptedChat encryptedChat, ArrayList<Long> visibleMessages, int visibleMessage) { lastChatEnterTime = enterTime; lastChatLeaveTime = leaveTime; lastChatAccount = account; lastSecretChat = encryptedChat; lastUser = user; lastMessageId = visibleMessage; lastChatVisibleMessages = visibleMessages; } @SuppressWarnings("unchecked") @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.fileLoaded || id == NotificationCenter.httpFileDidLoad) { String fileName = (String) args[0]; if (playingMessageObject != null && playingMessageObject.currentAccount == account) { String file = FileLoader.getAttachFileName(playingMessageObject.getDocument()); if (file.equals(fileName)) { if (downloadingCurrentMessage) { playMusicAgain = true; playMessage(playingMessageObject); } else if (audioInfo == null) { try { File cacheFile = FileLoader.getInstance(UserConfig.selectedAccount).getPathToMessage(playingMessageObject.messageOwner); audioInfo = AudioInfo.getAudioInfo(cacheFile); } catch (Exception e) { FileLog.e(e); } } } } } else if (id == NotificationCenter.messagesDeleted) { boolean scheduled = (Boolean) args[2]; if (scheduled) { return; } long channelId = (Long) args[1]; ArrayList<Integer> markAsDeletedMessages = (ArrayList<Integer>) args[0]; if (playingMessageObject != null) { if (channelId == playingMessageObject.messageOwner.peer_id.channel_id) { if (markAsDeletedMessages.contains(playingMessageObject.getId())) { cleanupPlayer(true, true); } } } if (voiceMessagesPlaylist != null && !voiceMessagesPlaylist.isEmpty()) { MessageObject messageObject = voiceMessagesPlaylist.get(0); if (channelId == messageObject.messageOwner.peer_id.channel_id) { for (int a = 0; a < markAsDeletedMessages.size(); a++) { Integer key = markAsDeletedMessages.get(a); messageObject = voiceMessagesPlaylistMap.get(key); voiceMessagesPlaylistMap.remove(key); if (messageObject != null) { voiceMessagesPlaylist.remove(messageObject); } } } } } else if (id == NotificationCenter.removeAllMessagesFromDialog) { long did = (Long) args[0]; if (playingMessageObject != null && playingMessageObject.getDialogId() == did) { cleanupPlayer(false, true); } } else if (id == NotificationCenter.musicDidLoad) { long did = (Long) args[0]; if (playingMessageObject != null && playingMessageObject.isMusic() && playingMessageObject.getDialogId() == did && !playingMessageObject.scheduled) { ArrayList<MessageObject> arrayListBegin = (ArrayList<MessageObject>) args[1]; ArrayList<MessageObject> arrayListEnd = (ArrayList<MessageObject>) args[2]; playlist.addAll(0, arrayListBegin); playlist.addAll(arrayListEnd); for (int a = 0, N = playlist.size(); a < N; a++) { MessageObject object = playlist.get(a); playlistMap.put(object.getId(), object); playlistMaxId[0] = Math.min(playlistMaxId[0], object.getId()); } sortPlaylist(); if (SharedConfig.shuffleMusic) { buildShuffledPlayList(); } else if (playingMessageObject != null) { int newIndex = playlist.indexOf(playingMessageObject); if (newIndex >= 0) { currentPlaylistNum = newIndex; } } playlistClassGuid = ConnectionsManager.generateClassGuid(); } } else if (id == NotificationCenter.mediaDidLoad) { int guid = (Integer) args[3]; if (guid == playlistClassGuid && playingMessageObject != null) { long did = (Long) args[0]; int type = (Integer) args[4]; ArrayList<MessageObject> arr = (ArrayList<MessageObject>) args[2]; boolean enc = DialogObject.isEncryptedDialog(did); int loadIndex = did == playlistMergeDialogId ? 1 : 0; if (!arr.isEmpty()) { playlistEndReached[loadIndex] = (Boolean) args[5]; } int addedCount = 0; for (int a = 0; a < arr.size(); a++) { MessageObject message = arr.get(a); if (message.isVoiceOnce()) continue; if (playlistMap.containsKey(message.getId())) { continue; } addedCount++; playlist.add(0, message); playlistMap.put(message.getId(), message); playlistMaxId[loadIndex] = Math.min(playlistMaxId[loadIndex], message.getId()); } sortPlaylist(); int newIndex = playlist.indexOf(playingMessageObject); if (newIndex >= 0) { currentPlaylistNum = newIndex; } loadingPlaylist = false; if (SharedConfig.shuffleMusic) { buildShuffledPlayList(); } if (addedCount != 0) { NotificationCenter.getInstance(playingMessageObject.currentAccount).postNotificationName(NotificationCenter.moreMusicDidLoad, addedCount); } } } else if (id == NotificationCenter.didReceiveNewMessages) { boolean scheduled = (Boolean) args[2]; if (scheduled) { return; } if (voiceMessagesPlaylist != null && !voiceMessagesPlaylist.isEmpty()) { MessageObject messageObject = voiceMessagesPlaylist.get(0); long did = (Long) args[0]; if (did == messageObject.getDialogId()) { ArrayList<MessageObject> arr = (ArrayList<MessageObject>) args[1]; for (int a = 0; a < arr.size(); a++) { messageObject = arr.get(a); if ((messageObject.isVoice() || messageObject.isRoundVideo()) && !messageObject.isVoiceOnce() && !messageObject.isRoundOnce() && (!voiceMessagesPlaylistUnread || messageObject.isContentUnread() && !messageObject.isOut())) { voiceMessagesPlaylist.add(messageObject); voiceMessagesPlaylistMap.put(messageObject.getId(), messageObject); } } } } } else if (id == NotificationCenter.playerDidStartPlaying) { VideoPlayer p = (VideoPlayer) args[0]; if (!isCurrentPlayer(p)) { MessageObject message = getPlayingMessageObject(); if(message != null && isPlayingMessage(message) && !isMessagePaused() && (message.isMusic() || message.isVoice())){ wasPlayingAudioBeforePause = true; } pauseMessage(message); } } } protected boolean isRecordingAudio() { return recordStartRunnable != null || recordingAudio != null; } private boolean isNearToSensor(float value) { return value < 5.0f && value != proximitySensor.getMaximumRange(); } public boolean isRecordingOrListeningByProximity() { return proximityTouched && (isRecordingAudio() || playingMessageObject != null && (playingMessageObject.isVoice() || playingMessageObject.isRoundVideo())); } private boolean forbidRaiseToListen() { try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { AudioDeviceInfo[] devices = NotificationsController.audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS); for (AudioDeviceInfo device : devices) { final int type = device.getType(); if (( type == AudioDeviceInfo.TYPE_BLUETOOTH_A2DP || type == AudioDeviceInfo.TYPE_BLUETOOTH_SCO || type == AudioDeviceInfo.TYPE_BLE_HEADSET || type == AudioDeviceInfo.TYPE_BLE_SPEAKER || type == AudioDeviceInfo.TYPE_WIRED_HEADPHONES || type == AudioDeviceInfo.TYPE_WIRED_HEADSET ) && device.isSink()) { return true; } } return false; } else { return NotificationsController.audioManager.isWiredHeadsetOn() || NotificationsController.audioManager.isBluetoothA2dpOn() || NotificationsController.audioManager.isBluetoothScoOn(); } } catch (Exception e) { FileLog.e(e); } return false; } @Override public void onSensorChanged(SensorEvent event) { if (!sensorsStarted || VoIPService.getSharedInstance() != null) { return; } if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) { if (BuildVars.LOGS_ENABLED) { FileLog.d("proximity changed to " + event.values[0] + " max value = " + event.sensor.getMaximumRange()); } if (lastProximityValue != event.values[0]) { proximityHasDifferentValues = true; } lastProximityValue = event.values[0]; if (proximityHasDifferentValues) { proximityTouched = isNearToSensor(event.values[0]); } } else if (event.sensor == accelerometerSensor) { final double alpha = lastTimestamp == 0 ? 0.98f : 1.0 / (1.0 + (event.timestamp - lastTimestamp) / 1000000000.0); final float alphaFast = 0.8f; lastTimestamp = event.timestamp; gravity[0] = (float) (alpha * gravity[0] + (1.0 - alpha) * event.values[0]); gravity[1] = (float) (alpha * gravity[1] + (1.0 - alpha) * event.values[1]); gravity[2] = (float) (alpha * gravity[2] + (1.0 - alpha) * event.values[2]); gravityFast[0] = (alphaFast * gravity[0] + (1.0f - alphaFast) * event.values[0]); gravityFast[1] = (alphaFast * gravity[1] + (1.0f - alphaFast) * event.values[1]); gravityFast[2] = (alphaFast * gravity[2] + (1.0f - alphaFast) * event.values[2]); linearAcceleration[0] = event.values[0] - gravity[0]; linearAcceleration[1] = event.values[1] - gravity[1]; linearAcceleration[2] = event.values[2] - gravity[2]; } else if (event.sensor == linearSensor) { linearAcceleration[0] = event.values[0]; linearAcceleration[1] = event.values[1]; linearAcceleration[2] = event.values[2]; } else if (event.sensor == gravitySensor) { gravityFast[0] = gravity[0] = event.values[0]; gravityFast[1] = gravity[1] = event.values[1]; gravityFast[2] = gravity[2] = event.values[2]; } final float minDist = 15.0f; final int minCount = 6; final int countLessMax = 10; if (event.sensor == linearSensor || event.sensor == gravitySensor || event.sensor == accelerometerSensor) { float val = gravity[0] * linearAcceleration[0] + gravity[1] * linearAcceleration[1] + gravity[2] * linearAcceleration[2]; if (raisedToBack != minCount) { if (val > 0 && previousAccValue > 0 || val < 0 && previousAccValue < 0) { boolean goodValue; int sign; if (val > 0) { goodValue = val > minDist; sign = 1; } else { goodValue = val < -minDist; sign = 2; } if (raisedToTopSign != 0 && raisedToTopSign != sign) { if (raisedToTop == minCount && goodValue) { if (raisedToBack < minCount) { raisedToBack++; if (raisedToBack == minCount) { raisedToTop = 0; raisedToTopSign = 0; countLess = 0; timeSinceRaise = System.currentTimeMillis(); if (BuildVars.LOGS_ENABLED && BuildVars.DEBUG_PRIVATE_VERSION) { FileLog.d("motion detected"); } } } } else { if (!goodValue) { countLess++; } if (countLess == countLessMax || raisedToTop != minCount || raisedToBack != 0) { raisedToTop = 0; raisedToTopSign = 0; raisedToBack = 0; countLess = 0; } } } else { if (goodValue && raisedToBack == 0 && (raisedToTopSign == 0 || raisedToTopSign == sign)) { if (raisedToTop < minCount && !proximityTouched) { raisedToTopSign = sign; raisedToTop++; if (raisedToTop == minCount) { countLess = 0; } } } else { if (!goodValue) { countLess++; } if (raisedToTopSign != sign || countLess == countLessMax || raisedToTop != minCount || raisedToBack != 0) { raisedToBack = 0; raisedToTop = 0; raisedToTopSign = 0; countLess = 0; } } } } /*if (val > 0 && previousAccValue > 0) { if (val > minDist && raisedToBack == 0) { if (raisedToTop < minCount && !proximityTouched) { raisedToTop++; if (raisedToTop == minCount) { countLess = 0; } } } else { if (val < minDist) { countLess++; } if (countLess == countLessMax || raisedToTop != minCount || raisedToBack != 0) { raisedToBack = 0; raisedToTop = 0; countLess = 0; } } } else if (val < 0 && previousAccValue < 0) { if (raisedToTop == minCount && val < -minDist) { if (raisedToBack < minCount) { raisedToBack++; if (raisedToBack == minCount) { raisedToTop = 0; countLess = 0; timeSinceRaise = System.currentTimeMillis(); if (BuildVars.LOGS_ENABLED && BuildVars.DEBUG_PRIVATE_VERSION) { FileLog.e("motion detected"); } } } } else { if (val > -minDist) { countLess++; } if (countLess == countLessMax || raisedToTop != minCount || raisedToBack != 0) { raisedToTop = 0; raisedToBack = 0; countLess = 0; } } }*/ /*if (BuildVars.LOGS_ENABLED && BuildVars.DEBUG_PRIVATE_VERSION) { FileLog.e("raise2 to top = " + raisedToTop + " to back = " + raisedToBack + " val = " + val + " countLess = " + countLess); }*/ } previousAccValue = val; accelerometerVertical = gravityFast[1] > 2.5f && Math.abs(gravityFast[2]) < 4.0f && Math.abs(gravityFast[0]) > 1.5f; /*if (BuildVars.LOGS_ENABLED && BuildVars.DEBUG_PRIVATE_VERSION) { FileLog.d(accelerometerVertical + " val = " + val + " acc (" + linearAcceleration[0] + ", " + linearAcceleration[1] + ", " + linearAcceleration[2] + ") grav (" + gravityFast[0] + ", " + gravityFast[1] + ", " + gravityFast[2] + ")"); }*/ } if (raisedToBack == minCount || accelerometerVertical) { lastAccelerometerDetected = System.currentTimeMillis(); } final boolean allowRecording = !manualRecording && playingMessageObject == null && SharedConfig.enabledRaiseTo(true) && ApplicationLoader.isScreenOn && !inputFieldHasText && allowStartRecord && raiseChat != null && !callInProgress; final boolean allowListening = SharedConfig.enabledRaiseTo(false) && playingMessageObject != null && (playingMessageObject.isVoice() || playingMessageObject.isRoundVideo()); final boolean proximityDetected = proximityTouched; final boolean accelerometerDetected = raisedToBack == minCount || accelerometerVertical || System.currentTimeMillis() - lastAccelerometerDetected < 60; final boolean alreadyPlaying = useFrontSpeaker || raiseToEarRecord; final boolean wakelockAllowed = ( // proximityDetected || accelerometerDetected || alreadyPlaying ) && !forbidRaiseToListen() && !VoIPService.isAnyKindOfCallActive() && (allowRecording || allowListening) && !PhotoViewer.getInstance().isVisible(); if (proximityWakeLock != null) { final boolean held = proximityWakeLock.isHeld(); if (held && !wakelockAllowed) { if (BuildVars.LOGS_ENABLED) { FileLog.d("wake lock releasing (proximityDetected=" + proximityDetected + ", accelerometerDetected=" + accelerometerDetected + ", alreadyPlaying=" + alreadyPlaying + ")"); } proximityWakeLock.release(); } else if (!held && wakelockAllowed) { if (BuildVars.LOGS_ENABLED) { FileLog.d("wake lock acquiring (proximityDetected=" + proximityDetected + ", accelerometerDetected=" + accelerometerDetected + ", alreadyPlaying=" + alreadyPlaying + ")"); } proximityWakeLock.acquire(); } } if (proximityTouched && wakelockAllowed) { if (allowRecording && recordStartRunnable == null) { if (!raiseToEarRecord) { if (BuildVars.LOGS_ENABLED) { FileLog.d("start record"); } useFrontSpeaker = true; if (recordingAudio != null || !raiseChat.playFirstUnreadVoiceMessage()) { raiseToEarRecord = true; useFrontSpeaker = false; raiseToSpeakUpdated(true); } if (useFrontSpeaker) { setUseFrontSpeaker(true); } // ignoreOnPause = true; // if (proximityHasDifferentValues && proximityWakeLock != null && !proximityWakeLock.isHeld()) { // proximityWakeLock.acquire(); // } } } else if (allowListening) { if (!useFrontSpeaker) { if (BuildVars.LOGS_ENABLED) { FileLog.d("start listen"); } // if (proximityHasDifferentValues && proximityWakeLock != null && !proximityWakeLock.isHeld()) { // proximityWakeLock.acquire(); // } setUseFrontSpeaker(true); startAudioAgain(false); // ignoreOnPause = true; } } raisedToBack = 0; raisedToTop = 0; raisedToTopSign = 0; countLess = 0; } else if (proximityTouched && ((accelerometerSensor == null || linearSensor == null) && gravitySensor == null) && !VoIPService.isAnyKindOfCallActive()) { if (playingMessageObject != null && !ApplicationLoader.mainInterfacePaused && allowListening) { if (!useFrontSpeaker && !manualRecording && !forbidRaiseToListen()) { if (BuildVars.LOGS_ENABLED) { FileLog.d("start listen by proximity only"); } // if (proximityHasDifferentValues && proximityWakeLock != null && !proximityWakeLock.isHeld()) { // proximityWakeLock.acquire(); // } setUseFrontSpeaker(true); startAudioAgain(false); // ignoreOnPause = true; } } } else if (!proximityTouched && !manualRecording) { if (raiseToEarRecord) { if (BuildVars.LOGS_ENABLED) { FileLog.d("stop record"); } raiseToSpeakUpdated(false); raiseToEarRecord = false; ignoreOnPause = false; // if (!ignoreAccelerometerGestures() && proximityHasDifferentValues && proximityWakeLock != null && proximityWakeLock.isHeld()) { // proximityWakeLock.release(); // } } else if (useFrontSpeaker) { if (BuildVars.LOGS_ENABLED) { FileLog.d("stop listen"); } useFrontSpeaker = false; startAudioAgain(true); ignoreOnPause = false; // if (!ignoreAccelerometerGestures() && proximityHasDifferentValues && proximityWakeLock != null && proximityWakeLock.isHeld()) { // proximityWakeLock.release(); // } } } if (timeSinceRaise != 0 && raisedToBack == minCount && Math.abs(System.currentTimeMillis() - timeSinceRaise) > 1000) { raisedToBack = 0; raisedToTop = 0; raisedToTopSign = 0; countLess = 0; timeSinceRaise = 0; } } private void raiseToSpeakUpdated(boolean raised) { if (recordingAudio != null) { toggleRecordingPause(false); } else if (raised) { startRecording(raiseChat.getCurrentAccount(), raiseChat.getDialogId(), null, raiseChat.getThreadMessage(), null, raiseChat.getClassGuid(), false, raiseChat != null ? raiseChat.quickReplyShortcut : null, raiseChat != null ? raiseChat.getQuickReplyId() : 0); } else { stopRecording(2, false, 0, false); } } private void setUseFrontSpeaker(boolean value) { useFrontSpeaker = value; AudioManager audioManager = NotificationsController.audioManager; if (useFrontSpeaker) { audioManager.setBluetoothScoOn(false); audioManager.setSpeakerphoneOn(false); } else { audioManager.setSpeakerphoneOn(true); } } public void startRecordingIfFromSpeaker() { if (!useFrontSpeaker || raiseChat == null || !allowStartRecord || !SharedConfig.enabledRaiseTo(true)) { return; } raiseToEarRecord = true; startRecording(raiseChat.getCurrentAccount(), raiseChat.getDialogId(), null, raiseChat.getThreadMessage(), null, raiseChat.getClassGuid(), false, raiseChat != null ? raiseChat.quickReplyShortcut : null, raiseChat != null ? raiseChat.getQuickReplyId() : 0); ignoreOnPause = true; } private void startAudioAgain(boolean paused) { if (playingMessageObject == null) { return; } NotificationCenter.getInstance(playingMessageObject.currentAccount).postNotificationName(NotificationCenter.audioRouteChanged, useFrontSpeaker); if (videoPlayer != null) { videoPlayer.setStreamType(useFrontSpeaker ? AudioManager.STREAM_VOICE_CALL : AudioManager.STREAM_MUSIC); if (!paused) { if (videoPlayer.getCurrentPosition() < 1000) { videoPlayer.seekTo(0); } videoPlayer.play(); } else { pauseMessage(playingMessageObject); } } else { boolean post = audioPlayer != null; final MessageObject currentMessageObject = playingMessageObject; float progress = playingMessageObject.audioProgress; int duration = playingMessageObject.audioPlayerDuration; if (paused || audioPlayer == null || !audioPlayer.isPlaying() || duration * progress > 1f) { currentMessageObject.audioProgress = progress; } else { currentMessageObject.audioProgress = 0; } cleanupPlayer(false, true); playMessage(currentMessageObject); if (paused) { if (post) { AndroidUtilities.runOnUIThread(() -> pauseMessage(currentMessageObject), 100); } else { pauseMessage(currentMessageObject); } } } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } public void setInputFieldHasText(boolean value) { inputFieldHasText = value; } public void setAllowStartRecord(boolean value) { allowStartRecord = value; } public void startRaiseToEarSensors(ChatActivity chatActivity) { if (chatActivity == null || accelerometerSensor == null && (gravitySensor == null || linearAcceleration == null) || proximitySensor == null) { return; } if (!SharedConfig.enabledRaiseTo(false) && (playingMessageObject == null || !playingMessageObject.isVoice() && !playingMessageObject.isRoundVideo())) { return; } raiseChat = chatActivity; if (!sensorsStarted) { gravity[0] = gravity[1] = gravity[2] = 0; linearAcceleration[0] = linearAcceleration[1] = linearAcceleration[2] = 0; gravityFast[0] = gravityFast[1] = gravityFast[2] = 0; lastTimestamp = 0; previousAccValue = 0; raisedToTop = 0; raisedToTopSign = 0; countLess = 0; raisedToBack = 0; Utilities.globalQueue.postRunnable(() -> { if (gravitySensor != null) { sensorManager.registerListener(MediaController.this, gravitySensor, 30000); } if (linearSensor != null) { sensorManager.registerListener(MediaController.this, linearSensor, 30000); } if (accelerometerSensor != null) { sensorManager.registerListener(MediaController.this, accelerometerSensor, 30000); } sensorManager.registerListener(MediaController.this, proximitySensor, SensorManager.SENSOR_DELAY_NORMAL); }); sensorsStarted = true; } } public void stopRaiseToEarSensors(ChatActivity chatActivity, boolean fromChat, boolean stopRecording) { if (ignoreOnPause) { ignoreOnPause = false; return; } if (stopRecording) { stopRecording(fromChat ? 2 : 0, false, 0, false); } if (!sensorsStarted || ignoreOnPause || accelerometerSensor == null && (gravitySensor == null || linearAcceleration == null) || proximitySensor == null || raiseChat != chatActivity) { return; } raiseChat = null; sensorsStarted = false; accelerometerVertical = false; proximityTouched = false; raiseToEarRecord = false; useFrontSpeaker = false; Utilities.globalQueue.postRunnable(() -> { if (linearSensor != null) { sensorManager.unregisterListener(MediaController.this, linearSensor); } if (gravitySensor != null) { sensorManager.unregisterListener(MediaController.this, gravitySensor); } if (accelerometerSensor != null) { sensorManager.unregisterListener(MediaController.this, accelerometerSensor); } sensorManager.unregisterListener(MediaController.this, proximitySensor); }); if (proximityWakeLock != null && proximityWakeLock.isHeld()) { proximityWakeLock.release(); } } public void cleanupPlayer(boolean notify, boolean stopService) { cleanupPlayer(notify, stopService, false, false); } public void cleanupPlayer(boolean notify, boolean stopService, boolean byVoiceEnd, boolean transferPlayerToPhotoViewer) { if (audioPlayer != null) { if (audioVolumeAnimator != null) { audioVolumeAnimator.removeAllUpdateListeners(); audioVolumeAnimator.cancel(); } if (audioPlayer.isPlaying() && playingMessageObject != null && !playingMessageObject.isVoice()) { VideoPlayer playerFinal = audioPlayer; ValueAnimator valueAnimator = ValueAnimator.ofFloat(audioVolume, 0); valueAnimator.addUpdateListener(valueAnimator1 -> { float volume; if (audioFocus != AUDIO_NO_FOCUS_CAN_DUCK) { volume = VOLUME_NORMAL; } else { volume = VOLUME_DUCK; } playerFinal.setVolume(volume * (float) valueAnimator1.getAnimatedValue()); }); valueAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { try { playerFinal.releasePlayer(true); } catch (Exception e) { FileLog.e(e); } } }); valueAnimator.setDuration(300); valueAnimator.start(); } else { try { audioPlayer.releasePlayer(true); } catch (Exception e) { FileLog.e(e); } } audioPlayer = null; Theme.unrefAudioVisualizeDrawable(playingMessageObject); } else if (videoPlayer != null) { currentAspectRatioFrameLayout = null; currentTextureViewContainer = null; currentAspectRatioFrameLayoutReady = false; isDrawingWasReady = false; currentTextureView = null; goingToShowMessageObject = null; if (transferPlayerToPhotoViewer) { PhotoViewer.getInstance().injectVideoPlayer(videoPlayer); goingToShowMessageObject = playingMessageObject; NotificationCenter.getInstance(playingMessageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingGoingToStop, playingMessageObject, true); } else { long position = videoPlayer.getCurrentPosition(); if (playingMessageObject != null && playingMessageObject.isVideo() && position > 0) { playingMessageObject.audioProgressMs = (int) position; NotificationCenter.getInstance(playingMessageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingGoingToStop, playingMessageObject, false); } videoPlayer.releasePlayer(true); videoPlayer = null; } try { baseActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } catch (Exception e) { FileLog.e(e); } if (playingMessageObject != null && !transferPlayerToPhotoViewer) { AndroidUtilities.cancelRunOnUIThread(setLoadingRunnable); FileLoader.getInstance(playingMessageObject.currentAccount).removeLoadingVideo(playingMessageObject.getDocument(), true, false); } } stopProgressTimer(); lastProgress = 0; isPaused = false; boolean playingNext = false; if (playingMessageObject != null) { if (downloadingCurrentMessage) { FileLoader.getInstance(playingMessageObject.currentAccount).cancelLoadFile(playingMessageObject.getDocument()); } MessageObject lastFile = playingMessageObject; if (notify) { playingMessageObject.resetPlayingProgress(); NotificationCenter.getInstance(lastFile.currentAccount).postNotificationName(NotificationCenter.messagePlayingProgressDidChanged, playingMessageObject.getId(), 0); } playingMessageObject = null; downloadingCurrentMessage = false; if (notify) { NotificationsController.audioManager.abandonAudioFocus(this); hasAudioFocus = 0; int index = -1; if (voiceMessagesPlaylist != null) { if (byVoiceEnd && (index = voiceMessagesPlaylist.indexOf(lastFile)) >= 0) { voiceMessagesPlaylist.remove(index); voiceMessagesPlaylistMap.remove(lastFile.getId()); if (voiceMessagesPlaylist.isEmpty()) { voiceMessagesPlaylist = null; voiceMessagesPlaylistMap = null; } } else { voiceMessagesPlaylist = null; voiceMessagesPlaylistMap = null; } } if (voiceMessagesPlaylist != null && index < voiceMessagesPlaylist.size()) { MessageObject nextVoiceMessage = voiceMessagesPlaylist.get(index); playMessage(nextVoiceMessage); playingNext = true; if (!nextVoiceMessage.isRoundVideo() && pipRoundVideoView != null) { pipRoundVideoView.close(true); pipRoundVideoView = null; } } else { if ((lastFile.isVoice() || lastFile.isRoundVideo()) && lastFile.getId() != 0) { startRecordingIfFromSpeaker(); } NotificationCenter.getInstance(lastFile.currentAccount).postNotificationName(NotificationCenter.messagePlayingDidReset, lastFile.getId(), stopService); pipSwitchingState = 0; if (pipRoundVideoView != null) { pipRoundVideoView.close(true); pipRoundVideoView = null; } } } if (stopService) { Intent intent = new Intent(ApplicationLoader.applicationContext, MusicPlayerService.class); ApplicationLoader.applicationContext.stopService(intent); } } if (!playingNext && byVoiceEnd && !SharedConfig.enabledRaiseTo(true)) { ChatActivity chat = raiseChat; stopRaiseToEarSensors(raiseChat, false, false); raiseChat = chat; } } public boolean isGoingToShowMessageObject(MessageObject messageObject) { return goingToShowMessageObject == messageObject; } public void resetGoingToShowMessageObject() { goingToShowMessageObject = null; } private boolean isSamePlayingMessage(MessageObject messageObject) { return playingMessageObject != null && playingMessageObject.getDialogId() == messageObject.getDialogId() && playingMessageObject.getId() == messageObject.getId() && ((playingMessageObject.eventId == 0) == (messageObject.eventId == 0)); } public boolean seekToProgress(MessageObject messageObject, float progress) { final MessageObject playingMessageObject = this.playingMessageObject; if (audioPlayer == null && videoPlayer == null || messageObject == null || playingMessageObject == null || !isSamePlayingMessage(messageObject)) { return false; } try { if (audioPlayer != null) { long duration = audioPlayer.getDuration(); if (duration == C.TIME_UNSET) { seekToProgressPending = progress; } else { playingMessageObject.audioProgress = progress; int seekTo = (int) (duration * progress); audioPlayer.seekTo(seekTo); lastProgress = seekTo; } } else if (videoPlayer != null) { videoPlayer.seekTo((long) (videoPlayer.getDuration() * progress)); } } catch (Exception e) { FileLog.e(e); return false; } NotificationCenter.getInstance(messageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingDidSeek, playingMessageObject.getId(), progress); return true; } public long getDuration() { if (audioPlayer == null) { return 0; } return audioPlayer.getDuration(); } public MessageObject getPlayingMessageObject() { return playingMessageObject; } public int getPlayingMessageObjectNum() { return currentPlaylistNum; } private void buildShuffledPlayList() { if (playlist.isEmpty()) { return; } ArrayList<MessageObject> all = new ArrayList<>(playlist); shuffledPlaylist.clear(); MessageObject messageObject = playlist.get(currentPlaylistNum); all.remove(currentPlaylistNum); int count = all.size(); for (int a = 0; a < count; a++) { int index = Utilities.random.nextInt(all.size()); shuffledPlaylist.add(all.get(index)); all.remove(index); } shuffledPlaylist.add(messageObject); currentPlaylistNum = shuffledPlaylist.size() - 1; } public void loadMoreMusic() { if (loadingPlaylist || playingMessageObject == null || playingMessageObject.scheduled || DialogObject.isEncryptedDialog(playingMessageObject.getDialogId()) || playlistClassGuid == 0) { return; } if (playlistGlobalSearchParams != null) { int finalPlaylistGuid = playlistClassGuid; if (!playlistGlobalSearchParams.endReached && !playlist.isEmpty()) { int currentAccount = playlist.get(0).currentAccount; TLObject request; if (playlistGlobalSearchParams.dialogId != 0) { final TLRPC.TL_messages_search req = new TLRPC.TL_messages_search(); req.q = playlistGlobalSearchParams.query; req.limit = 20; req.filter = playlistGlobalSearchParams.filter == null ? new TLRPC.TL_inputMessagesFilterEmpty() : playlistGlobalSearchParams.filter.filter; req.peer = AccountInstance.getInstance(currentAccount).getMessagesController().getInputPeer(playlistGlobalSearchParams.dialogId); MessageObject lastMessage = playlist.get(playlist.size() - 1); req.offset_id = lastMessage.getId(); if (playlistGlobalSearchParams.minDate > 0) { req.min_date = (int) (playlistGlobalSearchParams.minDate / 1000); } if (playlistGlobalSearchParams.maxDate > 0) { req.min_date = (int) (playlistGlobalSearchParams.maxDate / 1000); } request = req; } else { final TLRPC.TL_messages_searchGlobal req = new TLRPC.TL_messages_searchGlobal(); req.limit = 20; req.q = playlistGlobalSearchParams.query; req.filter = playlistGlobalSearchParams.filter.filter; MessageObject lastMessage = playlist.get(playlist.size() - 1); req.offset_id = lastMessage.getId(); req.offset_rate = playlistGlobalSearchParams.nextSearchRate; req.flags |= 1; req.folder_id = playlistGlobalSearchParams.folderId; long id; if (lastMessage.messageOwner.peer_id.channel_id != 0) { id = -lastMessage.messageOwner.peer_id.channel_id; } else if (lastMessage.messageOwner.peer_id.chat_id != 0) { id = -lastMessage.messageOwner.peer_id.chat_id; } else { id = lastMessage.messageOwner.peer_id.user_id; } req.offset_peer = MessagesController.getInstance(currentAccount).getInputPeer(id); if (playlistGlobalSearchParams.minDate > 0) { req.min_date = (int) (playlistGlobalSearchParams.minDate / 1000); } if (playlistGlobalSearchParams.maxDate > 0) { req.min_date = (int) (playlistGlobalSearchParams.maxDate / 1000); } request = req; } loadingPlaylist = true; ConnectionsManager.getInstance(currentAccount).sendRequest(request, (response, error) -> AndroidUtilities.runOnUIThread(() -> { if (playlistClassGuid != finalPlaylistGuid || playlistGlobalSearchParams == null || playingMessageObject == null) { return; } if (error != null) { return; } loadingPlaylist = false; TLRPC.messages_Messages res = (TLRPC.messages_Messages) response; playlistGlobalSearchParams.nextSearchRate = res.next_rate; MessagesStorage.getInstance(currentAccount).putUsersAndChats(res.users, res.chats, true, true); MessagesController.getInstance(currentAccount).putUsers(res.users, false); MessagesController.getInstance(currentAccount).putChats(res.chats, false); int n = res.messages.size(); int addedCount = 0; for (int i = 0; i < n; i++) { MessageObject messageObject = new MessageObject(currentAccount, res.messages.get(i), false, true); if (messageObject.isVoiceOnce()) continue; if (playlistMap.containsKey(messageObject.getId())) { continue; } playlist.add(0, messageObject); playlistMap.put(messageObject.getId(), messageObject); addedCount++; } sortPlaylist(); loadingPlaylist = false; playlistGlobalSearchParams.endReached = playlist.size() == playlistGlobalSearchParams.totalCount; if (SharedConfig.shuffleMusic) { buildShuffledPlayList(); } if (addedCount != 0) { NotificationCenter.getInstance(playingMessageObject.currentAccount).postNotificationName(NotificationCenter.moreMusicDidLoad, addedCount); } })); } return; } //TODO topics if (!playlistEndReached[0]) { loadingPlaylist = true; AccountInstance.getInstance(playingMessageObject.currentAccount).getMediaDataController().loadMedia(playingMessageObject.getDialogId(), 50, playlistMaxId[0], 0, MediaDataController.MEDIA_MUSIC, 0, 1, playlistClassGuid, 0, null, null); } else if (playlistMergeDialogId != 0 && !playlistEndReached[1]) { loadingPlaylist = true; AccountInstance.getInstance(playingMessageObject.currentAccount).getMediaDataController().loadMedia(playlistMergeDialogId, 50, playlistMaxId[0], 0, MediaDataController.MEDIA_MUSIC, 0, 1, playlistClassGuid, 0, null, null); } } public boolean setPlaylist(ArrayList<MessageObject> messageObjects, MessageObject current, long mergeDialogId, PlaylistGlobalSearchParams globalSearchParams) { return setPlaylist(messageObjects, current, mergeDialogId, true, globalSearchParams); } public boolean setPlaylist(ArrayList<MessageObject> messageObjects, MessageObject current, long mergeDialogId) { return setPlaylist(messageObjects, current, mergeDialogId, true, null); } public boolean setPlaylist(ArrayList<MessageObject> messageObjects, MessageObject current, long mergeDialogId, boolean loadMusic, PlaylistGlobalSearchParams params) { if (playingMessageObject == current) { int newIdx = playlist.indexOf(current); if (newIdx >= 0) { currentPlaylistNum = newIdx; } return playMessage(current); } forceLoopCurrentPlaylist = !loadMusic; playlistMergeDialogId = mergeDialogId; playMusicAgain = !playlist.isEmpty(); clearPlaylist(); playlistGlobalSearchParams = params; boolean isSecretChat = !messageObjects.isEmpty() && DialogObject.isEncryptedDialog(messageObjects.get(0).getDialogId()); int minId = Integer.MAX_VALUE; int maxId = Integer.MIN_VALUE; for (int a = messageObjects.size() - 1; a >= 0; a--) { MessageObject messageObject = messageObjects.get(a); if (messageObject.isMusic()) { int id = messageObject.getId(); if (id > 0 || isSecretChat) { minId = Math.min(minId, id); maxId = Math.max(maxId, id); } playlist.add(messageObject); playlistMap.put(id, messageObject); } } sortPlaylist(); currentPlaylistNum = playlist.indexOf(current); if (currentPlaylistNum == -1) { clearPlaylist(); currentPlaylistNum = playlist.size(); playlist.add(current); playlistMap.put(current.getId(), current); } if (current.isMusic() && !current.scheduled) { if (SharedConfig.shuffleMusic) { buildShuffledPlayList(); } if (loadMusic) { if (playlistGlobalSearchParams == null) { MediaDataController.getInstance(current.currentAccount).loadMusic(current.getDialogId(), minId, maxId); } else { playlistClassGuid = ConnectionsManager.generateClassGuid(); } } } return playMessage(current); } private void sortPlaylist() { Collections.sort(playlist, (o1, o2) -> { int mid1 = o1.getId(); int mid2 = o2.getId(); long group1 = o1.messageOwner.grouped_id; long group2 = o2.messageOwner.grouped_id; if (mid1 < 0 && mid2 < 0) { if (group1 != 0 && group1 == group2) { return -Integer.compare(mid1, mid2); } return Integer.compare(mid2, mid1); } else { if (group1 != 0 && group1 == group2) { return -Integer.compare(mid2, mid1); } return Integer.compare(mid1, mid2); } }); } public boolean hasNoNextVoiceOrRoundVideoMessage() { return playingMessageObject == null || (!playingMessageObject.isVoice() && !playingMessageObject.isRoundVideo()) || voiceMessagesPlaylist == null || voiceMessagesPlaylist.size() <= 1 || !voiceMessagesPlaylist.contains(playingMessageObject) || voiceMessagesPlaylist.indexOf(playingMessageObject) >= (voiceMessagesPlaylist.size() - 1); } public void playNextMessage() { playNextMessageWithoutOrder(false); } public boolean findMessageInPlaylistAndPlay(MessageObject messageObject) { int index = playlist.indexOf(messageObject); if (index == -1) { return playMessage(messageObject); } else { playMessageAtIndex(index); } return true; } public void playMessageAtIndex(int index) { if (currentPlaylistNum < 0 || currentPlaylistNum >= playlist.size()) { return; } currentPlaylistNum = index; playMusicAgain = true; MessageObject messageObject = playlist.get(currentPlaylistNum); if (playingMessageObject != null && !isSamePlayingMessage(messageObject)) { playingMessageObject.resetPlayingProgress(); } playMessage(messageObject); } private void playNextMessageWithoutOrder(boolean byStop) { ArrayList<MessageObject> currentPlayList = SharedConfig.shuffleMusic ? shuffledPlaylist : playlist; if (byStop && (SharedConfig.repeatMode == 2 || SharedConfig.repeatMode == 1 && currentPlayList.size() == 1) && !forceLoopCurrentPlaylist) { cleanupPlayer(false, false); MessageObject messageObject = currentPlayList.get(currentPlaylistNum); messageObject.audioProgress = 0; messageObject.audioProgressSec = 0; playMessage(messageObject); return; } boolean last = traversePlaylist(currentPlayList, SharedConfig.playOrderReversed ? +1 : -1); if (last && byStop && SharedConfig.repeatMode == 0 && !forceLoopCurrentPlaylist) { if (audioPlayer != null || videoPlayer != null) { if (audioPlayer != null) { try { audioPlayer.releasePlayer(true); } catch (Exception e) { FileLog.e(e); } audioPlayer = null; Theme.unrefAudioVisualizeDrawable(playingMessageObject); } else { currentAspectRatioFrameLayout = null; currentTextureViewContainer = null; currentAspectRatioFrameLayoutReady = false; currentTextureView = null; videoPlayer.releasePlayer(true); videoPlayer = null; try { baseActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } catch (Exception e) { FileLog.e(e); } AndroidUtilities.cancelRunOnUIThread(setLoadingRunnable); FileLoader.getInstance(playingMessageObject.currentAccount).removeLoadingVideo(playingMessageObject.getDocument(), true, false); } stopProgressTimer(); lastProgress = 0; isPaused = true; playingMessageObject.audioProgress = 0.0f; playingMessageObject.audioProgressSec = 0; NotificationCenter.getInstance(playingMessageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingProgressDidChanged, playingMessageObject.getId(), 0); NotificationCenter.getInstance(playingMessageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingPlayStateChanged, playingMessageObject.getId()); } return; } if (currentPlaylistNum < 0 || currentPlaylistNum >= currentPlayList.size()) { return; } if (playingMessageObject != null) { playingMessageObject.resetPlayingProgress(); } playMusicAgain = true; playMessage(currentPlayList.get(currentPlaylistNum)); } public void playPreviousMessage() { ArrayList<MessageObject> currentPlayList = SharedConfig.shuffleMusic ? shuffledPlaylist : playlist; if (currentPlayList.isEmpty() || currentPlaylistNum < 0 || currentPlaylistNum >= currentPlayList.size()) { return; } MessageObject currentSong = currentPlayList.get(currentPlaylistNum); if (currentSong.audioProgressSec > 10) { seekToProgress(currentSong, 0); return; } traversePlaylist(currentPlayList, SharedConfig.playOrderReversed ? -1 : 1); if (currentPlaylistNum >= currentPlayList.size()) { return; } playMusicAgain = true; playMessage(currentPlayList.get(currentPlaylistNum)); } private boolean traversePlaylist(ArrayList<MessageObject> playlist, int direction) { boolean last = false; final int wasCurrentPlaylistNum = currentPlaylistNum; int connectionState = ConnectionsManager.getInstance(UserConfig.selectedAccount).getConnectionState(); boolean offline = connectionState == ConnectionsManager.ConnectionStateWaitingForNetwork; currentPlaylistNum += direction; if (offline) { while (currentPlaylistNum < playlist.size() && currentPlaylistNum >= 0) { MessageObject audio = playlist.get(currentPlaylistNum); if (audio != null && audio.mediaExists) { break; } currentPlaylistNum += direction; } } if (currentPlaylistNum >= playlist.size() || currentPlaylistNum < 0) { currentPlaylistNum = currentPlaylistNum >= playlist.size() ? 0 : playlist.size() - 1; if (offline) { while (currentPlaylistNum >= 0 && currentPlaylistNum < playlist.size() && (direction > 0 ? currentPlaylistNum <= wasCurrentPlaylistNum : currentPlaylistNum >= wasCurrentPlaylistNum)) { MessageObject audio = playlist.get(currentPlaylistNum); if (audio != null && audio.mediaExists) { break; } currentPlaylistNum += direction; } if (currentPlaylistNum >= playlist.size() || currentPlaylistNum < 0) { currentPlaylistNum = currentPlaylistNum >= playlist.size() ? 0 : playlist.size() - 1; } } last = true; } return last; } protected void checkIsNextMediaFileDownloaded() { if (playingMessageObject == null || !playingMessageObject.isMusic()) { return; } checkIsNextMusicFileDownloaded(playingMessageObject.currentAccount); } private void checkIsNextVoiceFileDownloaded(int currentAccount) { if (voiceMessagesPlaylist == null || voiceMessagesPlaylist.size() < 2) { return; } MessageObject nextAudio = voiceMessagesPlaylist.get(1); File file = null; if (nextAudio.messageOwner.attachPath != null && nextAudio.messageOwner.attachPath.length() > 0) { file = new File(nextAudio.messageOwner.attachPath); if (!file.exists()) { file = null; } } final File cacheFile = file != null ? file : FileLoader.getInstance(currentAccount).getPathToMessage(nextAudio.messageOwner); boolean exist = cacheFile.exists(); if (cacheFile != file && !cacheFile.exists()) { FileLoader.getInstance(currentAccount).loadFile(nextAudio.getDocument(), nextAudio, FileLoader.PRIORITY_LOW, nextAudio.shouldEncryptPhotoOrVideo() ? 2 : 0); } } private void checkIsNextMusicFileDownloaded(int currentAccount) { if (!DownloadController.getInstance(currentAccount).canDownloadNextTrack()) { return; } ArrayList<MessageObject> currentPlayList = SharedConfig.shuffleMusic ? shuffledPlaylist : playlist; if (currentPlayList == null || currentPlayList.size() < 2) { return; } int nextIndex; if (SharedConfig.playOrderReversed) { nextIndex = currentPlaylistNum + 1; if (nextIndex >= currentPlayList.size()) { nextIndex = 0; } } else { nextIndex = currentPlaylistNum - 1; if (nextIndex < 0) { nextIndex = currentPlayList.size() - 1; } } if (nextIndex < 0 || nextIndex >= currentPlayList.size()) { return; } MessageObject nextAudio = currentPlayList.get(nextIndex); File file = null; if (!TextUtils.isEmpty(nextAudio.messageOwner.attachPath)) { file = new File(nextAudio.messageOwner.attachPath); if (!file.exists()) { file = null; } } final File cacheFile = file != null ? file : FileLoader.getInstance(currentAccount).getPathToMessage(nextAudio.messageOwner); boolean exist = cacheFile.exists(); if (cacheFile != file && !cacheFile.exists() && nextAudio.isMusic()) { FileLoader.getInstance(currentAccount).loadFile(nextAudio.getDocument(), nextAudio, FileLoader.PRIORITY_LOW, nextAudio.shouldEncryptPhotoOrVideo() ? 2 : 0); } } public void setVoiceMessagesPlaylist(ArrayList<MessageObject> playlist, boolean unread) { voiceMessagesPlaylist = playlist != null ? new ArrayList<>(playlist) : null; if (voiceMessagesPlaylist != null) { voiceMessagesPlaylistUnread = unread; voiceMessagesPlaylistMap = new SparseArray<>(); for (int a = 0; a < voiceMessagesPlaylist.size(); a++) { MessageObject messageObject = voiceMessagesPlaylist.get(a); voiceMessagesPlaylistMap.put(messageObject.getId(), messageObject); } } } private void checkAudioFocus(MessageObject messageObject) { int neededAudioFocus; if (messageObject.isVoice() || messageObject.isRoundVideo()) { if (useFrontSpeaker) { neededAudioFocus = 3; } else { neededAudioFocus = 2; } } else { neededAudioFocus = 1; } if (hasAudioFocus != neededAudioFocus) { hasAudioFocus = neededAudioFocus; int result; if (neededAudioFocus == 3) { result = NotificationsController.audioManager.requestAudioFocus(this, AudioManager.STREAM_VOICE_CALL, AudioManager.AUDIOFOCUS_GAIN); } else { result = NotificationsController.audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, neededAudioFocus == 2 && !SharedConfig.pauseMusicOnMedia ? AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK : AudioManager.AUDIOFOCUS_GAIN); } if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { audioFocus = AUDIO_FOCUSED; } } } public boolean isPiPShown() { return pipRoundVideoView != null; } public void setCurrentVideoVisible(boolean visible) { if (currentAspectRatioFrameLayout == null) { return; } if (visible) { if (pipRoundVideoView != null) { pipSwitchingState = 2; pipRoundVideoView.close(true); pipRoundVideoView = null; } else { if (currentAspectRatioFrameLayout.getParent() == null) { currentTextureViewContainer.addView(currentAspectRatioFrameLayout); } videoPlayer.setTextureView(currentTextureView); } } else { if (currentAspectRatioFrameLayout.getParent() != null) { pipSwitchingState = 1; currentTextureViewContainer.removeView(currentAspectRatioFrameLayout); } else { if (pipRoundVideoView == null) { try { pipRoundVideoView = new PipRoundVideoView(); pipRoundVideoView.show(baseActivity, () -> cleanupPlayer(true, true)); } catch (Exception e) { pipRoundVideoView = null; } } if (pipRoundVideoView != null) { videoPlayer.setTextureView(pipRoundVideoView.getTextureView()); } } } } public void setTextureView(TextureView textureView, AspectRatioFrameLayout aspectRatioFrameLayout, FrameLayout container, boolean set) { setTextureView(textureView, aspectRatioFrameLayout, container, set, null); } public void setTextureView(TextureView textureView, AspectRatioFrameLayout aspectRatioFrameLayout, FrameLayout container, boolean set, Runnable afterPip) { if (textureView == null) { return; } if (!set && currentTextureView == textureView) { pipSwitchingState = 1; currentTextureView = null; currentAspectRatioFrameLayout = null; currentTextureViewContainer = null; return; } if (videoPlayer == null || textureView == currentTextureView) { return; } isDrawingWasReady = aspectRatioFrameLayout != null && aspectRatioFrameLayout.isDrawingReady(); currentTextureView = textureView; if (afterPip != null && pipRoundVideoView == null) { try { pipRoundVideoView = new PipRoundVideoView(); pipRoundVideoView.show(baseActivity, () -> cleanupPlayer(true, true)); } catch (Exception e) { pipRoundVideoView = null; } } if (pipRoundVideoView != null) { videoPlayer.setTextureView(pipRoundVideoView.getTextureView()); } else { videoPlayer.setTextureView(currentTextureView); } currentAspectRatioFrameLayout = aspectRatioFrameLayout; currentTextureViewContainer = container; if (currentAspectRatioFrameLayoutReady && currentAspectRatioFrameLayout != null) { currentAspectRatioFrameLayout.setAspectRatio(currentAspectRatioFrameLayoutRatio, currentAspectRatioFrameLayoutRotation); //if (currentTextureViewContainer.getVisibility() != View.VISIBLE) { // currentTextureViewContainer.setVisibility(View.VISIBLE); //} } } public void setBaseActivity(Activity activity, boolean set) { if (set) { baseActivity = activity; } else if (baseActivity == activity) { baseActivity = null; } } public void setFeedbackView(View view, boolean set) { if (set) { feedbackView = view; } else if (feedbackView == view) { feedbackView = null; } } public void setPlaybackSpeed(boolean music, float speed) { if (music) { if (currentMusicPlaybackSpeed >= 6 && speed == 1f && playingMessageObject != null) { audioPlayer.pause(); float p = playingMessageObject.audioProgress; final MessageObject currentMessage = playingMessageObject; AndroidUtilities.runOnUIThread(() -> { if (audioPlayer != null && playingMessageObject != null && !isPaused) { if (isSamePlayingMessage(currentMessage)) { seekToProgress(playingMessageObject, p); } audioPlayer.play(); } }, 50); } currentMusicPlaybackSpeed = speed; if (Math.abs(speed - 1.0f) > 0.001f) { fastMusicPlaybackSpeed = speed; } } else { currentPlaybackSpeed = speed; if (Math.abs(speed - 1.0f) > 0.001f) { fastPlaybackSpeed = speed; } } if (audioPlayer != null) { audioPlayer.setPlaybackSpeed(Math.round(speed * 10f) / 10f); } else if (videoPlayer != null) { videoPlayer.setPlaybackSpeed(Math.round(speed * 10f) / 10f); } MessagesController.getGlobalMainSettings().edit() .putFloat(music ? "musicPlaybackSpeed" : "playbackSpeed", speed) .putFloat(music ? "fastMusicPlaybackSpeed" : "fastPlaybackSpeed", music ? fastMusicPlaybackSpeed : fastPlaybackSpeed) .commit(); NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.messagePlayingSpeedChanged); } public float getPlaybackSpeed(boolean music) { return music ? currentMusicPlaybackSpeed : currentPlaybackSpeed; } public float getFastPlaybackSpeed(boolean music) { return music ? fastMusicPlaybackSpeed : fastPlaybackSpeed; } private void updateVideoState(MessageObject messageObject, int[] playCount, boolean destroyAtEnd, boolean playWhenReady, int playbackState) { if (videoPlayer == null) { return; } if (playbackState != ExoPlayer.STATE_ENDED && playbackState != ExoPlayer.STATE_IDLE) { try { baseActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } catch (Exception e) { FileLog.e(e); } } else { try { baseActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } catch (Exception e) { FileLog.e(e); } } if (playbackState == ExoPlayer.STATE_READY) { playerWasReady = true; if (playingMessageObject != null && (playingMessageObject.isVideo() || playingMessageObject.isRoundVideo())) { AndroidUtilities.cancelRunOnUIThread(setLoadingRunnable); FileLoader.getInstance(messageObject.currentAccount).removeLoadingVideo(playingMessageObject.getDocument(), true, false); } currentAspectRatioFrameLayoutReady = true; } else if (playbackState == ExoPlayer.STATE_BUFFERING) { if (playWhenReady && playingMessageObject != null && (playingMessageObject.isVideo() || playingMessageObject.isRoundVideo())) { if (playerWasReady) { setLoadingRunnable.run(); } else { AndroidUtilities.runOnUIThread(setLoadingRunnable, 1000); } } } else if (videoPlayer.isPlaying() && playbackState == ExoPlayer.STATE_ENDED) { if (playingMessageObject.isVideo() && !destroyAtEnd && (playCount == null || playCount[0] < 4)) { videoPlayer.seekTo(0); if (playCount != null) { playCount[0]++; } } else { cleanupPlayer(true, hasNoNextVoiceOrRoundVideoMessage(), true, false); } } } public void injectVideoPlayer(VideoPlayer player, MessageObject messageObject) { if (player == null || messageObject == null) { return; } FileLoader.getInstance(messageObject.currentAccount).setLoadingVideoForPlayer(messageObject.getDocument(), true); playerWasReady = false; boolean destroyAtEnd = true; int[] playCount = null; clearPlaylist(); videoPlayer = player; playingMessageObject = messageObject; int tag = ++playerNum; videoPlayer.setDelegate(new VideoPlayer.VideoPlayerDelegate() { @Override public void onStateChanged(boolean playWhenReady, int playbackState) { if (tag != playerNum) { return; } updateVideoState(messageObject, playCount, destroyAtEnd, playWhenReady, playbackState); } @Override public void onError(VideoPlayer player, Exception e) { FileLog.e(e); } @Override public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) { currentAspectRatioFrameLayoutRotation = unappliedRotationDegrees; if (unappliedRotationDegrees == 90 || unappliedRotationDegrees == 270) { int temp = width; width = height; height = temp; } currentAspectRatioFrameLayoutRatio = height == 0 ? 1 : (width * pixelWidthHeightRatio) / height; if (currentAspectRatioFrameLayout != null) { currentAspectRatioFrameLayout.setAspectRatio(currentAspectRatioFrameLayoutRatio, currentAspectRatioFrameLayoutRotation); } } @Override public void onRenderedFirstFrame() { if (currentAspectRatioFrameLayout != null && !currentAspectRatioFrameLayout.isDrawingReady()) { isDrawingWasReady = true; currentAspectRatioFrameLayout.setDrawingReady(true); currentTextureViewContainer.setTag(1); } } @Override public boolean onSurfaceDestroyed(SurfaceTexture surfaceTexture) { if (videoPlayer == null) { return false; } if (pipSwitchingState == 2) { if (currentAspectRatioFrameLayout != null) { if (isDrawingWasReady) { currentAspectRatioFrameLayout.setDrawingReady(true); } if (currentAspectRatioFrameLayout.getParent() == null) { currentTextureViewContainer.addView(currentAspectRatioFrameLayout); } if (currentTextureView.getSurfaceTexture() != surfaceTexture) { currentTextureView.setSurfaceTexture(surfaceTexture); } videoPlayer.setTextureView(currentTextureView); } pipSwitchingState = 0; return true; } else if (pipSwitchingState == 1) { if (baseActivity != null) { if (pipRoundVideoView == null) { try { pipRoundVideoView = new PipRoundVideoView(); pipRoundVideoView.show(baseActivity, () -> cleanupPlayer(true, true)); } catch (Exception e) { pipRoundVideoView = null; } } if (pipRoundVideoView != null) { if (pipRoundVideoView.getTextureView().getSurfaceTexture() != surfaceTexture) { pipRoundVideoView.getTextureView().setSurfaceTexture(surfaceTexture); } videoPlayer.setTextureView(pipRoundVideoView.getTextureView()); } } pipSwitchingState = 0; return true; } else if (PhotoViewer.hasInstance() && PhotoViewer.getInstance().isInjectingVideoPlayer()) { PhotoViewer.getInstance().injectVideoPlayerSurface(surfaceTexture); return true; } return false; } @Override public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) { } }); currentAspectRatioFrameLayoutReady = false; if (currentTextureView != null) { videoPlayer.setTextureView(currentTextureView); } checkAudioFocus(messageObject); setPlayerVolume(); isPaused = false; lastProgress = 0; MessageObject oldMessageObject = playingMessageObject; playingMessageObject = messageObject; if (!SharedConfig.enabledRaiseTo(true)) { startRaiseToEarSensors(raiseChat); } startProgressTimer(playingMessageObject); NotificationCenter.getInstance(messageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingDidStart, messageObject, oldMessageObject); /*try { if (playingMessageObject.audioProgress != 0) { long duration = videoPlayer.getDuration(); if (duration == C.TIME_UNSET) { duration = (long) playingMessageObject.getDuration() * 1000; } int seekTo = (int) (duration * playingMessageObject.audioProgress); if (playingMessageObject.audioProgressMs != 0) { seekTo = playingMessageObject.audioProgressMs; playingMessageObject.audioProgressMs = 0; } videoPlayer.seekTo(seekTo); } } catch (Exception e2) { playingMessageObject.audioProgress = 0; playingMessageObject.audioProgressSec = 0; NotificationCenter.getInstance(messageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingProgressDidChanged, playingMessageObject.getId(), 0); FileLog.e(e2); }*/ } public void playEmojiSound(AccountInstance accountInstance, String emoji, MessagesController.EmojiSound sound, boolean loadOnly) { if (sound == null) { return; } Utilities.stageQueue.postRunnable(() -> { TLRPC.Document document = new TLRPC.TL_document(); document.access_hash = sound.accessHash; document.id = sound.id; document.mime_type = "sound/ogg"; document.file_reference = sound.fileReference; document.dc_id = accountInstance.getConnectionsManager().getCurrentDatacenterId(); File file = FileLoader.getInstance(accountInstance.getCurrentAccount()).getPathToAttach(document, true); if (file.exists()) { if (loadOnly) { return; } AndroidUtilities.runOnUIThread(() -> { try { int tag = ++emojiSoundPlayerNum; if (emojiSoundPlayer != null) { emojiSoundPlayer.releasePlayer(true); } emojiSoundPlayer = new VideoPlayer(false, false); emojiSoundPlayer.setDelegate(new VideoPlayer.VideoPlayerDelegate() { @Override public void onStateChanged(boolean playWhenReady, int playbackState) { AndroidUtilities.runOnUIThread(() -> { if (tag != emojiSoundPlayerNum) { return; } if (playbackState == ExoPlayer.STATE_ENDED) { if (emojiSoundPlayer != null) { try { emojiSoundPlayer.releasePlayer(true); emojiSoundPlayer = null; } catch (Exception e) { FileLog.e(e); } } } }); } @Override public void onError(VideoPlayer player, Exception e) { } @Override public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) { } @Override public void onRenderedFirstFrame() { } @Override public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) { } @Override public boolean onSurfaceDestroyed(SurfaceTexture surfaceTexture) { return false; } }); emojiSoundPlayer.preparePlayer(Uri.fromFile(file), "other"); emojiSoundPlayer.setStreamType(AudioManager.STREAM_MUSIC); emojiSoundPlayer.play(); } catch (Exception e) { FileLog.e(e); if (emojiSoundPlayer != null) { emojiSoundPlayer.releasePlayer(true); emojiSoundPlayer = null; } } }); } else { AndroidUtilities.runOnUIThread(() -> accountInstance.getFileLoader().loadFile(document, null, FileLoader.PRIORITY_NORMAL, 1)); } }); } private static long volumeBarLastTimeShown; public void checkVolumeBarUI() { if (isSilent) { return; } try { final long now = System.currentTimeMillis(); if (Math.abs(now - volumeBarLastTimeShown) < 5000) { return; } AudioManager audioManager = (AudioManager) ApplicationLoader.applicationContext.getSystemService(Context.AUDIO_SERVICE); int stream = useFrontSpeaker ? AudioManager.STREAM_VOICE_CALL : AudioManager.STREAM_MUSIC; int volume = audioManager.getStreamVolume(stream); if (volume == 0) { audioManager.adjustStreamVolume(stream, volume, AudioManager.FLAG_SHOW_UI); volumeBarLastTimeShown = now; } } catch (Exception ignore) {} } private void setBluetoothScoOn(boolean scoOn) { AudioManager am = (AudioManager) ApplicationLoader.applicationContext.getSystemService(Context.AUDIO_SERVICE); if (am.isBluetoothScoAvailableOffCall() && SharedConfig.recordViaSco || !scoOn) { BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); try { if (btAdapter != null && btAdapter.getProfileConnectionState(BluetoothProfile.HEADSET) == BluetoothProfile.STATE_CONNECTED || !scoOn) { if (scoOn && !am.isBluetoothScoOn()) { am.startBluetoothSco(); } else if (!scoOn && am.isBluetoothScoOn()) { am.stopBluetoothSco(); } } } catch (SecurityException ignored) { } catch (Throwable e) { FileLog.e(e); } } } public boolean playMessage(final MessageObject messageObject) { return playMessage(messageObject, false); } public boolean playMessage(final MessageObject messageObject, boolean silent) { if (messageObject == null) { return false; } isSilent = silent; checkVolumeBarUI(); if ((audioPlayer != null || videoPlayer != null) && isSamePlayingMessage(messageObject)) { if (isPaused) { resumeAudio(messageObject); } if (!SharedConfig.enabledRaiseTo(true)) { startRaiseToEarSensors(raiseChat); } return true; } if (!messageObject.isOut() && (messageObject.isContentUnread())) { MessagesController.getInstance(messageObject.currentAccount).markMessageContentAsRead(messageObject); } boolean notify = !playMusicAgain; MessageObject oldMessageObject = playingMessageObject; if (playingMessageObject != null) { notify = false; if (!playMusicAgain) { playingMessageObject.resetPlayingProgress(); NotificationCenter.getInstance(playingMessageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingProgressDidChanged, playingMessageObject.getId(), 0); } } cleanupPlayer(notify, false); shouldSavePositionForCurrentAudio = null; lastSaveTime = 0; playMusicAgain = false; seekToProgressPending = 0; File file = null; boolean exists = false; if (messageObject.messageOwner.attachPath != null && messageObject.messageOwner.attachPath.length() > 0) { file = new File(messageObject.messageOwner.attachPath); exists = file.exists(); if (!exists) { file = null; } } final File cacheFile = file != null ? file : FileLoader.getInstance(messageObject.currentAccount).getPathToMessage(messageObject.messageOwner); boolean canStream = SharedConfig.streamMedia && (messageObject.isMusic() || messageObject.isRoundVideo() || messageObject.isVideo() && messageObject.canStreamVideo()) && !messageObject.shouldEncryptPhotoOrVideo() && !DialogObject.isEncryptedDialog(messageObject.getDialogId()); if (cacheFile != file && !(exists = cacheFile.exists()) && !canStream) { FileLoader.getInstance(messageObject.currentAccount).loadFile(messageObject.getDocument(), messageObject, FileLoader.PRIORITY_LOW, messageObject.shouldEncryptPhotoOrVideo() ? 2 : 0); downloadingCurrentMessage = true; isPaused = false; lastProgress = 0; audioInfo = null; playingMessageObject = messageObject; if (canStartMusicPlayerService()) { Intent intent = new Intent(ApplicationLoader.applicationContext, MusicPlayerService.class); try { /*if (Build.VERSION.SDK_INT >= 26) { ApplicationLoader.applicationContext.startForegroundService(intent); } else {*/ ApplicationLoader.applicationContext.startService(intent); //} } catch (Throwable e) { FileLog.e(e); } } else { Intent intent = new Intent(ApplicationLoader.applicationContext, MusicPlayerService.class); ApplicationLoader.applicationContext.stopService(intent); } NotificationCenter.getInstance(playingMessageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingPlayStateChanged, playingMessageObject.getId()); return true; } else { downloadingCurrentMessage = false; } if (messageObject.isMusic()) { checkIsNextMusicFileDownloaded(messageObject.currentAccount); } else { checkIsNextVoiceFileDownloaded(messageObject.currentAccount); } if (currentAspectRatioFrameLayout != null) { isDrawingWasReady = false; currentAspectRatioFrameLayout.setDrawingReady(false); } boolean isVideo = messageObject.isVideo(); if (messageObject.isRoundVideo() || isVideo) { FileLoader.getInstance(messageObject.currentAccount).setLoadingVideoForPlayer(messageObject.getDocument(), true); playerWasReady = false; boolean destroyAtEnd = !isVideo || messageObject.messageOwner.peer_id.channel_id == 0 && messageObject.audioProgress <= 0.1f; int[] playCount = isVideo && messageObject.getDuration() <= 30 ? new int[]{1} : null; clearPlaylist(); videoPlayer = new VideoPlayer(); videoPlayer.setLooping(silent); int tag = ++playerNum; videoPlayer.setDelegate(new VideoPlayer.VideoPlayerDelegate() { @Override public void onStateChanged(boolean playWhenReady, int playbackState) { if (tag != playerNum) { return; } updateVideoState(messageObject, playCount, destroyAtEnd, playWhenReady, playbackState); } @Override public void onError(VideoPlayer player, Exception e) { FileLog.e(e); } @Override public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) { currentAspectRatioFrameLayoutRotation = unappliedRotationDegrees; if (unappliedRotationDegrees == 90 || unappliedRotationDegrees == 270) { int temp = width; width = height; height = temp; } currentAspectRatioFrameLayoutRatio = height == 0 ? 1 : (width * pixelWidthHeightRatio) / height; if (currentAspectRatioFrameLayout != null) { currentAspectRatioFrameLayout.setAspectRatio(currentAspectRatioFrameLayoutRatio, currentAspectRatioFrameLayoutRotation); } } @Override public void onRenderedFirstFrame() { if (currentAspectRatioFrameLayout != null && !currentAspectRatioFrameLayout.isDrawingReady()) { isDrawingWasReady = true; currentAspectRatioFrameLayout.setDrawingReady(true); currentTextureViewContainer.setTag(1); //if (currentTextureViewContainer != null && currentTextureViewContainer.getVisibility() != View.VISIBLE) { // currentTextureViewContainer.setVisibility(View.VISIBLE); //} } } @Override public boolean onSurfaceDestroyed(SurfaceTexture surfaceTexture) { if (videoPlayer == null) { return false; } if (pipSwitchingState == 2) { if (currentAspectRatioFrameLayout != null) { if (isDrawingWasReady) { currentAspectRatioFrameLayout.setDrawingReady(true); } if (currentAspectRatioFrameLayout.getParent() == null) { currentTextureViewContainer.addView(currentAspectRatioFrameLayout); } if (currentTextureView.getSurfaceTexture() != surfaceTexture) { currentTextureView.setSurfaceTexture(surfaceTexture); } videoPlayer.setTextureView(currentTextureView); } pipSwitchingState = 0; return true; } else if (pipSwitchingState == 1) { if (baseActivity != null) { if (pipRoundVideoView == null) { try { pipRoundVideoView = new PipRoundVideoView(); pipRoundVideoView.show(baseActivity, () -> cleanupPlayer(true, true)); } catch (Exception e) { pipRoundVideoView = null; } } if (pipRoundVideoView != null) { if (pipRoundVideoView.getTextureView().getSurfaceTexture() != surfaceTexture) { pipRoundVideoView.getTextureView().setSurfaceTexture(surfaceTexture); } videoPlayer.setTextureView(pipRoundVideoView.getTextureView()); } } pipSwitchingState = 0; return true; } else if (PhotoViewer.hasInstance() && PhotoViewer.getInstance().isInjectingVideoPlayer()) { PhotoViewer.getInstance().injectVideoPlayerSurface(surfaceTexture); return true; } return false; } @Override public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) { } }); currentAspectRatioFrameLayoutReady = false; if (pipRoundVideoView != null || !MessagesController.getInstance(messageObject.currentAccount).isDialogVisible(messageObject.getDialogId(), messageObject.scheduled)) { if (pipRoundVideoView == null) { try { pipRoundVideoView = new PipRoundVideoView(); pipRoundVideoView.show(baseActivity, () -> cleanupPlayer(true, true)); } catch (Exception e) { pipRoundVideoView = null; } } if (pipRoundVideoView != null) { videoPlayer.setTextureView(pipRoundVideoView.getTextureView()); } } else if (currentTextureView != null) { videoPlayer.setTextureView(currentTextureView); } if (exists) { if (!messageObject.mediaExists && cacheFile != file) { AndroidUtilities.runOnUIThread(() -> NotificationCenter.getInstance(messageObject.currentAccount).postNotificationName(NotificationCenter.fileLoaded, FileLoader.getAttachFileName(messageObject.getDocument()), cacheFile)); } videoPlayer.preparePlayer(Uri.fromFile(cacheFile), "other"); } else { try { int reference = FileLoader.getInstance(messageObject.currentAccount).getFileReference(messageObject); TLRPC.Document document = messageObject.getDocument(); String params = "?account=" + messageObject.currentAccount + "&id=" + document.id + "&hash=" + document.access_hash + "&dc=" + document.dc_id + "&size=" + document.size + "&mime=" + URLEncoder.encode(document.mime_type, "UTF-8") + "&rid=" + reference + "&name=" + URLEncoder.encode(FileLoader.getDocumentFileName(document), "UTF-8") + "&reference=" + Utilities.bytesToHex(document.file_reference != null ? document.file_reference : new byte[0]); Uri uri = Uri.parse("tg://" + messageObject.getFileName() + params); videoPlayer.preparePlayer(uri, "other"); } catch (Exception e) { FileLog.e(e); } } if (messageObject.isRoundVideo()) { videoPlayer.setStreamType(useFrontSpeaker ? AudioManager.STREAM_VOICE_CALL : AudioManager.STREAM_MUSIC); if (Math.abs(currentPlaybackSpeed - 1.0f) > 0.001f) { videoPlayer.setPlaybackSpeed(Math.round(currentPlaybackSpeed * 10f) / 10f); } if (messageObject.forceSeekTo >= 0) { messageObject.audioProgress = seekToProgressPending = messageObject.forceSeekTo; messageObject.forceSeekTo = -1; } } else { videoPlayer.setStreamType(AudioManager.STREAM_MUSIC); } } else { if (pipRoundVideoView != null) { pipRoundVideoView.close(true); pipRoundVideoView = null; } try { audioPlayer = new VideoPlayer(); int tag = ++playerNum; audioPlayer.setDelegate(new VideoPlayer.VideoPlayerDelegate() { @Override public void onStateChanged(boolean playWhenReady, int playbackState) { if (tag != playerNum) { return; } if (playbackState == ExoPlayer.STATE_ENDED || (playbackState == ExoPlayer.STATE_IDLE || playbackState == ExoPlayer.STATE_BUFFERING) && playWhenReady && messageObject.audioProgress >= 0.999f) { messageObject.audioProgress = 1f; NotificationCenter.getInstance(messageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingProgressDidChanged, messageObject.getId(), 0); if (!playlist.isEmpty() && (playlist.size() > 1 || !messageObject.isVoice())) { playNextMessageWithoutOrder(true); } else { cleanupPlayer(true, hasNoNextVoiceOrRoundVideoMessage(), messageObject.isVoice(), false); } } else if (audioPlayer != null && seekToProgressPending != 0 && (playbackState == ExoPlayer.STATE_READY || playbackState == ExoPlayer.STATE_IDLE)) { int seekTo = (int) (audioPlayer.getDuration() * seekToProgressPending); audioPlayer.seekTo(seekTo); lastProgress = seekTo; seekToProgressPending = 0; } } @Override public void onError(VideoPlayer player, Exception e) { } @Override public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) { } @Override public void onRenderedFirstFrame() { } @Override public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) { } @Override public boolean onSurfaceDestroyed(SurfaceTexture surfaceTexture) { return false; } }); audioPlayer.setAudioVisualizerDelegate(new VideoPlayer.AudioVisualizerDelegate() { @Override public void onVisualizerUpdate(boolean playing, boolean animate, float[] values) { Theme.getCurrentAudiVisualizerDrawable().setWaveform(playing, animate, values); } @Override public boolean needUpdate() { return Theme.getCurrentAudiVisualizerDrawable().getParentView() != null; } }); if (exists) { if (!messageObject.mediaExists && cacheFile != file) { AndroidUtilities.runOnUIThread(() -> NotificationCenter.getInstance(messageObject.currentAccount).postNotificationName(NotificationCenter.fileLoaded, FileLoader.getAttachFileName(messageObject.getDocument()), cacheFile)); } audioPlayer.preparePlayer(Uri.fromFile(cacheFile), "other"); isStreamingCurrentAudio = false; } else { int reference = FileLoader.getInstance(messageObject.currentAccount).getFileReference(messageObject); TLRPC.Document document = messageObject.getDocument(); String params = "?account=" + messageObject.currentAccount + "&id=" + document.id + "&hash=" + document.access_hash + "&dc=" + document.dc_id + "&size=" + document.size + "&mime=" + URLEncoder.encode(document.mime_type, "UTF-8") + "&rid=" + reference + "&name=" + URLEncoder.encode(FileLoader.getDocumentFileName(document), "UTF-8") + "&reference=" + Utilities.bytesToHex(document.file_reference != null ? document.file_reference : new byte[0]); Uri uri = Uri.parse("tg://" + messageObject.getFileName() + params); audioPlayer.preparePlayer(uri, "other"); isStreamingCurrentAudio = true; } if (messageObject.isVoice()) { String name = messageObject.getFileName(); if (name != null && messageObject.getDuration() >= 5 * 60) { SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("media_saved_pos", Activity.MODE_PRIVATE); float pos = preferences.getFloat(name, -1); if (pos > 0 && pos < 0.99f) { messageObject.audioProgress = seekToProgressPending = pos; } shouldSavePositionForCurrentAudio = name; } if (Math.abs(currentPlaybackSpeed - 1.0f) > 0.001f) { audioPlayer.setPlaybackSpeed(Math.round(currentPlaybackSpeed * 10f) / 10f); } audioInfo = null; clearPlaylist(); } else { try { audioInfo = AudioInfo.getAudioInfo(cacheFile); } catch (Exception e) { FileLog.e(e); } String name = messageObject.getFileName(); if (!TextUtils.isEmpty(name) && messageObject.getDuration() >= 10 * 60) { SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("media_saved_pos", Activity.MODE_PRIVATE); float pos = preferences.getFloat(name, -1); if (pos > 0 && pos < 0.999f) { messageObject.audioProgress = seekToProgressPending = pos; } shouldSavePositionForCurrentAudio = name; if (Math.abs(currentMusicPlaybackSpeed - 1.0f) > 0.001f) { audioPlayer.setPlaybackSpeed(Math.round(currentMusicPlaybackSpeed * 10f) / 10f); } } } if (messageObject.forceSeekTo >= 0) { messageObject.audioProgress = seekToProgressPending = messageObject.forceSeekTo; messageObject.forceSeekTo = -1; } audioPlayer.setStreamType(useFrontSpeaker ? AudioManager.STREAM_VOICE_CALL : AudioManager.STREAM_MUSIC); audioPlayer.play(); if (!messageObject.isVoice()) { if (audioVolumeAnimator != null) { audioVolumeAnimator.removeAllListeners(); audioVolumeAnimator.cancel(); } audioVolumeAnimator = ValueAnimator.ofFloat(audioVolume, 1f); audioVolumeAnimator.addUpdateListener(audioVolumeUpdateListener); audioVolumeAnimator.setDuration(300); audioVolumeAnimator.start(); } else { audioVolume = 1f; setPlayerVolume(); } } catch (Exception e) { FileLog.e(e); NotificationCenter.getInstance(messageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingPlayStateChanged, playingMessageObject != null ? playingMessageObject.getId() : 0); if (audioPlayer != null) { audioPlayer.releasePlayer(true); audioPlayer = null; Theme.unrefAudioVisualizeDrawable(playingMessageObject); isPaused = false; playingMessageObject = null; downloadingCurrentMessage = false; } return false; } } checkAudioFocus(messageObject); setPlayerVolume(); isPaused = false; lastProgress = 0; playingMessageObject = messageObject; if (!SharedConfig.enabledRaiseTo(true)) { startRaiseToEarSensors(raiseChat); } if (!ApplicationLoader.mainInterfacePaused && proximityWakeLock != null && !proximityWakeLock.isHeld() && (playingMessageObject.isVoice() || playingMessageObject.isRoundVideo()) && SharedConfig.enabledRaiseTo(false)) { // proximityWakeLock.acquire(); } startProgressTimer(playingMessageObject); NotificationCenter.getInstance(messageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingDidStart, messageObject, oldMessageObject); if (videoPlayer != null) { try { if (playingMessageObject.audioProgress != 0) { long duration = videoPlayer.getDuration(); if (duration == C.TIME_UNSET) { duration = (long) playingMessageObject.getDuration() * 1000; } int seekTo = (int) (duration * playingMessageObject.audioProgress); if (playingMessageObject.audioProgressMs != 0) { seekTo = playingMessageObject.audioProgressMs; playingMessageObject.audioProgressMs = 0; } videoPlayer.seekTo(seekTo); } } catch (Exception e2) { playingMessageObject.audioProgress = 0; playingMessageObject.audioProgressSec = 0; NotificationCenter.getInstance(messageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingProgressDidChanged, playingMessageObject.getId(), 0); FileLog.e(e2); } videoPlayer.play(); } else if (audioPlayer != null) { try { if (playingMessageObject.audioProgress != 0) { long duration = audioPlayer.getDuration(); if (duration == C.TIME_UNSET) { duration = (long) playingMessageObject.getDuration() * 1000; } int seekTo = (int) (duration * playingMessageObject.audioProgress); audioPlayer.seekTo(seekTo); } } catch (Exception e2) { playingMessageObject.resetPlayingProgress(); NotificationCenter.getInstance(messageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingProgressDidChanged, playingMessageObject.getId(), 0); FileLog.e(e2); } } if (canStartMusicPlayerService()) { Intent intent = new Intent(ApplicationLoader.applicationContext, MusicPlayerService.class); try { /*if (Build.VERSION.SDK_INT >= 26) { ApplicationLoader.applicationContext.startForegroundService(intent); } else {*/ ApplicationLoader.applicationContext.startService(intent); //} } catch (Throwable e) { FileLog.e(e); } } else { Intent intent = new Intent(ApplicationLoader.applicationContext, MusicPlayerService.class); ApplicationLoader.applicationContext.stopService(intent); } return true; } private boolean canStartMusicPlayerService() { return playingMessageObject != null && (playingMessageObject.isMusic() || playingMessageObject.isVoice() || playingMessageObject.isRoundVideo()) && !playingMessageObject.isVoiceOnce() && !playingMessageObject.isRoundOnce(); } public void updateSilent(boolean value) { isSilent = value; if (videoPlayer != null) { videoPlayer.setLooping(value); } setPlayerVolume(); checkVolumeBarUI(); if (playingMessageObject != null) { NotificationCenter.getInstance(playingMessageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingPlayStateChanged, playingMessageObject != null ? playingMessageObject.getId() : 0); } } public AudioInfo getAudioInfo() { return audioInfo; } public void setPlaybackOrderType(int type) { boolean oldShuffle = SharedConfig.shuffleMusic; SharedConfig.setPlaybackOrderType(type); if (oldShuffle != SharedConfig.shuffleMusic) { if (SharedConfig.shuffleMusic) { buildShuffledPlayList(); } else { if (playingMessageObject != null) { currentPlaylistNum = playlist.indexOf(playingMessageObject); if (currentPlaylistNum == -1) { clearPlaylist(); cleanupPlayer(true, true); } } } } } public boolean isStreamingCurrentAudio() { return isStreamingCurrentAudio; } public boolean isCurrentPlayer(VideoPlayer player) { return videoPlayer == player || audioPlayer == player; } public void tryResumePausedAudio() { MessageObject message = getPlayingMessageObject(); if (message!= null && isMessagePaused() && wasPlayingAudioBeforePause && (message.isVoice() || message.isMusic())) { playMessage(message); } wasPlayingAudioBeforePause = false; } public boolean pauseMessage(MessageObject messageObject) { if (audioPlayer == null && videoPlayer == null || messageObject == null || playingMessageObject == null || !isSamePlayingMessage(messageObject)) { return false; } stopProgressTimer(); try { if (audioPlayer != null) { if (!playingMessageObject.isVoice() && (playingMessageObject.getDuration() * (1f - playingMessageObject.audioProgress) > 1) && LaunchActivity.isResumed) { if (audioVolumeAnimator != null) { audioVolumeAnimator.removeAllUpdateListeners(); audioVolumeAnimator.cancel(); } audioVolumeAnimator = ValueAnimator.ofFloat(1f, 0); audioVolumeAnimator.addUpdateListener(audioVolumeUpdateListener); audioVolumeAnimator.setDuration(300); audioVolumeAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (audioPlayer != null) { audioPlayer.pause(); } } }); audioVolumeAnimator.start(); } else { audioPlayer.pause(); } } else if (videoPlayer != null) { videoPlayer.pause(); } isPaused = true; NotificationCenter.getInstance(playingMessageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingPlayStateChanged, playingMessageObject.getId()); } catch (Exception e) { FileLog.e(e); isPaused = false; return false; } return true; } private boolean resumeAudio(MessageObject messageObject) { if (audioPlayer == null && videoPlayer == null || messageObject == null || playingMessageObject == null || !isSamePlayingMessage(messageObject)) { return false; } try { startProgressTimer(playingMessageObject); if (audioVolumeAnimator != null) { audioVolumeAnimator.removeAllListeners(); audioVolumeAnimator.cancel(); } if (!messageObject.isVoice() && !messageObject.isRoundVideo()) { audioVolumeAnimator = ValueAnimator.ofFloat(audioVolume, 1f); audioVolumeAnimator.addUpdateListener(audioVolumeUpdateListener); audioVolumeAnimator.setDuration(300); audioVolumeAnimator.start(); } else { audioVolume = 1f; setPlayerVolume(); } if (audioPlayer != null) { audioPlayer.play(); } else if (videoPlayer != null) { videoPlayer.play(); } checkAudioFocus(messageObject); isPaused = false; NotificationCenter.getInstance(playingMessageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingPlayStateChanged, playingMessageObject.getId()); } catch (Exception e) { FileLog.e(e); return false; } return true; } public boolean isVideoDrawingReady() { return currentAspectRatioFrameLayout != null && currentAspectRatioFrameLayout.isDrawingReady(); } public ArrayList<MessageObject> getPlaylist() { return playlist; } public boolean isPlayingMessage(MessageObject messageObject) { if (messageObject != null && messageObject.isRepostPreview) { return false; } if (audioPlayer == null && videoPlayer == null || messageObject == null || playingMessageObject == null) { return false; } if (playingMessageObject.eventId != 0 && playingMessageObject.eventId == messageObject.eventId) { return !downloadingCurrentMessage; } if (isSamePlayingMessage(messageObject)) { return !downloadingCurrentMessage; } // return false; } public boolean isPlayingMessageAndReadyToDraw(MessageObject messageObject) { return isDrawingWasReady && isPlayingMessage(messageObject); } public boolean isMessagePaused() { return isPaused || downloadingCurrentMessage; } public boolean isDownloadingCurrentMessage() { return downloadingCurrentMessage; } public void setReplyingMessage(MessageObject replyToMsg, MessageObject replyToTopMsg, TL_stories.StoryItem storyItem) { recordReplyingMsg = replyToMsg; recordReplyingTopMsg = replyToTopMsg; recordReplyingStory = storyItem; } public void requestAudioFocus(boolean request) { if (request) { if (!hasRecordAudioFocus && SharedConfig.pauseMusicOnRecord) { int result = NotificationsController.audioManager.requestAudioFocus(audioRecordFocusChangedListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { hasRecordAudioFocus = true; } } } else { if (hasRecordAudioFocus) { NotificationsController.audioManager.abandonAudioFocus(audioRecordFocusChangedListener); hasRecordAudioFocus = false; } } } public void prepareResumedRecording(int currentAccount, MediaDataController.DraftVoice draft, long dialogId, MessageObject replyToMsg, MessageObject replyToTopMsg, TL_stories.StoryItem replyStory, int guid, String query_shortcut, int query_shortcut_id) { manualRecording = false; requestAudioFocus(true); recordQueue.cancelRunnable(recordStartRunnable); recordQueue.postRunnable(() -> { setBluetoothScoOn(true); sendAfterDone = 0; recordingAudio = new TLRPC.TL_document(); recordingGuid = guid; recordingAudio.dc_id = Integer.MIN_VALUE; recordingAudio.id = draft.id; recordingAudio.user_id = UserConfig.getInstance(currentAccount).getClientUserId(); recordingAudio.mime_type = "audio/ogg"; recordingAudio.file_reference = new byte[0]; SharedConfig.saveConfig(); recordingAudioFile = new File(draft.path) { @Override public boolean delete() { if (BuildVars.LOGS_ENABLED) { FileLog.e("delete voice file"); } return super.delete(); } }; FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE).mkdirs(); if (BuildVars.LOGS_ENABLED) { FileLog.d("start recording internal " + recordingAudioFile.getPath() + " " + recordingAudioFile.exists()); } AutoDeleteMediaTask.lockFile(recordingAudioFile); try { audioRecorderPaused = true; recordTimeCount = draft.recordTimeCount; writedFrame = draft.writedFrame; samplesCount = draft.samplesCount; recordSamples = draft.recordSamples; recordDialogId = dialogId; recordTopicId = replyToTopMsg == null ? 0 : MessageObject.getTopicId(recordingCurrentAccount, replyToTopMsg.messageOwner, false); recordingCurrentAccount = currentAccount; recordReplyingMsg = replyToMsg; recordReplyingTopMsg = replyToTopMsg; recordReplyingStory = replyStory; recordQuickReplyShortcut = query_shortcut; recordQuickReplyShortcutId = query_shortcut_id; } catch (Exception e) { FileLog.e(e); recordingAudio = null; AutoDeleteMediaTask.unlockFile(recordingAudioFile); recordingAudioFile.delete(); recordingAudioFile = null; try { audioRecorder.release(); audioRecorder = null; } catch (Exception e2) { FileLog.e(e2); } setBluetoothScoOn(false); AndroidUtilities.runOnUIThread(() -> { MediaDataController.getInstance(currentAccount).pushDraftVoiceMessage(dialogId, recordTopicId, null); recordStartRunnable = null; }); return; } final TLRPC.TL_document audioToSend = recordingAudio; final File recordingAudioFileToSend = recordingAudioFile; AndroidUtilities.runOnUIThread(() -> { boolean fileExist = recordingAudioFileToSend.exists(); if (!fileExist && BuildVars.DEBUG_VERSION) { FileLog.e(new RuntimeException("file not found :( recordTimeCount " + recordTimeCount + " writedFrames" + writedFrame)); } audioToSend.date = ConnectionsManager.getInstance(recordingCurrentAccount).getCurrentTime(); audioToSend.size = (int) recordingAudioFileToSend.length(); TLRPC.TL_documentAttributeAudio attributeAudio = new TLRPC.TL_documentAttributeAudio(); attributeAudio.voice = true; attributeAudio.waveform = getWaveform2(recordSamples, recordSamples.length); if (attributeAudio.waveform != null) { attributeAudio.flags |= 4; } attributeAudio.duration = recordTimeCount / 1000.0; audioToSend.attributes.clear(); audioToSend.attributes.add(attributeAudio); NotificationCenter.getInstance(recordingCurrentAccount).postNotificationName(NotificationCenter.recordPaused); NotificationCenter.getInstance(recordingCurrentAccount).postNotificationName(NotificationCenter.audioDidSent, recordingGuid, audioToSend, recordingAudioFileToSend.getAbsolutePath(), true); }); }); } public void toggleRecordingPause(boolean voiceOnce) { recordQueue.postRunnable(() -> { if (recordingAudio == null || recordingAudioFile == null) { return; } audioRecorderPaused = !audioRecorderPaused; final boolean isPaused = audioRecorderPaused; if (isPaused) { if (audioRecorder == null) { return; } sendAfterDone = 4; audioRecorder.stop(); audioRecorder.release(); audioRecorder = null; recordQueue.postRunnable(() -> { stopRecord(true); final TLRPC.TL_document audioToSend = recordingAudio; final File recordingAudioFileToSend = recordingAudioFile; if (recordingAudio == null || recordingAudioFile == null) { return; } AndroidUtilities.runOnUIThread(() -> { boolean fileExist = recordingAudioFileToSend.exists(); if (!fileExist && BuildVars.DEBUG_VERSION) { FileLog.e(new RuntimeException("file not found :( recordTimeCount " + recordTimeCount + " writedFrames" + writedFrame)); } if (fileExist) { MediaDataController.getInstance(recordingCurrentAccount).pushDraftVoiceMessage(recordDialogId, recordTopicId, MediaDataController.DraftVoice.of(this, recordingAudioFileToSend.getAbsolutePath(), voiceOnce)); } audioToSend.date = ConnectionsManager.getInstance(recordingCurrentAccount).getCurrentTime(); audioToSend.size = (int) recordingAudioFileToSend.length(); TLRPC.TL_documentAttributeAudio attributeAudio = new TLRPC.TL_documentAttributeAudio(); attributeAudio.voice = true; attributeAudio.waveform = getWaveform2(recordSamples, recordSamples.length); if (attributeAudio.waveform != null) { attributeAudio.flags |= 4; } attributeAudio.duration = recordTimeCount / 1000.0; audioToSend.attributes.clear(); audioToSend.attributes.add(attributeAudio); NotificationCenter.getInstance(recordingCurrentAccount).postNotificationName(NotificationCenter.recordPaused); NotificationCenter.getInstance(recordingCurrentAccount).postNotificationName(NotificationCenter.audioDidSent, recordingGuid, audioToSend, recordingAudioFileToSend.getAbsolutePath()); }); }); } else { recordQueue.cancelRunnable(recordRunnable); recordQueue.postRunnable(() -> { if (resumeRecord(recordingAudioFile.getPath(), sampleRate) == 0) { AndroidUtilities.runOnUIThread(() -> { recordStartRunnable = null; NotificationCenter.getInstance(recordingCurrentAccount).postNotificationName(NotificationCenter.recordStartError, recordingGuid); }); if (BuildVars.LOGS_ENABLED) { FileLog.d("cant resume encoder"); } return; } AndroidUtilities.runOnUIThread(() -> { MediaDataController.getInstance(recordingCurrentAccount).pushDraftVoiceMessage(recordDialogId, recordTopicId, null); audioRecorder = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, recordBufferSize); recordStartTime = System.currentTimeMillis(); fileBuffer.rewind(); audioRecorder.startRecording(); recordQueue.postRunnable(recordRunnable); NotificationCenter.getInstance(recordingCurrentAccount).postNotificationName(NotificationCenter.recordResumed); }); }); } }); } public void startRecording(int currentAccount, long dialogId, MessageObject replyToMsg, MessageObject replyToTopMsg, TL_stories.StoryItem replyStory, int guid, boolean manual, String quick_shortcut, int quick_shortcut_id) { boolean paused = false; if (playingMessageObject != null && isPlayingMessage(playingMessageObject) && !isMessagePaused()) { paused = true; } manualRecording = manual; requestAudioFocus(true); try { feedbackView.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING); } catch (Exception ignore) { } recordQueue.postRunnable(recordStartRunnable = () -> { if (audioRecorder != null) { AndroidUtilities.runOnUIThread(() -> { recordStartRunnable = null; NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.recordStartError, guid); }); return; } setBluetoothScoOn(true); sendAfterDone = 0; recordingAudio = new TLRPC.TL_document(); recordingGuid = guid; recordingAudio.file_reference = new byte[0]; recordingAudio.dc_id = Integer.MIN_VALUE; recordingAudio.id = SharedConfig.getLastLocalId(); recordingAudio.user_id = UserConfig.getInstance(currentAccount).getClientUserId(); recordingAudio.mime_type = "audio/ogg"; recordingAudio.file_reference = new byte[0]; SharedConfig.saveConfig(); recordingAudioFile = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_AUDIO), System.currentTimeMillis() + "_" + FileLoader.getAttachFileName(recordingAudio)) { @Override public boolean delete() { if (BuildVars.LOGS_ENABLED) { FileLog.e("delete voice file"); } return super.delete(); } }; FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE).mkdirs(); if (BuildVars.LOGS_ENABLED) { FileLog.d("start recording internal " + recordingAudioFile.getPath() + " " + recordingAudioFile.exists()); } AutoDeleteMediaTask.lockFile(recordingAudioFile); try { if (startRecord(recordingAudioFile.getPath(), sampleRate) == 0) { AndroidUtilities.runOnUIThread(() -> { recordStartRunnable = null; NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.recordStartError, guid); }); if (BuildVars.LOGS_ENABLED) { FileLog.d("cant init encoder"); } return; } audioRecorderPaused = false; audioRecorder = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, recordBufferSize); recordStartTime = System.currentTimeMillis(); recordTimeCount = 0; writedFrame = 0; samplesCount = 0; recordDialogId = dialogId; recordTopicId = replyToTopMsg == null ? 0 : MessageObject.getTopicId(recordingCurrentAccount, replyToTopMsg.messageOwner, false); recordingCurrentAccount = currentAccount; recordReplyingMsg = replyToMsg; recordReplyingTopMsg = replyToTopMsg; recordReplyingStory = replyStory; recordQuickReplyShortcut = quick_shortcut; recordQuickReplyShortcutId = quick_shortcut_id; fileBuffer.rewind(); audioRecorder.startRecording(); } catch (Exception e) { FileLog.e(e); recordingAudio = null; stopRecord(false); AutoDeleteMediaTask.unlockFile(recordingAudioFile); recordingAudioFile.delete(); recordingAudioFile = null; try { audioRecorder.release(); audioRecorder = null; } catch (Exception e2) { FileLog.e(e2); } setBluetoothScoOn(false); AndroidUtilities.runOnUIThread(() -> { recordStartRunnable = null; NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.recordStartError, guid); }); return; } recordQueue.postRunnable(recordRunnable); AndroidUtilities.runOnUIThread(() -> { recordStartRunnable = null; NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.recordStarted, guid, true); }); }, paused ? 500 : 50); } public void generateWaveform(MessageObject messageObject) { final String id = messageObject.getId() + "_" + messageObject.getDialogId(); final String path = FileLoader.getInstance(messageObject.currentAccount).getPathToMessage(messageObject.messageOwner).getAbsolutePath(); if (generatingWaveform.containsKey(id)) { return; } generatingWaveform.put(id, messageObject); Utilities.globalQueue.postRunnable(() -> { final byte[] waveform; try { waveform = getWaveform(path); } catch (Exception e) { FileLog.e(e); return; } AndroidUtilities.runOnUIThread(() -> { MessageObject messageObject1 = generatingWaveform.remove(id); if (messageObject1 == null) { return; } if (waveform != null && messageObject1.getDocument() != null) { for (int a = 0; a < messageObject1.getDocument().attributes.size(); a++) { TLRPC.DocumentAttribute attribute = messageObject1.getDocument().attributes.get(a); if (attribute instanceof TLRPC.TL_documentAttributeAudio) { attribute.waveform = waveform; attribute.flags |= 4; break; } } TLRPC.TL_messages_messages messagesRes = new TLRPC.TL_messages_messages(); messagesRes.messages.add(messageObject1.messageOwner); MessagesStorage.getInstance(messageObject1.currentAccount).putMessages(messagesRes, messageObject1.getDialogId(), -1, 0, false, messageObject.scheduled ? 1 : 0, 0); ArrayList<MessageObject> arrayList = new ArrayList<>(); arrayList.add(messageObject1); NotificationCenter.getInstance(messageObject1.currentAccount).postNotificationName(NotificationCenter.replaceMessagesObjects, messageObject1.getDialogId(), arrayList); } }); }); } public void cleanRecording(boolean delete) { recordingAudio = null; AutoDeleteMediaTask.unlockFile(recordingAudioFile); if (delete && recordingAudioFile != null) { try { recordingAudioFile.delete(); } catch (Exception e) { FileLog.e(e); } } recordingAudioFile = null; manualRecording = false; raiseToEarRecord = false; ignoreOnPause = false; } private void stopRecordingInternal(final int send, boolean notify, int scheduleDate, boolean once) { if (send != 0) { final TLRPC.TL_document audioToSend = recordingAudio; final File recordingAudioFileToSend = recordingAudioFile; if (BuildVars.LOGS_ENABLED) { FileLog.d("stop recording internal filename " + recordingAudioFile.getPath()); } fileEncodingQueue.postRunnable(() -> { stopRecord(false); if (BuildVars.LOGS_ENABLED) { FileLog.d("stop recording internal in queue " + recordingAudioFileToSend.exists() + " " + recordingAudioFileToSend.length()); } AndroidUtilities.runOnUIThread(() -> { if (BuildVars.LOGS_ENABLED) { FileLog.d("stop recording internal " + recordingAudioFileToSend.exists() + " " + recordingAudioFileToSend.length() + " " + " recordTimeCount " + recordTimeCount + " writedFrames" + writedFrame); } boolean fileExist = recordingAudioFileToSend.exists(); if (!fileExist && BuildVars.DEBUG_VERSION) { FileLog.e(new RuntimeException("file not found :( recordTimeCount " + recordTimeCount + " writedFrames" + writedFrame)); } MediaDataController.getInstance(recordingCurrentAccount).pushDraftVoiceMessage(recordDialogId, recordTopicId, null); audioToSend.date = ConnectionsManager.getInstance(recordingCurrentAccount).getCurrentTime(); audioToSend.size = (int) recordingAudioFileToSend.length(); TLRPC.TL_documentAttributeAudio attributeAudio = new TLRPC.TL_documentAttributeAudio(); attributeAudio.voice = true; attributeAudio.waveform = getWaveform2(recordSamples, recordSamples.length); if (attributeAudio.waveform != null) { attributeAudio.flags |= 4; } long duration = recordTimeCount; attributeAudio.duration = recordTimeCount / 1000.0; audioToSend.attributes.clear(); audioToSend.attributes.add(attributeAudio); if (duration > 700) { if (send == 1) { SendMessagesHelper.SendMessageParams params = SendMessagesHelper.SendMessageParams.of(audioToSend, null, recordingAudioFileToSend.getAbsolutePath(), recordDialogId, recordReplyingMsg, recordReplyingTopMsg, null, null, null, null, notify, scheduleDate, once ? 0x7FFFFFFF : 0, null, null, false); params.replyToStoryItem = recordReplyingStory; params.quick_reply_shortcut = recordQuickReplyShortcut; params.quick_reply_shortcut_id = recordQuickReplyShortcutId; SendMessagesHelper.getInstance(recordingCurrentAccount).sendMessage(params); } NotificationCenter.getInstance(recordingCurrentAccount).postNotificationName(NotificationCenter.audioDidSent, recordingGuid, send == 2 ? audioToSend : null, send == 2 ? recordingAudioFileToSend.getAbsolutePath() : null); } else { NotificationCenter.getInstance(recordingCurrentAccount).postNotificationName(NotificationCenter.audioRecordTooShort, recordingGuid, false, (int) duration); AutoDeleteMediaTask.unlockFile(recordingAudioFileToSend); recordingAudioFileToSend.delete(); } requestAudioFocus(false); }); }); } else { AutoDeleteMediaTask.unlockFile(recordingAudioFile); if (recordingAudioFile != null) { recordingAudioFile.delete(); } requestAudioFocus(false); } try { if (audioRecorder != null) { audioRecorder.release(); audioRecorder = null; } } catch (Exception e) { FileLog.e(e); } recordingAudio = null; recordingAudioFile = null; manualRecording = false; raiseToEarRecord = false; ignoreOnPause = false; } public void stopRecording(final int send, boolean notify, int scheduleDate, boolean once) { if (recordStartRunnable != null) { recordQueue.cancelRunnable(recordStartRunnable); recordStartRunnable = null; } recordQueue.postRunnable(() -> { if (sendAfterDone == 3) { sendAfterDone = 0; stopRecordingInternal(send, notify, scheduleDate, once); return; } if (audioRecorder == null) { recordingAudio = null; manualRecording = false; raiseToEarRecord = false; ignoreOnPause = false; return; } try { sendAfterDone = send; sendAfterDoneNotify = notify; sendAfterDoneScheduleDate = scheduleDate; sendAfterDoneOnce = once; audioRecorder.stop(); setBluetoothScoOn(false); } catch (Exception e) { FileLog.e(e); if (recordingAudioFile != null) { if (BuildVars.LOGS_ENABLED) { FileLog.e("delete voice file"); } recordingAudioFile.delete(); } } if (send == 0) { stopRecordingInternal(0, false, 0, false); } try { feedbackView.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING); } catch (Exception ignore) { } AndroidUtilities.runOnUIThread(() -> NotificationCenter.getInstance(recordingCurrentAccount).postNotificationName(NotificationCenter.recordStopped, recordingGuid, send == 2 ? 1 : 0)); }); } private static class MediaLoader implements NotificationCenter.NotificationCenterDelegate { private AccountInstance currentAccount; private AlertDialog progressDialog; private ArrayList<MessageObject> messageObjects; private HashMap<String, MessageObject> loadingMessageObjects = new HashMap<>(); private float finishedProgress; private boolean cancelled; private boolean finished; private int copiedFiles; private CountDownLatch waitingForFile; private MessagesStorage.IntCallback onFinishRunnable; private boolean isMusic; public MediaLoader(Context context, AccountInstance accountInstance, ArrayList<MessageObject> messages, MessagesStorage.IntCallback onFinish) { currentAccount = accountInstance; messageObjects = messages; onFinishRunnable = onFinish; isMusic = messages.get(0).isMusic(); currentAccount.getNotificationCenter().addObserver(this, NotificationCenter.fileLoaded); currentAccount.getNotificationCenter().addObserver(this, NotificationCenter.fileLoadProgressChanged); currentAccount.getNotificationCenter().addObserver(this, NotificationCenter.fileLoadFailed); progressDialog = new AlertDialog(context, AlertDialog.ALERT_TYPE_LOADING); progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading)); progressDialog.setCanceledOnTouchOutside(false); progressDialog.setCancelable(true); progressDialog.setOnCancelListener(d -> cancelled = true); } public void start() { AndroidUtilities.runOnUIThread(() -> { if (!finished) { progressDialog.show(); } }, 250); new Thread(() -> { try { if (Build.VERSION.SDK_INT >= 29) { for (int b = 0, N = messageObjects.size(); b < N; b++) { MessageObject message = messageObjects.get(b); String path = message.messageOwner.attachPath; String name = message.getDocumentName(); if (path != null && path.length() > 0) { File temp = new File(path); if (!temp.exists()) { path = null; } } if (path == null || path.length() == 0) { path = null; TLRPC.Document document = message.getDocument(); if (!TextUtils.isEmpty(FileLoader.getDocumentFileName(document)) && !(message.messageOwner instanceof TLRPC.TL_message_secret) && FileLoader.canSaveAsFile(message)) { String filename = FileLoader.getDocumentFileName(document); File newDir = FileLoader.getDirectory(FileLoader.MEDIA_DIR_FILES); if (newDir != null) { path = new File(newDir, filename).getAbsolutePath(); } } if (path == null) { path = FileLoader.getInstance(currentAccount.getCurrentAccount()).getPathToMessage(message.messageOwner).toString(); } } File sourceFile = new File(path); if (!sourceFile.exists()) { waitingForFile = new CountDownLatch(1); addMessageToLoad(message); waitingForFile.await(); } if (cancelled) { break; } if (sourceFile.exists()) { saveFileInternal(isMusic ? 3 : 2, sourceFile, name); copiedFiles++; } } } else { File dir; if (isMusic) { dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC); } else { dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); } dir.mkdir(); for (int b = 0, N = messageObjects.size(); b < N; b++) { MessageObject message = messageObjects.get(b); String name = message.getDocumentName(); File destFile = new File(dir, name); if (destFile.exists()) { int idx = name.lastIndexOf('.'); for (int a = 0; a < 10; a++) { String newName; if (idx != -1) { newName = name.substring(0, idx) + "(" + (a + 1) + ")" + name.substring(idx); } else { newName = name + "(" + (a + 1) + ")"; } destFile = new File(dir, newName); if (!destFile.exists()) { break; } } } if (!destFile.exists()) { destFile.createNewFile(); } String path = message.messageOwner.attachPath; if (path != null && path.length() > 0) { File temp = new File(path); if (!temp.exists()) { path = null; } } if (path == null || path.length() == 0) { path = FileLoader.getInstance(currentAccount.getCurrentAccount()).getPathToMessage(message.messageOwner).toString(); } File sourceFile = new File(path); if (!sourceFile.exists()) { waitingForFile = new CountDownLatch(1); addMessageToLoad(message); waitingForFile.await(); } if (sourceFile.exists()) { copyFile(sourceFile, destFile, message.getMimeType()); copiedFiles++; } } } checkIfFinished(); } catch (Exception e) { FileLog.e(e); } }).start(); } private void checkIfFinished() { if (!loadingMessageObjects.isEmpty()) { return; } AndroidUtilities.runOnUIThread(() -> { try { if (progressDialog.isShowing()) { progressDialog.dismiss(); } else { finished = true; } if (onFinishRunnable != null) { AndroidUtilities.runOnUIThread(() -> onFinishRunnable.run(copiedFiles)); } } catch (Exception e) { FileLog.e(e); } currentAccount.getNotificationCenter().removeObserver(this, NotificationCenter.fileLoaded); currentAccount.getNotificationCenter().removeObserver(this, NotificationCenter.fileLoadProgressChanged); currentAccount.getNotificationCenter().removeObserver(this, NotificationCenter.fileLoadFailed); }); } private void addMessageToLoad(MessageObject messageObject) { AndroidUtilities.runOnUIThread(() -> { TLRPC.Document document = messageObject.getDocument(); if (document == null) { return; } String fileName = FileLoader.getAttachFileName(document); loadingMessageObjects.put(fileName, messageObject); currentAccount.getFileLoader().loadFile(document, messageObject, FileLoader.PRIORITY_LOW, messageObject.shouldEncryptPhotoOrVideo() ? 2 : 0); }); } private boolean copyFile(File sourceFile, File destFile, String mime) { if (AndroidUtilities.isInternalUri(Uri.fromFile(sourceFile))) { return false; } try (FileInputStream inputStream = new FileInputStream(sourceFile); FileChannel source = inputStream.getChannel(); FileChannel destination = new FileOutputStream(destFile).getChannel()) { long size = source.size(); try { @SuppressLint("DiscouragedPrivateApi") Method getInt = FileDescriptor.class.getDeclaredMethod("getInt$"); int fdint = (Integer) getInt.invoke(inputStream.getFD()); if (AndroidUtilities.isInternalUri(fdint)) { if (progressDialog != null) { AndroidUtilities.runOnUIThread(() -> { try { progressDialog.dismiss(); } catch (Exception e) { FileLog.e(e); } }); } return false; } } catch (Throwable e) { FileLog.e(e); } long lastProgress = 0; for (long a = 0; a < size; a += 4096) { if (cancelled) { break; } destination.transferFrom(source, a, Math.min(4096, size - a)); if (a + 4096 >= size || lastProgress <= SystemClock.elapsedRealtime() - 500) { lastProgress = SystemClock.elapsedRealtime(); final int progress = (int) (finishedProgress + 100.0f / messageObjects.size() * a / size); AndroidUtilities.runOnUIThread(() -> { try { progressDialog.setProgress(progress); } catch (Exception e) { FileLog.e(e); } }); } } if (!cancelled) { if (isMusic) { AndroidUtilities.addMediaToGallery(destFile); } else { DownloadManager downloadManager = (DownloadManager) ApplicationLoader.applicationContext.getSystemService(Context.DOWNLOAD_SERVICE); String mimeType = mime; if (TextUtils.isEmpty(mimeType)) { MimeTypeMap myMime = MimeTypeMap.getSingleton(); String name = destFile.getName(); int idx = name.lastIndexOf('.'); if (idx != -1) { String ext = name.substring(idx + 1); mimeType = myMime.getMimeTypeFromExtension(ext.toLowerCase()); if (TextUtils.isEmpty(mimeType)) { mimeType = "text/plain"; } } else { mimeType = "text/plain"; } } downloadManager.addCompletedDownload(destFile.getName(), destFile.getName(), false, mimeType, destFile.getAbsolutePath(), destFile.length(), true); } finishedProgress += 100.0f / messageObjects.size(); final int progress = (int) (finishedProgress); AndroidUtilities.runOnUIThread(() -> { try { progressDialog.setProgress(progress); } catch (Exception e) { FileLog.e(e); } }); return true; } } catch (Exception e) { FileLog.e(e); } destFile.delete(); return false; } @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.fileLoaded || id == NotificationCenter.fileLoadFailed) { String fileName = (String) args[0]; if (loadingMessageObjects.remove(fileName) != null) { waitingForFile.countDown(); } } else if (id == NotificationCenter.fileLoadProgressChanged) { String fileName = (String) args[0]; if (loadingMessageObjects.containsKey(fileName)) { Long loadedSize = (Long) args[1]; Long totalSize = (Long) args[2]; float loadProgress = loadedSize / (float) totalSize; final int progress = (int) (finishedProgress + loadProgress / messageObjects.size() * 100); AndroidUtilities.runOnUIThread(() -> { try { progressDialog.setProgress(progress); } catch (Exception e) { FileLog.e(e); } }); } } } } public static void saveFilesFromMessages(Context context, AccountInstance accountInstance, ArrayList<MessageObject> messageObjects, final MessagesStorage.IntCallback onSaved) { if (messageObjects == null || messageObjects.isEmpty()) { return; } new MediaLoader(context, accountInstance, messageObjects, onSaved).start(); } public static void saveFile(String fullPath, Context context, final int type, final String name, final String mime) { saveFile(fullPath, context, type, name, mime, null); } public static void saveFile(String fullPath, Context context, final int type, final String name, final String mime, final Utilities.Callback<Uri> onSaved) { saveFile(fullPath, context, type, name, mime, onSaved, true); } public static void saveFile(String fullPath, Context context, final int type, final String name, final String mime, final Utilities.Callback<Uri> onSaved, boolean showProgress) { if (fullPath == null || context == null) { return; } File file = null; if (!TextUtils.isEmpty(fullPath)) { file = new File(fullPath); if (!file.exists() || AndroidUtilities.isInternalUri(Uri.fromFile(file))) { file = null; } } if (file == null) { return; } final File sourceFile = file; final boolean[] cancelled = new boolean[]{false}; if (sourceFile.exists()) { AlertDialog progressDialog = null; final boolean[] finished = new boolean[1]; if (context != null && type != 0) { try { final AlertDialog dialog = new AlertDialog(context, AlertDialog.ALERT_TYPE_LOADING); dialog.setMessage(LocaleController.getString("Loading", R.string.Loading)); dialog.setCanceledOnTouchOutside(false); dialog.setCancelable(true); dialog.setOnCancelListener(d -> cancelled[0] = true); AndroidUtilities.runOnUIThread(() -> { if (!finished[0]) { dialog.show(); } }, 250); progressDialog = dialog; } catch (Exception e) { FileLog.e(e); } } final AlertDialog finalProgress = progressDialog; new Thread(() -> { try { Uri uri; boolean result = true; if (Build.VERSION.SDK_INT >= 29) { uri = saveFileInternal(type, sourceFile, null); result = uri != null; } else { File destFile; if (type == 0) { destFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Telegram"); destFile.mkdirs(); destFile = new File(destFile, AndroidUtilities.generateFileName(0, FileLoader.getFileExtension(sourceFile))); } else if (type == 1) { destFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), "Telegram"); destFile.mkdirs(); destFile = new File(destFile, AndroidUtilities.generateFileName(1, FileLoader.getFileExtension(sourceFile))); } else { File dir; if (type == 2) { dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); } else { dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC); } dir = new File(dir, "Telegram"); dir.mkdirs(); destFile = new File(dir, name); if (destFile.exists()) { int idx = name.lastIndexOf('.'); for (int a = 0; a < 10; a++) { String newName; if (idx != -1) { newName = name.substring(0, idx) + "(" + (a + 1) + ")" + name.substring(idx); } else { newName = name + "(" + (a + 1) + ")"; } destFile = new File(dir, newName); if (!destFile.exists()) { break; } } } } if (!destFile.exists()) { destFile.createNewFile(); } long lastProgress = System.currentTimeMillis() - 500; try (FileInputStream inputStream = new FileInputStream(sourceFile); FileChannel source = inputStream.getChannel(); FileChannel destination = new FileOutputStream(destFile).getChannel()) { long size = source.size(); try { @SuppressLint("DiscouragedPrivateApi") Method getInt = FileDescriptor.class.getDeclaredMethod("getInt$"); int fdint = (Integer) getInt.invoke(inputStream.getFD()); if (AndroidUtilities.isInternalUri(fdint)) { if (finalProgress != null) { AndroidUtilities.runOnUIThread(() -> { try { finalProgress.dismiss(); } catch (Exception e) { FileLog.e(e); } }); } return; } } catch (Throwable e) { FileLog.e(e); } for (long a = 0; a < size; a += 4096) { if (cancelled[0]) { break; } destination.transferFrom(source, a, Math.min(4096, size - a)); if (finalProgress != null) { if (lastProgress <= System.currentTimeMillis() - 500) { lastProgress = System.currentTimeMillis(); final int progress = (int) ((float) a / (float) size * 100); AndroidUtilities.runOnUIThread(() -> { try { finalProgress.setProgress(progress); } catch (Exception e) { FileLog.e(e); } }); } } } } catch (Exception e) { FileLog.e(e); result = false; } if (cancelled[0]) { destFile.delete(); result = false; } if (result) { if (type == 2) { DownloadManager downloadManager = (DownloadManager) ApplicationLoader.applicationContext.getSystemService(Context.DOWNLOAD_SERVICE); downloadManager.addCompletedDownload(destFile.getName(), destFile.getName(), false, mime, destFile.getAbsolutePath(), destFile.length(), true); } else { AndroidUtilities.addMediaToGallery(destFile.getAbsoluteFile()); } } uri = Uri.fromFile(destFile); } if (result && onSaved != null) { AndroidUtilities.runOnUIThread(() -> onSaved.run(uri)); } } catch (Exception e) { FileLog.e(e); } if (finalProgress != null) { AndroidUtilities.runOnUIThread(() -> { try { if (finalProgress.isShowing()) { finalProgress.dismiss(); } else { finished[0] = true; } } catch (Exception e) { FileLog.e(e); } }); } }).start(); } } private static Uri saveFileInternal(int type, File sourceFile, String filename) { try { int selectedType = type; ContentValues contentValues = new ContentValues(); String extension = FileLoader.getFileExtension(sourceFile); String mimeType = null; if (extension != null) { mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); } Uri uriToInsert = null; if ((type == 0 || type == 1) && mimeType != null) { if (mimeType.startsWith("image")) { selectedType = 0; } if (mimeType.startsWith("video")) { selectedType = 1; } } if (selectedType == 0) { if (filename == null) { filename = AndroidUtilities.generateFileName(0, extension); } uriToInsert = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY); File dirDest = new File(Environment.DIRECTORY_PICTURES, "Telegram"); contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, dirDest + File.separator); contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, filename); contentValues.put(MediaStore.Images.Media.MIME_TYPE, mimeType); } else if (selectedType == 1) { if (filename == null) { filename = AndroidUtilities.generateFileName(1, extension); } File dirDest = new File(Environment.DIRECTORY_MOVIES, "Telegram"); contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, dirDest + File.separator); uriToInsert = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY); contentValues.put(MediaStore.Video.Media.DISPLAY_NAME, filename); } else if (selectedType == 2) { if (filename == null) { filename = sourceFile.getName(); } File dirDest = new File(Environment.DIRECTORY_DOWNLOADS, "Telegram"); contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, dirDest + File.separator); uriToInsert = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY); contentValues.put(MediaStore.Downloads.DISPLAY_NAME, filename); } else { if (filename == null) { filename = sourceFile.getName(); } File dirDest = new File(Environment.DIRECTORY_MUSIC, "Telegram"); contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, dirDest + File.separator); uriToInsert = MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY); contentValues.put(MediaStore.Audio.Media.DISPLAY_NAME, filename); } contentValues.put(MediaStore.MediaColumns.MIME_TYPE, mimeType); Uri dstUri = ApplicationLoader.applicationContext.getContentResolver().insert(uriToInsert, contentValues); if (dstUri != null) { FileInputStream fileInputStream = new FileInputStream(sourceFile); OutputStream outputStream = ApplicationLoader.applicationContext.getContentResolver().openOutputStream(dstUri); AndroidUtilities.copyFile(fileInputStream, outputStream); fileInputStream.close(); } return dstUri; } catch (Exception e) { FileLog.e(e); return null; } } public static String getStickerExt(Uri uri) { InputStream inputStream = null; try { try { inputStream = ApplicationLoader.applicationContext.getContentResolver().openInputStream(uri); } catch (Exception e) { inputStream = null; } if (inputStream == null) { File file = new File(uri.getPath()); if (file.exists()) { inputStream = new FileInputStream(file); } } byte[] header = new byte[12]; if (inputStream.read(header, 0, 12) == 12) { if (header[0] == (byte) 0x89 && header[1] == (byte) 0x50 && header[2] == (byte) 0x4E && header[3] == (byte) 0x47 && header[4] == (byte) 0x0D && header[5] == (byte) 0x0A && header[6] == (byte) 0x1A && header[7] == (byte) 0x0A) { return "png"; } if (header[0] == 0x1f && header[1] == (byte) 0x8b) { return "tgs"; } String str = new String(header); if (str != null) { str = str.toLowerCase(); if (str.startsWith("riff") && str.endsWith("webp")) { return "webp"; } } } } catch (Exception e) { FileLog.e(e); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (Exception e2) { FileLog.e(e2); } } return null; } public static boolean isWebp(Uri uri) { InputStream inputStream = null; try { inputStream = ApplicationLoader.applicationContext.getContentResolver().openInputStream(uri); byte[] header = new byte[12]; if (inputStream.read(header, 0, 12) == 12) { String str = new String(header); str = str.toLowerCase(); if (str.startsWith("riff") && str.endsWith("webp")) { return true; } } } catch (Exception e) { FileLog.e(e); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (Exception e2) { FileLog.e(e2); } } return false; } public static boolean isGif(Uri uri) { InputStream inputStream = null; try { inputStream = ApplicationLoader.applicationContext.getContentResolver().openInputStream(uri); byte[] header = new byte[3]; if (inputStream.read(header, 0, 3) == 3) { String str = new String(header); if (str.equalsIgnoreCase("gif")) { return true; } } } catch (Exception e) { FileLog.e(e); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (Exception e2) { FileLog.e(e2); } } return false; } public static String getFileName(Uri uri) { if (uri == null) { return ""; } try { String result = null; if (uri.getScheme().equals("content")) { try (Cursor cursor = ApplicationLoader.applicationContext.getContentResolver().query(uri, new String[]{OpenableColumns.DISPLAY_NAME}, null, null, null)) { if (cursor.moveToFirst()) { result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); } } catch (Exception e) { FileLog.e(e); } } if (result == null) { result = uri.getPath(); int cut = result.lastIndexOf('/'); if (cut != -1) { result = result.substring(cut + 1); } } return result; } catch (Exception e) { FileLog.e(e); } return ""; } public static String copyFileToCache(Uri uri, String ext) { return copyFileToCache(uri, ext, -1); } @SuppressLint("DiscouragedPrivateApi") public static String copyFileToCache(Uri uri, String ext, long sizeLimit) { InputStream inputStream = null; FileOutputStream output = null; int totalLen = 0; File f = null; try { String name = FileLoader.fixFileName(getFileName(uri)); if (name == null) { int id = SharedConfig.getLastLocalId(); SharedConfig.saveConfig(); name = String.format(Locale.US, "%d.%s", id, ext); } f = AndroidUtilities.getSharingDirectory(); f.mkdirs(); if (AndroidUtilities.isInternalUri(Uri.fromFile(f))) { return null; } int count = 0; do { f = AndroidUtilities.getSharingDirectory(); if (count == 0) { f = new File(f, name); } else { int lastDotIndex = name.lastIndexOf("."); if (lastDotIndex > 0) { f = new File(f, name.substring(0, lastDotIndex) + " (" + count + ")" + name.substring(lastDotIndex)); } else { f = new File(f, name + " (" + count + ")"); } } count++; } while (f.exists()); inputStream = ApplicationLoader.applicationContext.getContentResolver().openInputStream(uri); if (inputStream instanceof FileInputStream) { FileInputStream fileInputStream = (FileInputStream) inputStream; try { Method getInt = FileDescriptor.class.getDeclaredMethod("getInt$"); int fdint = (Integer) getInt.invoke(fileInputStream.getFD()); if (AndroidUtilities.isInternalUri(fdint)) { return null; } } catch (Throwable e) { FileLog.e(e); } } output = new FileOutputStream(f); byte[] buffer = new byte[1024 * 20]; int len; while ((len = inputStream.read(buffer)) != -1) { output.write(buffer, 0, len); totalLen += len; if (sizeLimit > 0 && totalLen > sizeLimit) { return null; } } return f.getAbsolutePath(); } catch (Exception e) { FileLog.e(e); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (Exception e2) { FileLog.e(e2); } try { if (output != null) { output.close(); } } catch (Exception e2) { FileLog.e(e2); } if (sizeLimit > 0 && totalLen > sizeLimit) { f.delete(); } } return null; } public static void loadGalleryPhotosAlbums(final int guid) { Thread thread = new Thread(() -> { final ArrayList<AlbumEntry> mediaAlbumsSorted = new ArrayList<>(); final ArrayList<AlbumEntry> photoAlbumsSorted = new ArrayList<>(); SparseArray<AlbumEntry> mediaAlbums = new SparseArray<>(); SparseArray<AlbumEntry> photoAlbums = new SparseArray<>(); AlbumEntry allPhotosAlbum = null; AlbumEntry allVideosAlbum = null; AlbumEntry allMediaAlbum = null; String cameraFolder = null; try { cameraFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath() + "/" + "Camera/"; } catch (Exception e) { FileLog.e(e); } Integer mediaCameraAlbumId = null; Integer photoCameraAlbumId = null; Cursor cursor = null; try { final Context context = ApplicationLoader.applicationContext; if ( Build.VERSION.SDK_INT < 23 || Build.VERSION.SDK_INT < 33 && context.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED || Build.VERSION.SDK_INT >= 33 && ( context.checkSelfPermission(Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED || context.checkSelfPermission(Manifest.permission.READ_MEDIA_VIDEO) == PackageManager.PERMISSION_GRANTED || context.checkSelfPermission(Manifest.permission.READ_MEDIA_AUDIO) == PackageManager.PERMISSION_GRANTED ) ) { cursor = MediaStore.Images.Media.query(context.getContentResolver(), MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projectionPhotos, null, null, (Build.VERSION.SDK_INT > 28 ? MediaStore.Images.Media.DATE_MODIFIED : MediaStore.Images.Media.DATE_TAKEN) + " DESC"); if (cursor != null) { int imageIdColumn = cursor.getColumnIndex(MediaStore.Images.Media._ID); int bucketIdColumn = cursor.getColumnIndex(MediaStore.Images.Media.BUCKET_ID); int bucketNameColumn = cursor.getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME); int dataColumn = cursor.getColumnIndex(MediaStore.Images.Media.DATA); int dateColumn = cursor.getColumnIndex(Build.VERSION.SDK_INT > 28 ? MediaStore.Images.Media.DATE_MODIFIED : MediaStore.Images.Media.DATE_TAKEN); int orientationColumn = cursor.getColumnIndex(MediaStore.Images.Media.ORIENTATION); int widthColumn = cursor.getColumnIndex(MediaStore.Images.Media.WIDTH); int heightColumn = cursor.getColumnIndex(MediaStore.Images.Media.HEIGHT); int sizeColumn = cursor.getColumnIndex(MediaStore.Images.Media.SIZE); while (cursor.moveToNext()) { String path = cursor.getString(dataColumn); if (TextUtils.isEmpty(path)) { continue; } int imageId = cursor.getInt(imageIdColumn); int bucketId = cursor.getInt(bucketIdColumn); String bucketName = cursor.getString(bucketNameColumn); long dateTaken = cursor.getLong(dateColumn); int orientation = cursor.getInt(orientationColumn); int width = cursor.getInt(widthColumn); int height = cursor.getInt(heightColumn); long size = cursor.getLong(sizeColumn); PhotoEntry photoEntry = new PhotoEntry(bucketId, imageId, dateTaken, path, orientation, false, width, height, size); if (allPhotosAlbum == null) { allPhotosAlbum = new AlbumEntry(0, LocaleController.getString("AllPhotos", R.string.AllPhotos), photoEntry); photoAlbumsSorted.add(0, allPhotosAlbum); } if (allMediaAlbum == null) { allMediaAlbum = new AlbumEntry(0, LocaleController.getString("AllMedia", R.string.AllMedia), photoEntry); mediaAlbumsSorted.add(0, allMediaAlbum); } allPhotosAlbum.addPhoto(photoEntry); allMediaAlbum.addPhoto(photoEntry); AlbumEntry albumEntry = mediaAlbums.get(bucketId); if (albumEntry == null) { albumEntry = new AlbumEntry(bucketId, bucketName, photoEntry); mediaAlbums.put(bucketId, albumEntry); if (mediaCameraAlbumId == null && cameraFolder != null && path != null && path.startsWith(cameraFolder)) { mediaAlbumsSorted.add(0, albumEntry); mediaCameraAlbumId = bucketId; } else { mediaAlbumsSorted.add(albumEntry); } } albumEntry.addPhoto(photoEntry); albumEntry = photoAlbums.get(bucketId); if (albumEntry == null) { albumEntry = new AlbumEntry(bucketId, bucketName, photoEntry); photoAlbums.put(bucketId, albumEntry); if (photoCameraAlbumId == null && cameraFolder != null && path != null && path.startsWith(cameraFolder)) { photoAlbumsSorted.add(0, albumEntry); photoCameraAlbumId = bucketId; } else { photoAlbumsSorted.add(albumEntry); } } albumEntry.addPhoto(photoEntry); } } } } catch (Throwable e) { FileLog.e(e); } finally { if (cursor != null) { try { cursor.close(); } catch (Exception e) { FileLog.e(e); } } } try { final Context context = ApplicationLoader.applicationContext; if ( Build.VERSION.SDK_INT < 23 || Build.VERSION.SDK_INT < 33 && context.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED || Build.VERSION.SDK_INT >= 33 && ( context.checkSelfPermission(Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED || context.checkSelfPermission(Manifest.permission.READ_MEDIA_VIDEO) == PackageManager.PERMISSION_GRANTED || context.checkSelfPermission(Manifest.permission.READ_MEDIA_AUDIO) == PackageManager.PERMISSION_GRANTED ) ) { cursor = MediaStore.Images.Media.query(ApplicationLoader.applicationContext.getContentResolver(), MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projectionVideo, null, null, (Build.VERSION.SDK_INT > 28 ? MediaStore.Video.Media.DATE_MODIFIED : MediaStore.Video.Media.DATE_TAKEN) + " DESC"); if (cursor != null) { int imageIdColumn = cursor.getColumnIndex(MediaStore.Video.Media._ID); int bucketIdColumn = cursor.getColumnIndex(MediaStore.Video.Media.BUCKET_ID); int bucketNameColumn = cursor.getColumnIndex(MediaStore.Video.Media.BUCKET_DISPLAY_NAME); int dataColumn = cursor.getColumnIndex(MediaStore.Video.Media.DATA); int dateColumn = cursor.getColumnIndex(Build.VERSION.SDK_INT > 28 ? MediaStore.Video.Media.DATE_MODIFIED : MediaStore.Video.Media.DATE_TAKEN); int durationColumn = cursor.getColumnIndex(MediaStore.Video.Media.DURATION); int widthColumn = cursor.getColumnIndex(MediaStore.Video.Media.WIDTH); int heightColumn = cursor.getColumnIndex(MediaStore.Video.Media.HEIGHT); int sizeColumn = cursor.getColumnIndex(MediaStore.Video.Media.SIZE); while (cursor.moveToNext()) { String path = cursor.getString(dataColumn); if (TextUtils.isEmpty(path)) { continue; } int imageId = cursor.getInt(imageIdColumn); int bucketId = cursor.getInt(bucketIdColumn); String bucketName = cursor.getString(bucketNameColumn); long dateTaken = cursor.getLong(dateColumn); long duration = cursor.getLong(durationColumn); int width = cursor.getInt(widthColumn); int height = cursor.getInt(heightColumn); long size = cursor.getLong(sizeColumn); PhotoEntry photoEntry = new PhotoEntry(bucketId, imageId, dateTaken, path, (int) (duration / 1000), true, width, height, size); if (allVideosAlbum == null) { allVideosAlbum = new AlbumEntry(0, LocaleController.getString("AllVideos", R.string.AllVideos), photoEntry); allVideosAlbum.videoOnly = true; int index = 0; if (allMediaAlbum != null) { index++; } if (allPhotosAlbum != null) { index++; } mediaAlbumsSorted.add(index, allVideosAlbum); } if (allMediaAlbum == null) { allMediaAlbum = new AlbumEntry(0, LocaleController.getString("AllMedia", R.string.AllMedia), photoEntry); mediaAlbumsSorted.add(0, allMediaAlbum); } allVideosAlbum.addPhoto(photoEntry); allMediaAlbum.addPhoto(photoEntry); AlbumEntry albumEntry = mediaAlbums.get(bucketId); if (albumEntry == null) { albumEntry = new AlbumEntry(bucketId, bucketName, photoEntry); mediaAlbums.put(bucketId, albumEntry); if (mediaCameraAlbumId == null && cameraFolder != null && path != null && path.startsWith(cameraFolder)) { mediaAlbumsSorted.add(0, albumEntry); mediaCameraAlbumId = bucketId; } else { mediaAlbumsSorted.add(albumEntry); } } albumEntry.addPhoto(photoEntry); } } } } catch (Throwable e) { FileLog.e(e); } finally { if (cursor != null) { try { cursor.close(); } catch (Exception e) { FileLog.e(e); } } } for (int a = 0; a < mediaAlbumsSorted.size(); a++) { Collections.sort(mediaAlbumsSorted.get(a).photos, (o1, o2) -> { if (o1.dateTaken < o2.dateTaken) { return 1; } else if (o1.dateTaken > o2.dateTaken) { return -1; } return 0; }); } broadcastNewPhotos(guid, mediaAlbumsSorted, photoAlbumsSorted, mediaCameraAlbumId, allMediaAlbum, allPhotosAlbum, allVideosAlbum, 0); }); thread.setPriority(Thread.MIN_PRIORITY); thread.start(); } public static boolean forceBroadcastNewPhotos; private static void broadcastNewPhotos(final int guid, final ArrayList<AlbumEntry> mediaAlbumsSorted, final ArrayList<AlbumEntry> photoAlbumsSorted, final Integer cameraAlbumIdFinal, final AlbumEntry allMediaAlbumFinal, final AlbumEntry allPhotosAlbumFinal, final AlbumEntry allVideosAlbumFinal, int delay) { if (broadcastPhotosRunnable != null) { AndroidUtilities.cancelRunOnUIThread(broadcastPhotosRunnable); } AndroidUtilities.runOnUIThread(broadcastPhotosRunnable = () -> { if (PhotoViewer.getInstance().isVisible() && !forceBroadcastNewPhotos) { broadcastNewPhotos(guid, mediaAlbumsSorted, photoAlbumsSorted, cameraAlbumIdFinal, allMediaAlbumFinal, allPhotosAlbumFinal, allVideosAlbumFinal, 1000); return; } allMediaAlbums = mediaAlbumsSorted; allPhotoAlbums = photoAlbumsSorted; broadcastPhotosRunnable = null; allPhotosAlbumEntry = allPhotosAlbumFinal; allMediaAlbumEntry = allMediaAlbumFinal; allVideosAlbumEntry = allVideosAlbumFinal; NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.albumsDidLoad, guid, mediaAlbumsSorted, photoAlbumsSorted, cameraAlbumIdFinal); }, delay); } public void scheduleVideoConvert(MessageObject messageObject) { scheduleVideoConvert(messageObject, false, true); } public boolean scheduleVideoConvert(MessageObject messageObject, boolean isEmpty, boolean withForeground) { if (messageObject == null || messageObject.videoEditedInfo == null) { return false; } if (isEmpty && !videoConvertQueue.isEmpty()) { return false; } else if (isEmpty) { new File(messageObject.messageOwner.attachPath).delete(); } VideoConvertMessage videoConvertMessage = new VideoConvertMessage(messageObject, messageObject.videoEditedInfo, withForeground); videoConvertQueue.add(videoConvertMessage); if (videoConvertMessage.foreground) { foregroundConvertingMessages.add(videoConvertMessage); checkForegroundConvertMessage(false); } if (videoConvertQueue.size() == 1) { startVideoConvertFromQueue(); } return true; } public void cancelVideoConvert(MessageObject messageObject) { if (messageObject != null) { if (!videoConvertQueue.isEmpty()) { for (int a = 0; a < videoConvertQueue.size(); a++) { VideoConvertMessage videoConvertMessage = videoConvertQueue.get(a); MessageObject object = videoConvertMessage.messageObject; if (object.equals(messageObject) && object.currentAccount == messageObject.currentAccount) { if (a == 0) { synchronized (videoConvertSync) { videoConvertMessage.videoEditedInfo.canceled = true; } } else { VideoConvertMessage convertMessage = videoConvertQueue.remove(a); foregroundConvertingMessages.remove(convertMessage); checkForegroundConvertMessage(true); } break; } } } } } private void checkForegroundConvertMessage(boolean cancelled) { if (!foregroundConvertingMessages.isEmpty()) { currentForegroundConvertingVideo = foregroundConvertingMessages.get(0); } else { currentForegroundConvertingVideo = null; } if (currentForegroundConvertingVideo != null || cancelled) { VideoEncodingService.start(cancelled); } } private boolean startVideoConvertFromQueue() { if (!videoConvertQueue.isEmpty()) { VideoConvertMessage videoConvertMessage = videoConvertQueue.get(0); VideoEditedInfo videoEditedInfo = videoConvertMessage.videoEditedInfo; synchronized (videoConvertSync) { if (videoEditedInfo != null) { videoEditedInfo.canceled = false; } } VideoConvertRunnable.runConversion(videoConvertMessage); return true; } return false; } @SuppressLint("NewApi") public static MediaCodecInfo selectCodec(String mimeType) { int numCodecs = MediaCodecList.getCodecCount(); MediaCodecInfo lastCodecInfo = null; for (int i = 0; i < numCodecs; i++) { MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i); if (!codecInfo.isEncoder()) { continue; } String[] types = codecInfo.getSupportedTypes(); for (String type : types) { if (type.equalsIgnoreCase(mimeType)) { lastCodecInfo = codecInfo; String name = lastCodecInfo.getName(); if (name != null) { if (!name.equals("OMX.SEC.avc.enc")) { return lastCodecInfo; } else if (name.equals("OMX.SEC.AVC.Encoder")) { return lastCodecInfo; } } } } } return lastCodecInfo; } private static boolean isRecognizedFormat(int colorFormat) { switch (colorFormat) { case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar: case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420PackedPlanar: case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar: case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420PackedSemiPlanar: case MediaCodecInfo.CodecCapabilities.COLOR_TI_FormatYUV420PackedSemiPlanar: return true; default: return false; } } @SuppressLint("NewApi") public static int selectColorFormat(MediaCodecInfo codecInfo, String mimeType) { MediaCodecInfo.CodecCapabilities capabilities = codecInfo.getCapabilitiesForType(mimeType); int lastColorFormat = 0; for (int i = 0; i < capabilities.colorFormats.length; i++) { int colorFormat = capabilities.colorFormats[i]; if (isRecognizedFormat(colorFormat)) { lastColorFormat = colorFormat; if (!(codecInfo.getName().equals("OMX.SEC.AVC.Encoder") && colorFormat == 19)) { return colorFormat; } } } return lastColorFormat; } public static int findTrack(MediaExtractor extractor, boolean audio) { int numTracks = extractor.getTrackCount(); for (int i = 0; i < numTracks; i++) { MediaFormat format = extractor.getTrackFormat(i); String mime = format.getString(MediaFormat.KEY_MIME); if (audio) { if (mime.startsWith("audio/")) { return i; } } else { if (mime.startsWith("video/")) { return i; } } } return -5; } public static boolean isH264Video(String videoPath) { MediaExtractor extractor = new MediaExtractor(); try { extractor.setDataSource(videoPath); int videoIndex = MediaController.findTrack(extractor, false); return videoIndex >= 0 && extractor.getTrackFormat(videoIndex).getString(MediaFormat.KEY_MIME).equals(MediaController.VIDEO_MIME_TYPE); } catch (Exception e) { FileLog.e(e); } finally { extractor.release(); } return false; } private void didWriteData(final VideoConvertMessage message, final File file, final boolean last, final long lastFrameTimestamp, long availableSize, final boolean error, final float progress) { final boolean firstWrite = message.videoEditedInfo.videoConvertFirstWrite; if (firstWrite) { message.videoEditedInfo.videoConvertFirstWrite = false; } AndroidUtilities.runOnUIThread(() -> { if (error || last) { boolean cancelled = message.videoEditedInfo.canceled; synchronized (videoConvertSync) { message.videoEditedInfo.canceled = false; } videoConvertQueue.remove(message); foregroundConvertingMessages.remove(message); checkForegroundConvertMessage(cancelled || error); startVideoConvertFromQueue(); } if (error) { NotificationCenter.getInstance(message.currentAccount).postNotificationName(NotificationCenter.filePreparingFailed, message.messageObject, file.toString(), progress, lastFrameTimestamp); } else { if (firstWrite) { NotificationCenter.getInstance(message.currentAccount).postNotificationName(NotificationCenter.filePreparingStarted, message.messageObject, file.toString(), progress, lastFrameTimestamp); } NotificationCenter.getInstance(message.currentAccount).postNotificationName(NotificationCenter.fileNewChunkAvailable, message.messageObject, file.toString(), availableSize, last ? file.length() : 0, progress, lastFrameTimestamp); } }); } public void pauseByRewind() { if (audioPlayer != null) { audioPlayer.pause(); } } public void resumeByRewind() { if (audioPlayer != null && playingMessageObject != null && !isPaused) { if (audioPlayer.isBuffering()) { MessageObject currentMessageObject = playingMessageObject; cleanupPlayer(false, false); playMessage(currentMessageObject); } else { audioPlayer.play(); } } } private static class VideoConvertRunnable implements Runnable { private VideoConvertMessage convertMessage; private VideoConvertRunnable(VideoConvertMessage message) { convertMessage = message; } @Override public void run() { MediaController.getInstance().convertVideo(convertMessage); } public static void runConversion(final VideoConvertMessage obj) { new Thread(() -> { try { VideoConvertRunnable wrapper = new VideoConvertRunnable(obj); Thread th = new Thread(wrapper, "VideoConvertRunnable"); th.start(); th.join(); } catch (Exception e) { FileLog.e(e); } }).start(); } } private boolean convertVideo(final VideoConvertMessage convertMessage) { MessageObject messageObject = convertMessage.messageObject; VideoEditedInfo info = convertMessage.videoEditedInfo; if (messageObject == null || info == null) { return false; } String videoPath = info.originalPath; long startTime = info.startTime; long avatarStartTime = info.avatarStartTime; long endTime = info.endTime; int resultWidth = info.resultWidth; int resultHeight = info.resultHeight; int rotationValue = info.rotationValue; int originalWidth = info.originalWidth; int originalHeight = info.originalHeight; int framerate = info.framerate; int bitrate = info.bitrate; int originalBitrate = info.originalBitrate; boolean isSecret = DialogObject.isEncryptedDialog(messageObject.getDialogId()) || info.forceFragmenting; final File cacheFile = new File(messageObject.messageOwner.attachPath); if (cacheFile.exists()) { cacheFile.delete(); } if (BuildVars.LOGS_ENABLED) { FileLog.d("begin convert " + videoPath + " startTime = " + startTime + " avatarStartTime = " + avatarStartTime + " endTime " + endTime + " rWidth = " + resultWidth + " rHeight = " + resultHeight + " rotation = " + rotationValue + " oWidth = " + originalWidth + " oHeight = " + originalHeight + " framerate = " + framerate + " bitrate = " + bitrate + " originalBitrate = " + originalBitrate); } if (videoPath == null) { videoPath = ""; } long duration; if (startTime > 0 && endTime > 0) { duration = endTime - startTime; } else if (endTime > 0) { duration = endTime; } else if (startTime > 0) { duration = info.originalDuration - startTime; } else { duration = info.originalDuration; } if (framerate == 0) { framerate = 25; } else if (framerate > 59) { framerate = 59; } if (rotationValue == 90 || rotationValue == 270) { int temp = resultHeight; resultHeight = resultWidth; resultWidth = temp; } if (!info.shouldLimitFps && framerate > 40 && (Math.min(resultHeight, resultWidth) <= 480)) { framerate = 30; } boolean needCompress = avatarStartTime != -1 || info.cropState != null || info.mediaEntities != null || info.paintPath != null || info.filterState != null || resultWidth != originalWidth || resultHeight != originalHeight || rotationValue != 0 || info.roundVideo || startTime != -1 || !info.mixedSoundInfos.isEmpty(); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("videoconvert", Activity.MODE_PRIVATE); long time = System.currentTimeMillis(); VideoConvertorListener callback = new VideoConvertorListener() { private long lastAvailableSize = 0; @Override public boolean checkConversionCanceled() { return info.canceled; } @Override public void didWriteData(long availableSize, float progress) { if (info.canceled) { return; } if (availableSize < 0) { availableSize = cacheFile.length(); } if (!info.needUpdateProgress && lastAvailableSize == availableSize) { return; } lastAvailableSize = availableSize; MediaController.this.didWriteData(convertMessage, cacheFile, false, 0, availableSize, false, progress); } }; info.videoConvertFirstWrite = true; MediaCodecVideoConvertor videoConvertor = new MediaCodecVideoConvertor(); MediaCodecVideoConvertor.ConvertVideoParams convertVideoParams = MediaCodecVideoConvertor.ConvertVideoParams.of(videoPath, cacheFile, rotationValue, isSecret, originalWidth, originalHeight, resultWidth, resultHeight, framerate, bitrate, originalBitrate, startTime, endTime, avatarStartTime, needCompress, duration, callback, info); convertVideoParams.soundInfos.addAll(info.mixedSoundInfos); boolean error = videoConvertor.convertVideo(convertVideoParams); boolean canceled = info.canceled; if (!canceled) { synchronized (videoConvertSync) { canceled = info.canceled; } } if (BuildVars.LOGS_ENABLED) { FileLog.d("time=" + (System.currentTimeMillis() - time) + " canceled=" + canceled); } preferences.edit().putBoolean("isPreviousOk", true).apply(); didWriteData(convertMessage, cacheFile, true, videoConvertor.getLastFrameTimestamp(), cacheFile.length(), error || canceled, 1f); return true; } public static int getVideoBitrate(String path) { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); int bitrate = 0; try { retriever.setDataSource(path); bitrate = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE)); } catch (Exception e) { FileLog.e(e); } try { retriever.release(); } catch (Throwable throwable) { FileLog.e(throwable); } return bitrate; } public static int makeVideoBitrate(int originalHeight, int originalWidth, int originalBitrate, int height, int width) { float compressFactor; float minCompressFactor; int maxBitrate; if (Math.min(height, width) >= 1080) { maxBitrate = 6800_000; compressFactor = 1f; minCompressFactor = 1f; } else if (Math.min(height, width) >= 720) { maxBitrate = 2600_000; compressFactor = 1f; minCompressFactor = 1f; } else if (Math.min(height, width) >= 480) { maxBitrate = 1000_000; compressFactor = 0.75f; minCompressFactor = 0.9f; } else { maxBitrate = 750_000; compressFactor = 0.6f; minCompressFactor = 0.7f; } int remeasuredBitrate = (int) (originalBitrate / (Math.min(originalHeight / (float) (height), originalWidth / (float) (width)))); remeasuredBitrate *= compressFactor; int minBitrate = (int) (getVideoBitrateWithFactor(minCompressFactor) / (1280f * 720f / (width * height))); if (originalBitrate < minBitrate) { return remeasuredBitrate; } if (remeasuredBitrate > maxBitrate) { return maxBitrate; } return Math.max(remeasuredBitrate, minBitrate); } /** * Some encoders(e.g. OMX.Exynos) can forcibly raise bitrate during encoder initialization. */ public static int extractRealEncoderBitrate(int width, int height, int bitrate, boolean tryHevc) { String cacheKey = width + "" + height + "" + bitrate; Integer cachedBitrate = cachedEncoderBitrates.get(cacheKey); if (cachedBitrate != null) return cachedBitrate; try { MediaCodec encoder = null; if (tryHevc) { try { encoder = MediaCodec.createEncoderByType("video/hevc"); } catch (Exception ignore) {} } if (encoder == null) { encoder = MediaCodec.createEncoderByType(MediaController.VIDEO_MIME_TYPE); } MediaFormat outputFormat = MediaFormat.createVideoFormat(MediaController.VIDEO_MIME_TYPE, width, height); outputFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface); outputFormat.setInteger("max-bitrate", bitrate); outputFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitrate); outputFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 30); outputFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1); encoder.configure(outputFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); int encoderBitrate = (int) (encoder.getOutputFormat().getInteger(MediaFormat.KEY_BIT_RATE)); cachedEncoderBitrates.put(cacheKey, encoderBitrate); encoder.release(); return encoderBitrate; } catch (Exception e) { return bitrate; } } private static int getVideoBitrateWithFactor(float f) { return (int) (f * 2000f * 1000f * 1.13f); } public interface VideoConvertorListener { boolean checkConversionCanceled(); void didWriteData(long availableSize, float progress); } public static class PlaylistGlobalSearchParams { final String query; final FiltersView.MediaFilterData filter; final long dialogId; public long topicId; final long minDate; final long maxDate; public int totalCount; public boolean endReached; public int nextSearchRate; public int folderId; public ReactionsLayoutInBubble.VisibleReaction reaction; public PlaylistGlobalSearchParams(String query, long dialogId, long minDate, long maxDate, FiltersView.MediaFilterData filter) { this.filter = filter; this.query = query; this.dialogId = dialogId; this.minDate = minDate; this.maxDate = maxDate; } } public boolean currentPlaylistIsGlobalSearch() { return playlistGlobalSearchParams != null; } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/messenger/MediaController.java
41,668
package org.opencv.samples.recorder; import org.opencv.android.CameraActivity; import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame; import org.opencv.android.OpenCVLoader; import org.opencv.android.Utils; import org.opencv.core.Mat; import org.opencv.core.Size; import org.opencv.imgproc.Imgproc; import org.opencv.videoio.VideoCapture; import org.opencv.videoio.VideoWriter; import org.opencv.android.CameraBridgeViewBase; import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2; import org.opencv.videoio.Videoio; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.MenuItem; import android.view.SurfaceView; import android.view.WindowManager; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.util.Collections; import java.util.List; public class RecorderActivity extends CameraActivity implements CvCameraViewListener2, View.OnClickListener { private static final String TAG = "OCVSample::Activity"; private static final String FILENAME_MP4 = "sample_video1.mp4"; private static final String FILENAME_AVI = "sample_video1.avi"; private static final int STATUS_FINISHED_PLAYBACK = 0; private static final int STATUS_PREVIEW = 1; private static final int STATUS_RECORDING = 2; private static final int STATUS_PLAYING = 3; private static final int STATUS_ERROR = 4; private String mVideoFilename; private boolean mUseBuiltInMJPG = false; private int mStatus = STATUS_FINISHED_PLAYBACK; private int mFPS = 30; private int mWidth = 0, mHeight = 0; private CameraBridgeViewBase mOpenCvCameraView; private ImageView mImageView; private Button mTriggerButton; private TextView mStatusTextView; Runnable mPlayerThread; private VideoWriter mVideoWriter = null; private VideoCapture mVideoCapture = null; private Mat mVideoFrame; private Mat mRenderFrame; public RecorderActivity() { Log.i(TAG, "Instantiated new " + this.getClass()); } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { Log.i(TAG, "called onCreate"); super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.recorder_surface_view); mStatusTextView = (TextView) findViewById(R.id.textview1); mStatusTextView.bringToFront(); if (OpenCVLoader.initLocal()) { Log.i(TAG, "OpenCV loaded successfully"); } else { Log.e(TAG, "OpenCV initialization failed!"); mStatus = STATUS_ERROR; mStatusTextView.setText("Error: Can't initialize OpenCV"); return; } mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.recorder_activity_java_surface_view); mOpenCvCameraView.setVisibility(SurfaceView.GONE); mOpenCvCameraView.setCvCameraViewListener(this); mOpenCvCameraView.disableView(); mImageView = (ImageView) findViewById(R.id.image_view); mTriggerButton = (Button) findViewById(R.id.btn1); mTriggerButton.setOnClickListener(this); mTriggerButton.bringToFront(); if (mUseBuiltInMJPG) mVideoFilename = getFilesDir() + "/" + FILENAME_AVI; else mVideoFilename = getFilesDir() + "/" + FILENAME_MP4; } @Override public void onPause() { Log.d(TAG, "Pause"); super.onPause(); if (mOpenCvCameraView != null) mOpenCvCameraView.disableView(); mImageView.setVisibility(SurfaceView.GONE); if (mVideoWriter != null) { mVideoWriter.release(); mVideoWriter = null; } if (mVideoCapture != null) { mVideoCapture.release(); mVideoCapture = null; } mStatus = STATUS_FINISHED_PLAYBACK; mStatusTextView.setText("Status: Finished playback"); mTriggerButton.setText("Start Camera"); mVideoFrame.release(); mRenderFrame.release(); } @Override public void onResume() { Log.d(TAG, "onResume"); super.onResume(); mVideoFrame = new Mat(); mRenderFrame = new Mat(); changeStatus(); } @Override protected List<? extends CameraBridgeViewBase> getCameraViewList() { return Collections.singletonList(mOpenCvCameraView); } public void onDestroy() { Log.d(TAG, "called onDestroy"); super.onDestroy(); if (mOpenCvCameraView != null) mOpenCvCameraView.disableView(); if (mVideoWriter != null) mVideoWriter.release(); if (mVideoCapture != null) mVideoCapture.release(); } public void onCameraViewStarted(int width, int height) { Log.d(TAG, "Camera view started " + String.valueOf(width) + "x" + String.valueOf(height)); mWidth = width; mHeight = height; } public void onCameraViewStopped() { Log.d(TAG, "Camera view stopped"); } public Mat onCameraFrame(CvCameraViewFrame inputFrame) { Log.d(TAG, "Camera frame arrived"); Mat rgbMat = inputFrame.rgba(); Log.d(TAG, "Size: " + rgbMat.width() + "x" + rgbMat.height()); if (mVideoWriter != null && mVideoWriter.isOpened()) { Imgproc.cvtColor(rgbMat, mVideoFrame, Imgproc.COLOR_RGBA2BGR); mVideoWriter.write(mVideoFrame); } return rgbMat; } @Override public void onClick(View view) { Log.i(TAG,"onClick event"); changeStatus(); } public void changeStatus() { switch(mStatus) { case STATUS_ERROR: Toast.makeText(this, "Error", Toast.LENGTH_LONG).show(); break; case STATUS_FINISHED_PLAYBACK: if (!startPreview()) { setErrorStatus(); break; } mStatus = STATUS_PREVIEW; mStatusTextView.setText("Status: Camera preview"); mTriggerButton.setText("Start recording"); break; case STATUS_PREVIEW: if (!startRecording()) { setErrorStatus(); break; } mStatus = STATUS_RECORDING; mStatusTextView.setText("Status: recording video"); mTriggerButton.setText(" Stop and play video"); break; case STATUS_RECORDING: if (!stopRecording()) { setErrorStatus(); break; } if (!startPlayback()) { setErrorStatus(); break; } mStatus = STATUS_PLAYING; mStatusTextView.setText("Status: Playing video"); mTriggerButton.setText("Stop playback"); break; case STATUS_PLAYING: if (!stopPlayback()) { setErrorStatus(); break; } mStatus = STATUS_FINISHED_PLAYBACK; mStatusTextView.setText("Status: Finished playback"); mTriggerButton.setText("Start Camera"); break; } } public void setErrorStatus() { mStatus = STATUS_ERROR; mStatusTextView.setText("Status: Error"); } public boolean startPreview() { mOpenCvCameraView.enableView(); mOpenCvCameraView.setVisibility(View.VISIBLE); return true; } public boolean startRecording() { Log.i(TAG,"Starting recording"); File file = new File(mVideoFilename); file.delete(); mVideoWriter = new VideoWriter(); if (!mUseBuiltInMJPG) { mVideoWriter.open(mVideoFilename, Videoio.CAP_ANDROID, VideoWriter.fourcc('H', '2', '6', '4'), mFPS, new Size(mWidth, mHeight)); if (!mVideoWriter.isOpened()) { Log.i(TAG,"Can't record H264. Switching to MJPG"); mUseBuiltInMJPG = true; mVideoFilename = getFilesDir() + "/" + FILENAME_AVI; } } if (mUseBuiltInMJPG) { mVideoWriter.open(mVideoFilename, VideoWriter.fourcc('M', 'J', 'P', 'G'), mFPS, new Size(mWidth, mHeight)); } Log.d(TAG, "Size: " + String.valueOf(mWidth) + "x" + String.valueOf(mHeight)); Log.d(TAG, "File: " + mVideoFilename); if (mVideoWriter.isOpened()) { Toast.makeText(this, "Record started to file " + mVideoFilename, Toast.LENGTH_LONG).show(); return true; } else { Toast.makeText(this, "Failed to start a record", Toast.LENGTH_LONG).show(); return false; } } public boolean stopRecording() { Log.i(TAG, "Finishing recording"); mOpenCvCameraView.disableView(); mOpenCvCameraView.setVisibility(SurfaceView.GONE); mVideoWriter.release(); mVideoWriter = null; return true; } public boolean startPlayback() { mImageView.setVisibility(SurfaceView.VISIBLE); if (!mUseBuiltInMJPG){ mVideoCapture = new VideoCapture(mVideoFilename, Videoio.CAP_ANDROID); } else { mVideoCapture = new VideoCapture(mVideoFilename, Videoio.CAP_OPENCV_MJPEG); } if (!mVideoCapture.isOpened()) { Log.e(TAG, "Can't open video"); Toast.makeText(this, "Can't open file " + mVideoFilename, Toast.LENGTH_SHORT).show(); return false; } Toast.makeText(this, "Starting playback from file " + mVideoFilename, Toast.LENGTH_SHORT).show(); mPlayerThread = new Runnable() { @Override public void run() { if (mVideoCapture == null || !mVideoCapture.isOpened()) { return; } mVideoCapture.read(mVideoFrame); if (mVideoFrame.empty()) { if (mStatus == STATUS_PLAYING) { changeStatus(); } return; } // VideoCapture with CAP_ANDROID generates RGB frames instead of BGR // https://github.com/opencv/opencv/issues/24687 Imgproc.cvtColor(mVideoFrame, mRenderFrame, mUseBuiltInMJPG ? Imgproc.COLOR_BGR2RGBA: Imgproc.COLOR_RGB2RGBA); Bitmap bmp = Bitmap.createBitmap(mRenderFrame.cols(), mRenderFrame.rows(), Bitmap.Config.ARGB_8888); Utils.matToBitmap(mRenderFrame, bmp); mImageView.setImageBitmap(bmp); Handler h = new Handler(); h.postDelayed(this, 33); } }; mPlayerThread.run(); return true; } public boolean stopPlayback() { mVideoCapture.release(); mVideoCapture = null; mImageView.setVisibility(SurfaceView.GONE); return true; } }
opencv/opencv
samples/android/video-recorder/src/org/opencv/samples/recorder/RecorderActivity.java
41,669
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.messenger; import android.app.Service; import android.content.Intent; import android.os.IBinder; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; public class VideoEncodingService extends Service implements NotificationCenter.NotificationCenterDelegate { private NotificationCompat.Builder builder; private MediaController.VideoConvertMessage currentMessage; private static VideoEncodingService instance; int currentAccount; String currentPath; public VideoEncodingService() { super(); } public static void start(boolean cancelled) { if (instance == null) { try { Intent intent = new Intent(ApplicationLoader.applicationContext, VideoEncodingService.class); ApplicationLoader.applicationContext.startService(intent); } catch (Exception e) { FileLog.e(e); } } else if (cancelled) { MediaController.VideoConvertMessage messageInController = MediaController.getInstance().getCurrentForegroundConverMessage(); if (instance.currentMessage != messageInController) { if (messageInController != null) { instance.setCurrentMessage(messageInController); } else { instance.stopSelf(); } } } } public static void stop() { if (instance != null) { instance.stopSelf(); } } public IBinder onBind(Intent arg2) { return null; } public void onDestroy() { super.onDestroy(); instance = null; try { stopForeground(true); } catch (Throwable ignore) { } NotificationManagerCompat.from(ApplicationLoader.applicationContext).cancel(4); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileUploadProgressChanged); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileUploadFailed); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileUploaded); currentMessage = null; if (BuildVars.LOGS_ENABLED) { FileLog.d("VideoEncodingService: destroy video service"); } } @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.fileUploadProgressChanged) { String fileName = (String) args[0]; if (account == currentAccount && currentPath != null && currentPath.equals(fileName)) { Long loadedSize = (Long) args[1]; Long totalSize = (Long) args[2]; float progress = Math.min(1f, loadedSize / (float) totalSize); Boolean enc = (Boolean) args[3]; int currentProgress = (int) (progress * 100); builder.setProgress(100, currentProgress, currentProgress == 0); updateNotification(); } } else if (id == NotificationCenter.fileUploaded || id == NotificationCenter.fileUploadFailed) { String fileName = (String) args[0]; if (account == currentAccount && currentPath != null && currentPath.equals(fileName)) { AndroidUtilities.runOnUIThread(() -> { MediaController.VideoConvertMessage message = MediaController.getInstance().getCurrentForegroundConverMessage(); if (message != null) { setCurrentMessage(message); } else { stopSelf(); } }); } } } private void updateNotification() { try { MediaController.VideoConvertMessage message = MediaController.getInstance().getCurrentForegroundConverMessage(); if (message == null) { return; } NotificationManagerCompat.from(ApplicationLoader.applicationContext).notify(4, builder.build()); } catch (Throwable e) { FileLog.e(e); } } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (isRunning()) { return Service.START_NOT_STICKY; } MediaController.VideoConvertMessage videoConvertMessage = MediaController.getInstance().getCurrentForegroundConverMessage(); if (videoConvertMessage == null) { return Service.START_NOT_STICKY; } instance = this; if (builder == null) { NotificationsController.checkOtherNotificationsChannel(); builder = new NotificationCompat.Builder(ApplicationLoader.applicationContext, NotificationsController.OTHER_NOTIFICATIONS_CHANNEL); builder.setSmallIcon(android.R.drawable.stat_sys_upload); builder.setWhen(System.currentTimeMillis()); builder.setChannelId(NotificationsController.OTHER_NOTIFICATIONS_CHANNEL); builder.setContentTitle(LocaleController.getString("AppName", R.string.AppName)); } setCurrentMessage(videoConvertMessage); try { startForeground(4, builder.build()); } catch (Throwable e) { //ignore ForegroundServiceStartNotAllowedException FileLog.e(e); } AndroidUtilities.runOnUIThread(this::updateNotification); return Service.START_NOT_STICKY; } private void updateBuilderForMessage(MediaController.VideoConvertMessage videoConvertMessage) { if (videoConvertMessage == null) { return; } boolean isGif = videoConvertMessage.messageObject != null && MessageObject.isGifMessage(videoConvertMessage.messageObject.messageOwner); if (isGif) { builder.setTicker(LocaleController.getString("SendingGif", R.string.SendingGif)); builder.setContentText(LocaleController.getString("SendingGif", R.string.SendingGif)); } else { builder.setTicker(LocaleController.getString("SendingVideo", R.string.SendingVideo)); builder.setContentText(LocaleController.getString("SendingVideo", R.string.SendingVideo)); } int currentProgress = 0; builder.setProgress(100, currentProgress, true); } private void setCurrentMessage(MediaController.VideoConvertMessage message) { if (currentMessage == message) { return; } if (currentMessage != null) { NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileUploadProgressChanged); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileUploadFailed); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileUploaded); } updateBuilderForMessage(message); currentMessage = message; currentAccount = message.currentAccount; currentPath = message.messageObject.messageOwner.attachPath; NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.fileUploadProgressChanged); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.fileUploadFailed); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.fileUploaded); if (isRunning()) { updateNotification(); } } public static boolean isRunning() { return instance != null; } }
Telegram-FOSS-Team/Telegram-FOSS
TMessagesProj/src/main/java/org/telegram/messenger/VideoEncodingService.java
41,670
404: Not Found
chenyong2github/UnrealEngine
Engine/Build/Android/Java/src/com/epicgames/unreal/VideoDecoder.java
41,671
/* * Copyright 2017 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ package org.webrtc; import android.annotation.TargetApi; import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaFormat; import android.opengl.GLES20; import android.os.Bundle; import androidx.annotation.Nullable; import android.view.Surface; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Map; import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; import org.webrtc.ThreadUtils.ThreadChecker; /** * Android hardware video encoder. * * @note This class is only supported on Android Kitkat and above. */ @TargetApi(19) @SuppressWarnings("deprecation") // Cannot support API level 19 without using deprecated methods. class HardwareVideoEncoder implements VideoEncoder { private static final String TAG = "HardwareVideoEncoder"; // Bitrate modes - should be in sync with OMX_VIDEO_CONTROLRATETYPE defined // in OMX_Video.h private static final int VIDEO_ControlRateConstant = 2; // Key associated with the bitrate control mode value (above). Not present as a MediaFormat // constant until API level 21. private static final String KEY_BITRATE_MODE = "bitrate-mode"; private static final int VIDEO_AVC_PROFILE_HIGH = 8; private static final int VIDEO_AVC_LEVEL_3 = 0x100; private static final int MAX_VIDEO_FRAMERATE = 30; // See MAX_ENCODER_Q_SIZE in androidmediaencoder.cc. private static final int MAX_ENCODER_Q_SIZE = 2; private static final int MEDIA_CODEC_RELEASE_TIMEOUT_MS = 5000; private static final int DEQUEUE_OUTPUT_BUFFER_TIMEOUT_US = 100000; /** * Keeps track of the number of output buffers that have been passed down the pipeline and not yet * released. We need to wait for this to go down to zero before operations invalidating the output * buffers, i.e., stop() and getOutputBuffers(). */ private static class BusyCount { private final Object countLock = new Object(); private int count; public void increment() { synchronized (countLock) { count++; } } // This method may be called on an arbitrary thread. public void decrement() { synchronized (countLock) { count--; if (count == 0) { countLock.notifyAll(); } } } // The increment and waitForZero methods are called on the same thread (deliverEncodedImage, // running on the output thread). Hence, after waitForZero returns, the count will stay zero // until the same thread calls increment. public void waitForZero() { boolean wasInterrupted = false; synchronized (countLock) { while (count > 0) { try { countLock.wait(); } catch (InterruptedException e) { Logging.e(TAG, "Interrupted while waiting on busy count", e); wasInterrupted = true; } } } if (wasInterrupted) { Thread.currentThread().interrupt(); } } } // --- Initialized on construction. private final MediaCodecWrapperFactory mediaCodecWrapperFactory; private final String codecName; private final VideoCodecMimeType codecType; private final Integer surfaceColorFormat; private final Integer yuvColorFormat; private final YuvFormat yuvFormat; private final Map<String, String> params; private final int keyFrameIntervalSec; // Base interval for generating key frames. // Interval at which to force a key frame. Used to reduce color distortions caused by some // Qualcomm video encoders. private final long forcedKeyFrameNs; private final BitrateAdjuster bitrateAdjuster; // EGL context shared with the application. Used to access texture inputs. private final EglBase14.Context sharedContext; // Drawer used to draw input textures onto the codec's input surface. private final GlRectDrawer textureDrawer = new GlRectDrawer(); private final VideoFrameDrawer videoFrameDrawer = new VideoFrameDrawer(); // A queue of EncodedImage.Builders that correspond to frames in the codec. These builders are // pre-populated with all the information that can't be sent through MediaCodec. private final BlockingDeque<EncodedImage.Builder> outputBuilders = new LinkedBlockingDeque<>(); private final ThreadChecker encodeThreadChecker = new ThreadChecker(); private final ThreadChecker outputThreadChecker = new ThreadChecker(); private final BusyCount outputBuffersBusyCount = new BusyCount(); // --- Set on initialize and immutable until release. private Callback callback; private boolean automaticResizeOn; // --- Valid and immutable while an encoding session is running. @Nullable private MediaCodecWrapper codec; @Nullable private ByteBuffer[] outputBuffers; // Thread that delivers encoded frames to the user callback. @Nullable private Thread outputThread; // EGL base wrapping the shared texture context. Holds hooks to both the shared context and the // input surface. Making this base current allows textures from the context to be drawn onto the // surface. @Nullable private EglBase14 textureEglBase; // Input surface for the codec. The encoder will draw input textures onto this surface. @Nullable private Surface textureInputSurface; private int width; private int height; private boolean useSurfaceMode; // --- Only accessed from the encoding thread. // Presentation timestamp of the last requested (or forced) key frame. private long lastKeyFrameNs; // --- Only accessed on the output thread. // Contents of the last observed config frame output by the MediaCodec. Used by H.264. @Nullable private ByteBuffer configBuffer; private int adjustedBitrate; // Whether the encoder is running. Volatile so that the output thread can watch this value and // exit when the encoder stops. private volatile boolean running; // Any exception thrown during shutdown. The output thread releases the MediaCodec and uses this // value to send exceptions thrown during release back to the encoder thread. @Nullable private volatile Exception shutdownException; /** * Creates a new HardwareVideoEncoder with the given codecName, codecType, colorFormat, key frame * intervals, and bitrateAdjuster. * * @param codecName the hardware codec implementation to use * @param codecType the type of the given video codec (eg. VP8, VP9, or H264) * @param surfaceColorFormat color format for surface mode or null if not available * @param yuvColorFormat color format for bytebuffer mode * @param keyFrameIntervalSec interval in seconds between key frames; used to initialize the codec * @param forceKeyFrameIntervalMs interval at which to force a key frame if one is not requested; * used to reduce distortion caused by some codec implementations * @param bitrateAdjuster algorithm used to correct codec implementations that do not produce the * desired bitrates * @throws IllegalArgumentException if colorFormat is unsupported */ public HardwareVideoEncoder(MediaCodecWrapperFactory mediaCodecWrapperFactory, String codecName, VideoCodecMimeType codecType, Integer surfaceColorFormat, Integer yuvColorFormat, Map<String, String> params, int keyFrameIntervalSec, int forceKeyFrameIntervalMs, BitrateAdjuster bitrateAdjuster, EglBase14.Context sharedContext) { this.mediaCodecWrapperFactory = mediaCodecWrapperFactory; this.codecName = codecName; this.codecType = codecType; this.surfaceColorFormat = surfaceColorFormat; this.yuvColorFormat = yuvColorFormat; this.yuvFormat = YuvFormat.valueOf(yuvColorFormat); this.params = params; this.keyFrameIntervalSec = keyFrameIntervalSec; this.forcedKeyFrameNs = TimeUnit.MILLISECONDS.toNanos(forceKeyFrameIntervalMs); this.bitrateAdjuster = bitrateAdjuster; this.sharedContext = sharedContext; // Allow construction on a different thread. encodeThreadChecker.detachThread(); } @Override public VideoCodecStatus initEncode(Settings settings, Callback callback) { encodeThreadChecker.checkIsOnValidThread(); this.callback = callback; automaticResizeOn = settings.automaticResizeOn; this.width = settings.width; this.height = settings.height; useSurfaceMode = canUseSurface(); if (settings.startBitrate != 0 && settings.maxFramerate != 0) { bitrateAdjuster.setTargets(settings.startBitrate * 1000, settings.maxFramerate); } adjustedBitrate = bitrateAdjuster.getAdjustedBitrateBps(); Logging.d(TAG, "initEncode: " + width + " x " + height + ". @ " + settings.startBitrate + "kbps. Fps: " + settings.maxFramerate + " Use surface mode: " + useSurfaceMode); return initEncodeInternal(); } private VideoCodecStatus initEncodeInternal() { encodeThreadChecker.checkIsOnValidThread(); lastKeyFrameNs = -1; try { codec = mediaCodecWrapperFactory.createByCodecName(codecName); } catch (IOException | IllegalArgumentException e) { Logging.e(TAG, "Cannot create media encoder " + codecName); return VideoCodecStatus.FALLBACK_SOFTWARE; } final int colorFormat = useSurfaceMode ? surfaceColorFormat : yuvColorFormat; try { MediaFormat format = MediaFormat.createVideoFormat(codecType.mimeType(), width, height); format.setInteger(MediaFormat.KEY_BIT_RATE, adjustedBitrate); format.setInteger(KEY_BITRATE_MODE, VIDEO_ControlRateConstant); format.setInteger(MediaFormat.KEY_COLOR_FORMAT, colorFormat); format.setInteger(MediaFormat.KEY_FRAME_RATE, bitrateAdjuster.getCodecConfigFramerate()); format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, keyFrameIntervalSec); if (codecType == VideoCodecMimeType.H264) { String profileLevelId = params.get(VideoCodecInfo.H264_FMTP_PROFILE_LEVEL_ID); if (profileLevelId == null) { profileLevelId = VideoCodecInfo.H264_CONSTRAINED_BASELINE_3_1; } switch (profileLevelId) { case VideoCodecInfo.H264_CONSTRAINED_HIGH_3_1: format.setInteger("profile", VIDEO_AVC_PROFILE_HIGH); format.setInteger("level", VIDEO_AVC_LEVEL_3); break; case VideoCodecInfo.H264_CONSTRAINED_BASELINE_3_1: break; default: Logging.w(TAG, "Unknown profile level id: " + profileLevelId); } } Logging.d(TAG, "Format: " + format); codec.configure( format, null /* surface */, null /* crypto */, MediaCodec.CONFIGURE_FLAG_ENCODE); if (useSurfaceMode) { textureEglBase = EglBase.createEgl14(sharedContext, EglBase.CONFIG_RECORDABLE); textureInputSurface = codec.createInputSurface(); textureEglBase.createSurface(textureInputSurface); textureEglBase.makeCurrent(); } codec.start(); outputBuffers = codec.getOutputBuffers(); } catch (IllegalStateException e) { Logging.e(TAG, "initEncodeInternal failed", e); release(); return VideoCodecStatus.FALLBACK_SOFTWARE; } running = true; outputThreadChecker.detachThread(); outputThread = createOutputThread(); outputThread.start(); return VideoCodecStatus.OK; } @Override public VideoCodecStatus release() { encodeThreadChecker.checkIsOnValidThread(); final VideoCodecStatus returnValue; if (outputThread == null) { returnValue = VideoCodecStatus.OK; } else { // The outputThread actually stops and releases the codec once running is false. running = false; if (!ThreadUtils.joinUninterruptibly(outputThread, MEDIA_CODEC_RELEASE_TIMEOUT_MS)) { Logging.e(TAG, "Media encoder release timeout"); returnValue = VideoCodecStatus.TIMEOUT; } else if (shutdownException != null) { // Log the exception and turn it into an error. Logging.e(TAG, "Media encoder release exception", shutdownException); returnValue = VideoCodecStatus.ERROR; } else { returnValue = VideoCodecStatus.OK; } } textureDrawer.release(); videoFrameDrawer.release(); if (textureEglBase != null) { textureEglBase.release(); textureEglBase = null; } if (textureInputSurface != null) { textureInputSurface.release(); textureInputSurface = null; } outputBuilders.clear(); codec = null; outputBuffers = null; outputThread = null; // Allow changing thread after release. encodeThreadChecker.detachThread(); return returnValue; } @Override public VideoCodecStatus encode(VideoFrame videoFrame, EncodeInfo encodeInfo) { encodeThreadChecker.checkIsOnValidThread(); if (codec == null) { return VideoCodecStatus.UNINITIALIZED; } final VideoFrame.Buffer videoFrameBuffer = videoFrame.getBuffer(); final boolean isTextureBuffer = videoFrameBuffer instanceof VideoFrame.TextureBuffer; //TODO back to texture buffer // If input resolution changed, restart the codec with the new resolution. final int frameWidth = videoFrame.getBuffer().getWidth(); final int frameHeight = videoFrame.getBuffer().getHeight(); final boolean shouldUseSurfaceMode = canUseSurface() && isTextureBuffer; if (frameWidth != width || frameHeight != height || shouldUseSurfaceMode != useSurfaceMode) { VideoCodecStatus status = resetCodec(frameWidth, frameHeight, shouldUseSurfaceMode); if (status != VideoCodecStatus.OK) { return status; } } if (outputBuilders.size() > MAX_ENCODER_Q_SIZE) { // Too many frames in the encoder. Drop this frame. Logging.e(TAG, "Dropped frame, encoder queue full"); return VideoCodecStatus.NO_OUTPUT; // See webrtc bug 2887. } boolean requestedKeyFrame = false; for (EncodedImage.FrameType frameType : encodeInfo.frameTypes) { if (frameType == EncodedImage.FrameType.VideoFrameKey) { requestedKeyFrame = true; } } if (requestedKeyFrame || shouldForceKeyFrame(videoFrame.getTimestampNs())) { requestKeyFrame(videoFrame.getTimestampNs()); } // Number of bytes in the video buffer. Y channel is sampled at one byte per pixel; U and V are // subsampled at one byte per four pixels. int bufferSize = videoFrameBuffer.getHeight() * videoFrameBuffer.getWidth() * 3 / 2; EncodedImage.Builder builder = EncodedImage.builder() .setCaptureTimeNs(videoFrame.getTimestampNs()) .setEncodedWidth(videoFrame.getBuffer().getWidth()) .setEncodedHeight(videoFrame.getBuffer().getHeight()) .setRotation(videoFrame.getRotation()); outputBuilders.offer(builder); final VideoCodecStatus returnValue; if (useSurfaceMode) { returnValue = encodeTextureBuffer(videoFrame); } else { returnValue = encodeByteBuffer(videoFrame, videoFrameBuffer, bufferSize); } // Check if the queue was successful. if (returnValue != VideoCodecStatus.OK) { // Keep the output builders in sync with buffers in the codec. outputBuilders.pollLast(); } return returnValue; } private VideoCodecStatus encodeTextureBuffer(VideoFrame videoFrame) { encodeThreadChecker.checkIsOnValidThread(); try { // TODO(perkj): glClear() shouldn't be necessary since every pixel is covered anyway, // but it's a workaround for bug webrtc:5147. GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); // It is not necessary to release this frame because it doesn't own the buffer. VideoFrame derotatedFrame = new VideoFrame(videoFrame.getBuffer(), 0 /* rotation */, videoFrame.getTimestampNs()); videoFrameDrawer.drawFrame(derotatedFrame, textureDrawer, null /* additionalRenderMatrix */); textureEglBase.swapBuffers(videoFrame.getTimestampNs(), false); } catch (RuntimeException e) { Logging.e(TAG, "encodeTexture failed", e); return VideoCodecStatus.ERROR; } return VideoCodecStatus.OK; } private VideoCodecStatus encodeByteBuffer( VideoFrame videoFrame, VideoFrame.Buffer videoFrameBuffer, int bufferSize) { encodeThreadChecker.checkIsOnValidThread(); // Frame timestamp rounded to the nearest microsecond. long presentationTimestampUs = (videoFrame.getTimestampNs() + 500) / 1000; // No timeout. Don't block for an input buffer, drop frames if the encoder falls behind. int index; try { index = codec.dequeueInputBuffer(0 /* timeout */); } catch (IllegalStateException e) { Logging.e(TAG, "dequeueInputBuffer failed", e); return VideoCodecStatus.ERROR; } if (index == -1) { // Encoder is falling behind. No input buffers available. Drop the frame. Logging.d(TAG, "Dropped frame, no input buffers available"); return VideoCodecStatus.NO_OUTPUT; // See webrtc bug 2887. } ByteBuffer buffer; try { buffer = codec.getInputBuffers()[index]; } catch (IllegalStateException e) { Logging.e(TAG, "getInputBuffers failed", e); return VideoCodecStatus.ERROR; } fillInputBuffer(buffer, videoFrameBuffer); try { codec.queueInputBuffer( index, 0 /* offset */, bufferSize, presentationTimestampUs, 0 /* flags */); } catch (IllegalStateException e) { Logging.e(TAG, "queueInputBuffer failed", e); // IllegalStateException thrown when the codec is in the wrong state. return VideoCodecStatus.ERROR; } return VideoCodecStatus.OK; } @Override public VideoCodecStatus setRateAllocation(BitrateAllocation bitrateAllocation, int framerate) { encodeThreadChecker.checkIsOnValidThread(); if (framerate > MAX_VIDEO_FRAMERATE) { framerate = MAX_VIDEO_FRAMERATE; } bitrateAdjuster.setTargets(bitrateAllocation.getSum(), framerate); return VideoCodecStatus.OK; } @Override public ScalingSettings getScalingSettings() { encodeThreadChecker.checkIsOnValidThread(); if (automaticResizeOn) { if (codecType == VideoCodecMimeType.VP8) { final int kLowVp8QpThreshold = 29; final int kHighVp8QpThreshold = 95; return new ScalingSettings(kLowVp8QpThreshold, kHighVp8QpThreshold); } else if (codecType == VideoCodecMimeType.H264) { final int kLowH264QpThreshold = 24; final int kHighH264QpThreshold = 37; return new ScalingSettings(kLowH264QpThreshold, kHighH264QpThreshold); } } return ScalingSettings.OFF; } @Override public String getImplementationName() { return "HWEncoder"; } private VideoCodecStatus resetCodec(int newWidth, int newHeight, boolean newUseSurfaceMode) { encodeThreadChecker.checkIsOnValidThread(); VideoCodecStatus status = release(); if (status != VideoCodecStatus.OK) { return status; } width = newWidth; height = newHeight; useSurfaceMode = newUseSurfaceMode; return initEncodeInternal(); } private boolean shouldForceKeyFrame(long presentationTimestampNs) { encodeThreadChecker.checkIsOnValidThread(); return forcedKeyFrameNs > 0 && presentationTimestampNs > lastKeyFrameNs + forcedKeyFrameNs; } private void requestKeyFrame(long presentationTimestampNs) { encodeThreadChecker.checkIsOnValidThread(); // Ideally MediaCodec would honor BUFFER_FLAG_SYNC_FRAME so we could // indicate this in queueInputBuffer() below and guarantee _this_ frame // be encoded as a key frame, but sadly that flag is ignored. Instead, // we request a key frame "soon". try { Bundle b = new Bundle(); b.putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0); codec.setParameters(b); } catch (IllegalStateException e) { Logging.e(TAG, "requestKeyFrame failed", e); return; } lastKeyFrameNs = presentationTimestampNs; } private Thread createOutputThread() { return new Thread() { @Override public void run() { while (running) { deliverEncodedImage(); } releaseCodecOnOutputThread(); } }; } // Visible for testing. protected void deliverEncodedImage() { outputThreadChecker.checkIsOnValidThread(); try { MediaCodec.BufferInfo info = new MediaCodec.BufferInfo(); int index = codec.dequeueOutputBuffer(info, DEQUEUE_OUTPUT_BUFFER_TIMEOUT_US); if (index < 0) { if (index == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) { outputBuffersBusyCount.waitForZero(); outputBuffers = codec.getOutputBuffers(); } return; } ByteBuffer codecOutputBuffer = outputBuffers[index]; codecOutputBuffer.position(info.offset); codecOutputBuffer.limit(info.offset + info.size); if ((info.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) { Logging.d(TAG, "Config frame generated. Offset: " + info.offset + ". Size: " + info.size); configBuffer = ByteBuffer.allocateDirect(info.size); configBuffer.put(codecOutputBuffer); } else { bitrateAdjuster.reportEncodedFrame(info.size); if (adjustedBitrate != bitrateAdjuster.getAdjustedBitrateBps()) { updateBitrate(); } final boolean isKeyFrame = (info.flags & MediaCodec.BUFFER_FLAG_SYNC_FRAME) != 0; if (isKeyFrame) { Logging.d(TAG, "Sync frame generated"); } final ByteBuffer frameBuffer; if (isKeyFrame && (codecType == VideoCodecMimeType.H264 || codecType == VideoCodecMimeType.H265)) { if (configBuffer == null) { configBuffer = ByteBuffer.allocateDirect(info.size); } Logging.d(TAG, "Prepending config frame of size " + configBuffer.capacity() + " to output buffer with offset " + info.offset + ", size " + info.size); // For H.264 key frame prepend SPS and PPS NALs at the start. frameBuffer = ByteBuffer.allocateDirect(info.size + configBuffer.capacity()); configBuffer.rewind(); frameBuffer.put(configBuffer); frameBuffer.put(codecOutputBuffer); frameBuffer.rewind(); } else { frameBuffer = codecOutputBuffer.slice(); } final EncodedImage.FrameType frameType = isKeyFrame ? EncodedImage.FrameType.VideoFrameKey : EncodedImage.FrameType.VideoFrameDelta; outputBuffersBusyCount.increment(); EncodedImage.Builder builder = outputBuilders.poll(); EncodedImage encodedImage = builder .setBuffer(frameBuffer, () -> { // This callback should not throw any exceptions since // it may be called on an arbitrary thread. // Check bug webrtc:11230 for more details. try { codec.releaseOutputBuffer(index, false); } catch (Exception e) { Logging.e(TAG, "releaseOutputBuffer failed", e); } outputBuffersBusyCount.decrement(); }) .setFrameType(frameType) .createEncodedImage(); // TODO(mellem): Set codec-specific info. callback.onEncodedFrame(encodedImage, new CodecSpecificInfo()); // Note that the callback may have retained the image. encodedImage.release(); } } catch (IllegalStateException e) { Logging.e(TAG, "deliverOutput failed", e); } } private void releaseCodecOnOutputThread() { outputThreadChecker.checkIsOnValidThread(); Logging.d(TAG, "Releasing MediaCodec on output thread"); outputBuffersBusyCount.waitForZero(); try { codec.stop(); } catch (Exception e) { Logging.e(TAG, "Media encoder stop failed", e); } try { codec.release(); } catch (Exception e) { Logging.e(TAG, "Media encoder release failed", e); // Propagate exceptions caught during release back to the main thread. shutdownException = e; } configBuffer = null; Logging.d(TAG, "Release on output thread done"); } private VideoCodecStatus updateBitrate() { outputThreadChecker.checkIsOnValidThread(); adjustedBitrate = bitrateAdjuster.getAdjustedBitrateBps(); try { Bundle params = new Bundle(); params.putInt(MediaCodec.PARAMETER_KEY_VIDEO_BITRATE, adjustedBitrate); codec.setParameters(params); return VideoCodecStatus.OK; } catch (IllegalStateException e) { Logging.e(TAG, "updateBitrate failed", e); return VideoCodecStatus.ERROR; } } private boolean canUseSurface() { return sharedContext != null && surfaceColorFormat != null; } // Visible for testing. protected void fillInputBuffer(ByteBuffer buffer, VideoFrame.Buffer videoFrameBuffer) { yuvFormat.fillBuffer(buffer, videoFrameBuffer); } /** * Enumeration of supported YUV color formats used for MediaCodec's input. */ private enum YuvFormat { I420 { @Override void fillBuffer(ByteBuffer dstBuffer, VideoFrame.Buffer srcBuffer) { VideoFrame.I420Buffer i420 = srcBuffer.toI420(); YuvHelper.I420Copy(i420.getDataY(), i420.getStrideY(), i420.getDataU(), i420.getStrideU(), i420.getDataV(), i420.getStrideV(), dstBuffer, i420.getWidth(), i420.getHeight()); i420.release(); } }, NV12 { @Override void fillBuffer(ByteBuffer dstBuffer, VideoFrame.Buffer srcBuffer) { VideoFrame.I420Buffer i420 = srcBuffer.toI420(); YuvHelper.I420ToNV12(i420.getDataY(), i420.getStrideY(), i420.getDataU(), i420.getStrideU(), i420.getDataV(), i420.getStrideV(), dstBuffer, i420.getWidth(), i420.getHeight()); i420.release(); } }; abstract void fillBuffer(ByteBuffer dstBuffer, VideoFrame.Buffer srcBuffer); static YuvFormat valueOf(int colorFormat) { switch (colorFormat) { case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar: return I420; case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar: case MediaCodecInfo.CodecCapabilities.COLOR_QCOM_FormatYUV420SemiPlanar: case MediaCodecUtils.COLOR_QCOM_FORMATYUV420PackedSemiPlanar32m: return NV12; default: throw new IllegalArgumentException("Unsupported colorFormat: " + colorFormat); } } } }
NekoX-Dev/NekoX
TMessagesProj/src/main/java/org/webrtc/HardwareVideoEncoder.java
41,672
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.messenger; import android.app.Service; import android.content.Intent; import android.os.IBinder; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import com.google.android.exoplayer2.util.Log; public class VideoEncodingService extends Service implements NotificationCenter.NotificationCenterDelegate { private NotificationCompat.Builder builder; private MediaController.VideoConvertMessage currentMessage; private static VideoEncodingService instance; int currentAccount; String currentPath; public VideoEncodingService() { super(); } public static void start(boolean cancelled) { if (instance == null) { Intent intent = new Intent(ApplicationLoader.applicationContext, VideoEncodingService.class); ApplicationLoader.applicationContext.startService(intent); } else if (cancelled) { MediaController.VideoConvertMessage messageInController = MediaController.getInstance().getCurrentForegroundConverMessage(); if (instance.currentMessage != messageInController) { if (messageInController != null) { instance.setCurrentMessage(messageInController); } else { instance.stopSelf(); } } } } public static void stop() { if (instance != null) { instance.stopSelf(); } } public IBinder onBind(Intent arg2) { return null; } public void onDestroy() { super.onDestroy(); instance = null; try { stopForeground(true); } catch (Throwable ignore) { } NotificationManagerCompat.from(ApplicationLoader.applicationContext).cancel(4); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileUploadProgressChanged); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileUploadFailed); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileUploaded); currentMessage = null; if (BuildVars.LOGS_ENABLED) { FileLog.d("VideoEncodingService: destroy video service"); } } @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.fileUploadProgressChanged) { String fileName = (String) args[0]; if (account == currentAccount && currentPath != null && currentPath.equals(fileName)) { Long loadedSize = (Long) args[1]; Long totalSize = (Long) args[2]; float progress = Math.min(1f, loadedSize / (float) totalSize); Boolean enc = (Boolean) args[3]; int currentProgress = (int) (progress * 100); builder.setProgress(100, currentProgress, currentProgress == 0); try { NotificationManagerCompat.from(ApplicationLoader.applicationContext).notify(4, builder.build()); } catch (Throwable e) { FileLog.e(e); } } } else if (id == NotificationCenter.fileUploaded || id == NotificationCenter.fileUploadFailed) { String fileName = (String) args[0]; if (account == currentAccount && currentPath != null && currentPath.equals(fileName)) { AndroidUtilities.runOnUIThread(() -> { MediaController.VideoConvertMessage message = MediaController.getInstance().getCurrentForegroundConverMessage(); if (message != null) { setCurrentMessage(message); } else { stopSelf(); } }); } } } public int onStartCommand(Intent intent, int flags, int startId) { if (isRunning()) { return Service.START_NOT_STICKY; } instance = this; MediaController.VideoConvertMessage videoConvertMessage = MediaController.getInstance().getCurrentForegroundConverMessage(); if (builder == null) { NotificationsController.checkOtherNotificationsChannel(); builder = new NotificationCompat.Builder(ApplicationLoader.applicationContext, NotificationsController.OTHER_NOTIFICATIONS_CHANNEL); builder.setSmallIcon(android.R.drawable.stat_sys_upload); builder.setWhen(System.currentTimeMillis()); builder.setChannelId(NotificationsController.OTHER_NOTIFICATIONS_CHANNEL); builder.setContentTitle(LocaleController.getString("AppName", R.string.AppName)); } setCurrentMessage(videoConvertMessage); try { startForeground(4, builder.build()); } catch (Throwable e) { //ignore ForegroundServiceStartNotAllowedException FileLog.e(e); } AndroidUtilities.runOnUIThread(() -> NotificationManagerCompat.from(ApplicationLoader.applicationContext).notify(4, builder.build())); return Service.START_NOT_STICKY; } private void updateBuilderForMessage(MediaController.VideoConvertMessage videoConvertMessage) { if (videoConvertMessage == null) { return; } boolean isGif = videoConvertMessage.messageObject != null && MessageObject.isGifMessage(videoConvertMessage.messageObject.messageOwner); if (isGif) { builder.setTicker(LocaleController.getString("SendingGif", R.string.SendingGif)); builder.setContentText(LocaleController.getString("SendingGif", R.string.SendingGif)); } else { builder.setTicker(LocaleController.getString("SendingVideo", R.string.SendingVideo)); builder.setContentText(LocaleController.getString("SendingVideo", R.string.SendingVideo)); } int currentProgress = 0; builder.setProgress(100, currentProgress, true); } private void setCurrentMessage(MediaController.VideoConvertMessage message) { if (currentMessage == message) { return; } if (currentMessage != null) { NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileUploadProgressChanged); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileUploadFailed); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileUploaded); } updateBuilderForMessage(message); currentMessage = message; currentAccount = message.currentAccount; currentPath = message.messageObject.messageOwner.attachPath; NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.fileUploadProgressChanged); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.fileUploadFailed); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.fileUploaded); if (isRunning()) { NotificationManagerCompat.from(ApplicationLoader.applicationContext).notify(4, builder.build()); } } public static boolean isRunning() { return instance != null; } }
jinbangzhang/Telegram
TMessagesProj/src/main/java/org/telegram/messenger/VideoEncodingService.java
41,673
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.messenger; import android.app.Service; import android.content.Intent; import android.os.IBinder; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import com.google.android.exoplayer2.util.Log; public class VideoEncodingService extends Service implements NotificationCenter.NotificationCenterDelegate { private NotificationCompat.Builder builder; private MediaController.VideoConvertMessage currentMessage; private static VideoEncodingService instance; int currentAccount; String currentPath; public VideoEncodingService() { super(); } public static void start(boolean cancelled) { if (instance == null) { try { Intent intent = new Intent(ApplicationLoader.applicationContext, VideoEncodingService.class); ApplicationLoader.applicationContext.startService(intent); } catch (Exception e) { FileLog.e(e); } } else if (cancelled) { MediaController.VideoConvertMessage messageInController = MediaController.getInstance().getCurrentForegroundConverMessage(); if (instance.currentMessage != messageInController) { if (messageInController != null) { instance.setCurrentMessage(messageInController); } else { instance.stopSelf(); } } } } public static void stop() { if (instance != null) { instance.stopSelf(); } } public IBinder onBind(Intent arg2) { return null; } public void onDestroy() { super.onDestroy(); instance = null; try { stopForeground(true); } catch (Throwable ignore) { } NotificationManagerCompat.from(ApplicationLoader.applicationContext).cancel(4); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileUploadProgressChanged); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileUploadFailed); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileUploaded); currentMessage = null; if (BuildVars.LOGS_ENABLED) { FileLog.d("VideoEncodingService: destroy video service"); } } @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.fileUploadProgressChanged) { String fileName = (String) args[0]; if (account == currentAccount && currentPath != null && currentPath.equals(fileName)) { Long loadedSize = (Long) args[1]; Long totalSize = (Long) args[2]; float progress = Math.min(1f, loadedSize / (float) totalSize); Boolean enc = (Boolean) args[3]; int currentProgress = (int) (progress * 100); builder.setProgress(100, currentProgress, currentProgress == 0); try { NotificationManagerCompat.from(ApplicationLoader.applicationContext).notify(4, builder.build()); } catch (Throwable e) { FileLog.e(e); } } } else if (id == NotificationCenter.fileUploaded || id == NotificationCenter.fileUploadFailed) { String fileName = (String) args[0]; if (account == currentAccount && currentPath != null && currentPath.equals(fileName)) { AndroidUtilities.runOnUIThread(() -> { MediaController.VideoConvertMessage message = MediaController.getInstance().getCurrentForegroundConverMessage(); if (message != null) { setCurrentMessage(message); } else { stopSelf(); } }); } } } public int onStartCommand(Intent intent, int flags, int startId) { if (isRunning()) { return Service.START_NOT_STICKY; } instance = this; MediaController.VideoConvertMessage videoConvertMessage = MediaController.getInstance().getCurrentForegroundConverMessage(); if (builder == null) { NotificationsController.checkOtherNotificationsChannel(); builder = new NotificationCompat.Builder(ApplicationLoader.applicationContext, NotificationsController.OTHER_NOTIFICATIONS_CHANNEL); builder.setSmallIcon(android.R.drawable.stat_sys_upload); builder.setWhen(System.currentTimeMillis()); builder.setChannelId(NotificationsController.OTHER_NOTIFICATIONS_CHANNEL); builder.setContentTitle(LocaleController.getString("AppName", R.string.AppName)); } setCurrentMessage(videoConvertMessage); try { startForeground(4, builder.build()); } catch (Throwable e) { //ignore ForegroundServiceStartNotAllowedException FileLog.e(e); } AndroidUtilities.runOnUIThread(() -> NotificationManagerCompat.from(ApplicationLoader.applicationContext).notify(4, builder.build())); return Service.START_NOT_STICKY; } private void updateBuilderForMessage(MediaController.VideoConvertMessage videoConvertMessage) { if (videoConvertMessage == null) { return; } boolean isGif = videoConvertMessage.messageObject != null && MessageObject.isGifMessage(videoConvertMessage.messageObject.messageOwner); if (isGif) { builder.setTicker(LocaleController.getString("SendingGif", R.string.SendingGif)); builder.setContentText(LocaleController.getString("SendingGif", R.string.SendingGif)); } else { builder.setTicker(LocaleController.getString("SendingVideo", R.string.SendingVideo)); builder.setContentText(LocaleController.getString("SendingVideo", R.string.SendingVideo)); } int currentProgress = 0; builder.setProgress(100, currentProgress, true); } private void setCurrentMessage(MediaController.VideoConvertMessage message) { if (currentMessage == message) { return; } if (currentMessage != null) { NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileUploadProgressChanged); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileUploadFailed); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileUploaded); } updateBuilderForMessage(message); currentMessage = message; currentAccount = message.currentAccount; currentPath = message.messageObject.messageOwner.attachPath; NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.fileUploadProgressChanged); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.fileUploadFailed); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.fileUploaded); if (isRunning()) { NotificationManagerCompat.from(ApplicationLoader.applicationContext).notify(4, builder.build()); } } public static boolean isRunning() { return instance != null; } }
danieldaeschle/Telegram-Safe
TMessagesProj/src/main/java/org/telegram/messenger/VideoEncodingService.java
41,674
package org.telegram.messenger.voip; import android.os.Build; import org.json.JSONException; import org.json.JSONObject; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.BuildVars; import org.telegram.messenger.FileLog; import org.webrtc.ContextUtils; import org.webrtc.VideoSink; import java.util.Arrays; import java.util.List; public final class Instance { public static final List<String> AVAILABLE_VERSIONS = Build.VERSION.SDK_INT >= 18 ? Arrays.asList("4.1.2", "4.0.2", "4.0.1", "4.0.0", "5.0.0", "2.7.7", "2.4.4") : Arrays.asList("2.4.4"); public static final int AUDIO_STATE_MUTED = 0; public static final int AUDIO_STATE_ACTIVE = 1; public static final int VIDEO_STATE_INACTIVE = 0; public static final int VIDEO_STATE_PAUSED = 1; public static final int VIDEO_STATE_ACTIVE = 2; //region Constants public static final int NET_TYPE_UNKNOWN = 0; public static final int NET_TYPE_GPRS = 1; public static final int NET_TYPE_EDGE = 2; public static final int NET_TYPE_3G = 3; public static final int NET_TYPE_HSPA = 4; public static final int NET_TYPE_LTE = 5; public static final int NET_TYPE_WIFI = 6; public static final int NET_TYPE_ETHERNET = 7; public static final int NET_TYPE_OTHER_HIGH_SPEED = 8; public static final int NET_TYPE_OTHER_LOW_SPEED = 9; public static final int NET_TYPE_DIALUP = 10; public static final int NET_TYPE_OTHER_MOBILE = 11; public static final int ENDPOINT_TYPE_INET = 0; public static final int ENDPOINT_TYPE_LAN = 1; public static final int ENDPOINT_TYPE_UDP_RELAY = 2; public static final int ENDPOINT_TYPE_TCP_RELAY = 3; public static final int STATE_WAIT_INIT = 1; public static final int STATE_WAIT_INIT_ACK = 2; public static final int STATE_ESTABLISHED = 3; public static final int STATE_FAILED = 4; public static final int STATE_RECONNECTING = 5; public static final int DATA_SAVING_NEVER = 0; public static final int DATA_SAVING_MOBILE = 1; public static final int DATA_SAVING_ALWAYS = 2; public static final int DATA_SAVING_ROAMING = 3; public static final int PEER_CAP_GROUP_CALLS = 1; // Java-side Errors public static final String ERROR_CONNECTION_SERVICE = "ERROR_CONNECTION_SERVICE"; public static final String ERROR_INSECURE_UPGRADE = "ERROR_INSECURE_UPGRADE"; public static final String ERROR_LOCALIZED = "ERROR_LOCALIZED"; public static final String ERROR_PRIVACY = "ERROR_PRIVACY"; public static final String ERROR_PEER_OUTDATED = "ERROR_PEER_OUTDATED"; // Native-side Errors public static final String ERROR_UNKNOWN = "ERROR_UNKNOWN"; public static final String ERROR_INCOMPATIBLE = "ERROR_INCOMPATIBLE"; public static final String ERROR_TIMEOUT = "ERROR_TIMEOUT"; public static final String ERROR_AUDIO_IO = "ERROR_AUDIO_IO"; //endregion private static ServerConfig globalServerConfig = new ServerConfig(new JSONObject()); private static int bufferSize; private static NativeInstance instance; private Instance() { } public static ServerConfig getGlobalServerConfig() { return globalServerConfig; } public static void setGlobalServerConfig(String serverConfigJson) { try { globalServerConfig = new ServerConfig(new JSONObject(serverConfigJson)); if (instance != null) { instance.setGlobalServerConfig(serverConfigJson); } } catch (JSONException e) { if (BuildVars.LOGS_ENABLED) { FileLog.e("failed to parse tgvoip server config", e); } } } public static void destroyInstance() { instance = null; } public static NativeInstance makeInstance(String version, Config config, String persistentStateFilePath, Endpoint[] endpoints, Proxy proxy, int networkType, EncryptionKey encryptionKey, VideoSink remoteSink, long videoCapturer, NativeInstance.AudioLevelsCallback audioLevelsCallback) { if (!"2.4.4".equals(version)) { ContextUtils.initialize(ApplicationLoader.applicationContext); } instance = NativeInstance.make(version, config, persistentStateFilePath, endpoints, proxy, networkType, encryptionKey, remoteSink, videoCapturer, audioLevelsCallback); setGlobalServerConfig(globalServerConfig.jsonObject.toString()); setBufferSize(bufferSize); return instance; } public static void setBufferSize(int size) { bufferSize = size; if (instance != null) { instance.setBufferSize(size); } } public static int getConnectionMaxLayer() { return 92; } public static String getVersion() { return instance != null ? instance.getVersion() : null; } private static void checkHasDelegate() { if (instance == null) { throw new IllegalStateException("tgvoip version is not set"); } } public interface OnStateUpdatedListener { void onStateUpdated(int state, boolean inTransition); } public interface OnSignalBarsUpdatedListener { void onSignalBarsUpdated(int signalBars); } public interface OnSignalingDataListener { void onSignalingData(byte[] data); } public interface OnRemoteMediaStateUpdatedListener { void onMediaStateUpdated(int audioState, int videoState); } public static final class Config { public final double initializationTimeout; public final double receiveTimeout; public final int dataSaving; public final boolean enableP2p; public final boolean enableAec; public final boolean enableNs; public final boolean enableAgc; public final boolean enableCallUpgrade; public final String logPath; public final String statsLogPath; public final int maxApiLayer; public final boolean enableSm; public Config(double initializationTimeout, double receiveTimeout, int dataSaving, boolean enableP2p, boolean enableAec, boolean enableNs, boolean enableAgc, boolean enableCallUpgrade, boolean enableSm, String logPath, String statsLogPath, int maxApiLayer) { this.initializationTimeout = initializationTimeout; this.receiveTimeout = receiveTimeout; this.dataSaving = dataSaving; this.enableP2p = enableP2p; this.enableAec = enableAec; this.enableNs = enableNs; this.enableAgc = enableAgc; this.enableCallUpgrade = enableCallUpgrade; this.logPath = logPath; this.statsLogPath = statsLogPath; this.maxApiLayer = maxApiLayer; this.enableSm = enableSm; } @Override public String toString() { return "Config{" + "initializationTimeout=" + initializationTimeout + ", receiveTimeout=" + receiveTimeout + ", dataSaving=" + dataSaving + ", enableP2p=" + enableP2p + ", enableAec=" + enableAec + ", enableNs=" + enableNs + ", enableAgc=" + enableAgc + ", enableCallUpgrade=" + enableCallUpgrade + ", logPath='" + logPath + '\'' + ", statsLogPath='" + statsLogPath + '\'' + ", maxApiLayer=" + maxApiLayer + ", enableSm=" + enableSm + '}'; } } public static final class Endpoint { public final boolean isRtc; public final long id; public final String ipv4; public final String ipv6; public final int port; public final int type; public final byte[] peerTag; public final boolean turn; public final boolean stun; public final String username; public final String password; public final boolean tcp; public Endpoint(boolean isRtc, long id, String ipv4, String ipv6, int port, int type, byte[] peerTag, boolean turn, boolean stun, String username, String password, boolean tcp) { this.isRtc = isRtc; this.id = id; this.ipv4 = ipv4; this.ipv6 = ipv6; this.port = port; this.type = type; this.peerTag = peerTag; this.turn = turn; this.stun = stun; this.username = username; this.password = password; this.tcp = tcp; } @Override public String toString() { return "Endpoint{" + "id=" + id + ", ipv4='" + ipv4 + '\'' + ", ipv6='" + ipv6 + '\'' + ", port=" + port + ", type=" + type + ", peerTag=" + Arrays.toString(peerTag) + ", turn=" + turn + ", stun=" + stun + ", username=" + username + ", password=" + password + ", tcp=" + tcp + '}'; } } public static final class Proxy { public final String host; public final int port; public final String login; public final String password; public Proxy(String host, int port, String login, String password) { this.host = host; this.port = port; this.login = login; this.password = password; } @Override public String toString() { return "Proxy{" + "host='" + host + '\'' + ", port=" + port + ", login='" + login + '\'' + ", password='" + password + '\'' + '}'; } } public static final class EncryptionKey { public final byte[] value; public final boolean isOutgoing; public EncryptionKey(byte[] value, boolean isOutgoing) { this.value = value; this.isOutgoing = isOutgoing; } @Override public String toString() { return "EncryptionKey{" + "value=" + Arrays.toString(value) + ", isOutgoing=" + isOutgoing + '}'; } } public static final class FinalState { public final byte[] persistentState; public String debugLog; public final TrafficStats trafficStats; public final boolean isRatingSuggested; public FinalState(byte[] persistentState, String debugLog, TrafficStats trafficStats, boolean isRatingSuggested) { this.persistentState = persistentState; this.debugLog = debugLog; this.trafficStats = trafficStats; this.isRatingSuggested = isRatingSuggested; } @Override public String toString() { return "FinalState{" + "persistentState=" + Arrays.toString(persistentState) + ", debugLog='" + debugLog + '\'' + ", trafficStats=" + trafficStats + ", isRatingSuggested=" + isRatingSuggested + '}'; } } public static final class TrafficStats { public final long bytesSentWifi; public final long bytesReceivedWifi; public final long bytesSentMobile; public final long bytesReceivedMobile; public TrafficStats(long bytesSentWifi, long bytesReceivedWifi, long bytesSentMobile, long bytesReceivedMobile) { this.bytesSentWifi = bytesSentWifi; this.bytesReceivedWifi = bytesReceivedWifi; this.bytesSentMobile = bytesSentMobile; this.bytesReceivedMobile = bytesReceivedMobile; } @Override public String toString() { return "TrafficStats{" + "bytesSentWifi=" + bytesSentWifi + ", bytesReceivedWifi=" + bytesReceivedWifi + ", bytesSentMobile=" + bytesSentMobile + ", bytesReceivedMobile=" + bytesReceivedMobile + '}'; } } public static final class Fingerprint { public final String hash; public final String setup; public final String fingerprint; public Fingerprint(String hash, String setup, String fingerprint) { this.hash = hash; this.setup = setup; this.fingerprint = fingerprint; } @Override public String toString() { return "Fingerprint{" + "hash=" + hash + ", setup=" + setup + ", fingerprint=" + fingerprint + '}'; } } public static final class Candidate { public final String port; public final String protocol; public final String network; public final String generation; public final String id; public final String component; public final String foundation; public final String priority; public final String ip; public final String type; public final String tcpType; public final String relAddr; public final String relPort; public Candidate(String port, String protocol, String network, String generation, String id, String component, String foundation, String priority, String ip, String type, String tcpType, String relAddr, String relPort) { this.port = port; this.protocol = protocol; this.network = network; this.generation = generation; this.id = id; this.component = component; this.foundation = foundation; this.priority = priority; this.ip = ip; this.type = type; this.tcpType = tcpType; this.relAddr = relAddr; this.relPort = relPort; } @Override public String toString() { return "Candidate{" + "port=" + port + ", protocol=" + protocol + ", network=" + network + ", generation=" + generation + ", id=" + id + ", component=" + component + ", foundation=" + foundation + ", priority=" + priority + ", ip=" + ip + ", type=" + type + ", tcpType=" + tcpType + ", relAddr=" + relAddr + ", relPort=" + relPort + '}'; } } public static final class ServerConfig { public final boolean useSystemNs; public final boolean useSystemAec; public final boolean enableStunMarking; public final double hangupUiTimeout; public final boolean enable_vp8_encoder; public final boolean enable_vp8_decoder; public final boolean enable_vp9_encoder; public final boolean enable_vp9_decoder; public final boolean enable_h265_encoder; public final boolean enable_h265_decoder; public final boolean enable_h264_encoder; public final boolean enable_h264_decoder; private final JSONObject jsonObject; private ServerConfig(JSONObject jsonObject) { this.jsonObject = jsonObject; this.useSystemNs = jsonObject.optBoolean("use_system_ns", true); this.useSystemAec = jsonObject.optBoolean("use_system_aec", true); this.enableStunMarking = jsonObject.optBoolean("voip_enable_stun_marking", false); this.hangupUiTimeout = jsonObject.optDouble("hangup_ui_timeout", 5); this.enable_vp8_encoder = jsonObject.optBoolean("enable_vp8_encoder", true); this.enable_vp8_decoder = jsonObject.optBoolean("enable_vp8_decoder", true); this.enable_vp9_encoder = jsonObject.optBoolean("enable_vp9_encoder", true); this.enable_vp9_decoder = jsonObject.optBoolean("enable_vp9_decoder", true); this.enable_h265_encoder = jsonObject.optBoolean("enable_h265_encoder", true); this.enable_h265_decoder = jsonObject.optBoolean("enable_h265_decoder", true); this.enable_h264_encoder = jsonObject.optBoolean("enable_h264_encoder", true); this.enable_h264_decoder = jsonObject.optBoolean("enable_h264_decoder", true); } public String getString(String key) { return getString(key, ""); } public String getString(String key, String fallback) { return jsonObject.optString(key, fallback); } } }
dawitys/Telegram
TMessagesProj/src/main/java/org/telegram/messenger/voip/Instance.java
41,675
/* * Copyright (c) 2011-2019 Contributors to the Eclipse Foundation * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 * which is available at https://www.apache.org/licenses/LICENSE-2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 */ package io.vertx.core.http.impl; import java.util.HashMap; import java.util.Map; /** * We do our own mapping since support for mime mapping in Java is platform dependent * and doesn't seem to work very well * * @author <a href="http://tfox.org">Tim Fox</a> */ public class MimeMapping { private static final Map<String, String> m = new HashMap<>(); static { m.put("ez", "application/andrew-inset"); m.put("aw", "application/applixware"); m.put("atom", "application/atom+xml"); m.put("atomcat", "application/atomcat+xml"); m.put("atomsvc", "application/atomsvc+xml"); m.put("ccxml", "application/ccxml+xml"); m.put("cdmia", "application/cdmi-capability"); m.put("cdmic", "application/cdmi-container"); m.put("cdmid", "application/cdmi-domain"); m.put("cdmio", "application/cdmi-object"); m.put("cdmiq", "application/cdmi-queue"); m.put("cu", "application/cu-seeme"); m.put("davmount", "application/davmount+xml"); m.put("dbk", "application/docbook+xml"); m.put("dssc", "application/dssc+der"); m.put("xdssc", "application/dssc+xml"); m.put("ecma", "application/ecmascript"); m.put("emma", "application/emma+xml"); m.put("epub", "application/epub+zip"); m.put("exi", "application/exi"); m.put("pfr", "application/font-tdpfr"); m.put("gml", "application/gml+xml"); m.put("gpx", "application/gpx+xml"); m.put("gxf", "application/gxf"); m.put("stk", "application/hyperstudio"); m.put("ink", "application/inkml+xml"); m.put("inkml", "application/inkml+xml"); m.put("ipfix", "application/ipfix"); m.put("jar", "application/java-archive"); m.put("ser", "application/java-serialized-object"); m.put("class", "application/java-vm"); m.put("js", "text/javascript"); m.put("mjs", "text/javascript"); m.put("json", "application/json"); m.put("jsonml", "application/jsonml+json"); m.put("lostxml", "application/lost+xml"); m.put("hqx", "application/mac-binhex40"); m.put("cpt", "application/mac-compactpro"); m.put("mads", "application/mads+xml"); m.put("mrc", "application/marc"); m.put("mrcx", "application/marcxml+xml"); m.put("ma", "application/mathematica"); m.put("nb", "application/mathematica"); m.put("mb", "application/mathematica"); m.put("mathml", "application/mathml+xml"); m.put("mbox", "application/mbox"); m.put("mscml", "application/mediaservercontrol+xml"); m.put("metalink", "application/metalink+xml"); m.put("meta4", "application/metalink4+xml"); m.put("mets", "application/mets+xml"); m.put("mods", "application/mods+xml"); m.put("m21", "application/mp21"); m.put("mp21", "application/mp21"); m.put("mp4s", "application/mp4"); m.put("doc", "application/msword"); m.put("dot", "application/msword"); m.put("mxf", "application/mxf"); m.put("bin", "application/octet-stream"); m.put("dms", "application/octet-stream"); m.put("lrf", "application/octet-stream"); m.put("mar", "application/octet-stream"); m.put("so", "application/octet-stream"); m.put("dist", "application/octet-stream"); m.put("distz", "application/octet-stream"); m.put("pkg", "application/octet-stream"); m.put("bpk", "application/octet-stream"); m.put("dump", "application/octet-stream"); m.put("elc", "application/octet-stream"); m.put("deploy", "application/octet-stream"); m.put("oda", "application/oda"); m.put("opf", "application/oebps-package+xml"); m.put("ogx", "application/ogg"); m.put("omdoc", "application/omdoc+xml"); m.put("onetoc", "application/onenote"); m.put("onetoc2", "application/onenote"); m.put("onetmp", "application/onenote"); m.put("onepkg", "application/onenote"); m.put("oxps", "application/oxps"); m.put("xer", "application/patch-ops-error+xml"); m.put("pdf", "application/pdf"); m.put("pgp", "application/pgp-encrypted"); m.put("asc", "application/pgp-signature"); m.put("sig", "application/pgp-signature"); m.put("prf", "application/pics-rules"); m.put("p10", "application/pkcs10"); m.put("p7m", "application/pkcs7-mime"); m.put("p7c", "application/pkcs7-mime"); m.put("p7s", "application/pkcs7-signature"); m.put("p8", "application/pkcs8"); m.put("ac", "application/pkix-attr-cert"); m.put("cer", "application/pkix-cert"); m.put("crl", "application/pkix-crl"); m.put("pkipath", "application/pkix-pkipath"); m.put("pki", "application/pkixcmp"); m.put("pls", "application/pls+xml"); m.put("ai", "application/postscript"); m.put("eps", "application/postscript"); m.put("ps", "application/postscript"); m.put("cww", "application/prs.cww"); m.put("pskcxml", "application/pskc+xml"); m.put("rdf", "application/rdf+xml"); m.put("rif", "application/reginfo+xml"); m.put("rnc", "application/relax-ng-compact-syntax"); m.put("rl", "application/resource-lists+xml"); m.put("rld", "application/resource-lists-diff+xml"); m.put("rs", "application/rls-services+xml"); m.put("gbr", "application/rpki-ghostbusters"); m.put("mft", "application/rpki-manifest"); m.put("roa", "application/rpki-roa"); m.put("rsd", "application/rsd+xml"); m.put("rss", "application/rss+xml"); m.put("rtf", "application/rtf"); m.put("sbml", "application/sbml+xml"); m.put("scq", "application/scvp-cv-request"); m.put("scs", "application/scvp-cv-response"); m.put("spq", "application/scvp-vp-request"); m.put("spp", "application/scvp-vp-response"); m.put("sdp", "application/sdp"); m.put("setpay", "application/set-payment-initiation"); m.put("setreg", "application/set-registration-initiation"); m.put("shf", "application/shf+xml"); m.put("smi", "application/smil+xml"); m.put("smil", "application/smil+xml"); m.put("rq", "application/sparql-query"); m.put("srx", "application/sparql-results+xml"); m.put("gram", "application/srgs"); m.put("grxml", "application/srgs+xml"); m.put("sru", "application/sru+xml"); m.put("ssdl", "application/ssdl+xml"); m.put("ssml", "application/ssml+xml"); m.put("tei", "application/tei+xml"); m.put("teicorpus", "application/tei+xml"); m.put("tfi", "application/thraud+xml"); m.put("tsd", "application/timestamped-data"); m.put("plb", "application/vnd.3gpp.pic-bw-large"); m.put("psb", "application/vnd.3gpp.pic-bw-small"); m.put("pvb", "application/vnd.3gpp.pic-bw-var"); m.put("tcap", "application/vnd.3gpp2.tcap"); m.put("pwn", "application/vnd.3m.post-it-notes"); m.put("aso", "application/vnd.accpac.simply.aso"); m.put("imp", "application/vnd.accpac.simply.imp"); m.put("acu", "application/vnd.acucobol"); m.put("atc", "application/vnd.acucorp"); m.put("acutc", "application/vnd.acucorp"); m.put("air", "application/vnd.adobe.air-application-installer-package+zip"); m.put("fcdt", "application/vnd.adobe.formscentral.fcdt"); m.put("fxp", "application/vnd.adobe.fxp"); m.put("fxpl", "application/vnd.adobe.fxp"); m.put("xdp", "application/vnd.adobe.xdp+xml"); m.put("xfdf", "application/vnd.adobe.xfdf"); m.put("ahead", "application/vnd.ahead.space"); m.put("azf", "application/vnd.airzip.filesecure.azf"); m.put("azs", "application/vnd.airzip.filesecure.azs"); m.put("azw", "application/vnd.amazon.ebook"); m.put("acc", "application/vnd.americandynamics.acc"); m.put("ami", "application/vnd.amiga.ami"); m.put("apk", "application/vnd.android.package-archive"); m.put("cii", "application/vnd.anser-web-certificate-issue-initiation"); m.put("fti", "application/vnd.anser-web-funds-transfer-initiation"); m.put("atx", "application/vnd.antix.game-component"); m.put("mpkg", "application/vnd.apple.installer+xml"); m.put("m3u8", "application/vnd.apple.mpegurl"); m.put("swi", "application/vnd.aristanetworks.swi"); m.put("iota", "application/vnd.astraea-software.iota"); m.put("aep", "application/vnd.audiograph"); m.put("mpm", "application/vnd.blueice.multipass"); m.put("bmi", "application/vnd.bmi"); m.put("rep", "application/vnd.businessobjects"); m.put("cdxml", "application/vnd.chemdraw+xml"); m.put("mmd", "application/vnd.chipnuts.karaoke-mmd"); m.put("cdy", "application/vnd.cinderella"); m.put("cla", "application/vnd.claymore"); m.put("rp9", "application/vnd.cloanto.rp9"); m.put("c4g", "application/vnd.clonk.c4group"); m.put("c4d", "application/vnd.clonk.c4group"); m.put("c4f", "application/vnd.clonk.c4group"); m.put("c4p", "application/vnd.clonk.c4group"); m.put("c4u", "application/vnd.clonk.c4group"); m.put("c11amc", "application/vnd.cluetrust.cartomobile-config"); m.put("c11amz", "application/vnd.cluetrust.cartomobile-config-pkg"); m.put("csp", "application/vnd.commonspace"); m.put("cdbcmsg", "application/vnd.contact.cmsg"); m.put("cmc", "application/vnd.cosmocaller"); m.put("clkx", "application/vnd.crick.clicker"); m.put("clkk", "application/vnd.crick.clicker.keyboard"); m.put("clkp", "application/vnd.crick.clicker.palette"); m.put("clkt", "application/vnd.crick.clicker.template"); m.put("clkw", "application/vnd.crick.clicker.wordbank"); m.put("wbs", "application/vnd.criticaltools.wbs+xml"); m.put("pml", "application/vnd.ctc-posml"); m.put("ppd", "application/vnd.cups-ppd"); m.put("car", "application/vnd.curl.car"); m.put("pcurl", "application/vnd.curl.pcurl"); m.put("dart", "application/vnd.dart"); m.put("rdz", "application/vnd.data-vision.rdz"); m.put("uvf", "application/vnd.dece.data"); m.put("uvvf", "application/vnd.dece.data"); m.put("uvd", "application/vnd.dece.data"); m.put("uvvd", "application/vnd.dece.data"); m.put("uvt", "application/vnd.dece.ttml+xml"); m.put("uvvt", "application/vnd.dece.ttml+xml"); m.put("uvx", "application/vnd.dece.unspecified"); m.put("uvvx", "application/vnd.dece.unspecified"); m.put("uvz", "application/vnd.dece.zip"); m.put("uvvz", "application/vnd.dece.zip"); m.put("fe_launch", "application/vnd.denovo.fcselayout-link"); m.put("dna", "application/vnd.dna"); m.put("mlp", "application/vnd.dolby.mlp"); m.put("dpg", "application/vnd.dpgraph"); m.put("dfac", "application/vnd.dreamfactory"); m.put("kpxx", "application/vnd.ds-keypoint"); m.put("ait", "application/vnd.dvb.ait"); m.put("svc", "application/vnd.dvb.service"); m.put("geo", "application/vnd.dynageo"); m.put("mag", "application/vnd.ecowin.chart"); m.put("nml", "application/vnd.enliven"); m.put("esf", "application/vnd.epson.esf"); m.put("msf", "application/vnd.epson.msf"); m.put("qam", "application/vnd.epson.quickanime"); m.put("slt", "application/vnd.epson.salt"); m.put("ssf", "application/vnd.epson.ssf"); m.put("es3", "application/vnd.eszigno3+xml"); m.put("et3", "application/vnd.eszigno3+xml"); m.put("ez2", "application/vnd.ezpix-album"); m.put("ez3", "application/vnd.ezpix-package"); m.put("fdf", "application/vnd.fdf"); m.put("mseed", "application/vnd.fdsn.mseed"); m.put("seed", "application/vnd.fdsn.seed"); m.put("dataless", "application/vnd.fdsn.seed"); m.put("gph", "application/vnd.flographit"); m.put("ftc", "application/vnd.fluxtime.clip"); m.put("fm", "application/vnd.framemaker"); m.put("frame", "application/vnd.framemaker"); m.put("maker", "application/vnd.framemaker"); m.put("book", "application/vnd.framemaker"); m.put("fnc", "application/vnd.frogans.fnc"); m.put("ltf", "application/vnd.frogans.ltf"); m.put("fsc", "application/vnd.fsc.weblaunch"); m.put("oas", "application/vnd.fujitsu.oasys"); m.put("oa2", "application/vnd.fujitsu.oasys2"); m.put("oa3", "application/vnd.fujitsu.oasys3"); m.put("fg5", "application/vnd.fujitsu.oasysgp"); m.put("bh2", "application/vnd.fujitsu.oasysprs"); m.put("ddd", "application/vnd.fujixerox.ddd"); m.put("xdw", "application/vnd.fujixerox.docuworks"); m.put("xbd", "application/vnd.fujixerox.docuworks.binder"); m.put("fzs", "application/vnd.fuzzysheet"); m.put("txd", "application/vnd.genomatix.tuxedo"); m.put("ggb", "application/vnd.geogebra.file"); m.put("ggt", "application/vnd.geogebra.tool"); m.put("gex", "application/vnd.geometry-explorer"); m.put("gre", "application/vnd.geometry-explorer"); m.put("gxt", "application/vnd.geonext"); m.put("g2w", "application/vnd.geoplan"); m.put("g3w", "application/vnd.geospace"); m.put("gmx", "application/vnd.gmx"); m.put("kml", "application/vnd.google-earth.kml+xml"); m.put("kmz", "application/vnd.google-earth.kmz"); m.put("gqf", "application/vnd.grafeq"); m.put("gqs", "application/vnd.grafeq"); m.put("gac", "application/vnd.groove-account"); m.put("ghf", "application/vnd.groove-help"); m.put("gim", "application/vnd.groove-identity-message"); m.put("grv", "application/vnd.groove-injector"); m.put("gtm", "application/vnd.groove-tool-message"); m.put("tpl", "application/vnd.groove-tool-template"); m.put("vcg", "application/vnd.groove-vcard"); m.put("hal", "application/vnd.hal+xml"); m.put("zmm", "application/vnd.handheld-entertainment+xml"); m.put("hbci", "application/vnd.hbci"); m.put("les", "application/vnd.hhe.lesson-player"); m.put("hpgl", "application/vnd.hp-hpgl"); m.put("hpid", "application/vnd.hp-hpid"); m.put("hps", "application/vnd.hp-hps"); m.put("jlt", "application/vnd.hp-jlyt"); m.put("pcl", "application/vnd.hp-pcl"); m.put("pclxl", "application/vnd.hp-pclxl"); m.put("sfd-hdstx", "application/vnd.hydrostatix.sof-data"); m.put("mpy", "application/vnd.ibm.minipay"); m.put("afp", "application/vnd.ibm.modcap"); m.put("listafp", "application/vnd.ibm.modcap"); m.put("list3820", "application/vnd.ibm.modcap"); m.put("irm", "application/vnd.ibm.rights-management"); m.put("sc", "application/vnd.ibm.secure-container"); m.put("icc", "application/vnd.iccprofile"); m.put("icm", "application/vnd.iccprofile"); m.put("igl", "application/vnd.igloader"); m.put("ivp", "application/vnd.immervision-ivp"); m.put("ivu", "application/vnd.immervision-ivu"); m.put("igm", "application/vnd.insors.igm"); m.put("xpw", "application/vnd.intercon.formnet"); m.put("xpx", "application/vnd.intercon.formnet"); m.put("i2g", "application/vnd.intergeo"); m.put("qbo", "application/vnd.intu.qbo"); m.put("qfx", "application/vnd.intu.qfx"); m.put("rcprofile", "application/vnd.ipunplugged.rcprofile"); m.put("irp", "application/vnd.irepository.package+xml"); m.put("xpr", "application/vnd.is-xpr"); m.put("fcs", "application/vnd.isac.fcs"); m.put("jam", "application/vnd.jam"); m.put("rms", "application/vnd.jcp.javame.midlet-rms"); m.put("jisp", "application/vnd.jisp"); m.put("joda", "application/vnd.joost.joda-archive"); m.put("ktz", "application/vnd.kahootz"); m.put("ktr", "application/vnd.kahootz"); m.put("karbon", "application/vnd.kde.karbon"); m.put("chrt", "application/vnd.kde.kchart"); m.put("kfo", "application/vnd.kde.kformula"); m.put("flw", "application/vnd.kde.kivio"); m.put("kon", "application/vnd.kde.kontour"); m.put("kpr", "application/vnd.kde.kpresenter"); m.put("kpt", "application/vnd.kde.kpresenter"); m.put("ksp", "application/vnd.kde.kspread"); m.put("kwd", "application/vnd.kde.kword"); m.put("kwt", "application/vnd.kde.kword"); m.put("htke", "application/vnd.kenameaapp"); m.put("kia", "application/vnd.kidspiration"); m.put("kne", "application/vnd.kinar"); m.put("knp", "application/vnd.kinar"); m.put("skp", "application/vnd.koan"); m.put("skd", "application/vnd.koan"); m.put("skt", "application/vnd.koan"); m.put("skm", "application/vnd.koan"); m.put("sse", "application/vnd.kodak-descriptor"); m.put("lasxml", "application/vnd.las.las+xml"); m.put("lbd", "application/vnd.llamagraphics.life-balance.desktop"); m.put("lbe", "application/vnd.llamagraphics.life-balance.exchange+xml"); m.put("123", "application/vnd.lotus-1-2-3"); m.put("apr", "application/vnd.lotus-approach"); m.put("pre", "application/vnd.lotus-freelance"); m.put("nsf", "application/vnd.lotus-notes"); m.put("org", "application/vnd.lotus-organizer"); m.put("scm", "application/vnd.lotus-screencam"); m.put("lwp", "application/vnd.lotus-wordpro"); m.put("portpkg", "application/vnd.macports.portpkg"); m.put("mcd", "application/vnd.mcd"); m.put("mc1", "application/vnd.medcalcdata"); m.put("cdkey", "application/vnd.mediastation.cdkey"); m.put("mwf", "application/vnd.mfer"); m.put("mfm", "application/vnd.mfmp"); m.put("flo", "application/vnd.micrografx.flo"); m.put("igx", "application/vnd.micrografx.igx"); m.put("mif", "application/vnd.mif"); m.put("daf", "application/vnd.mobius.daf"); m.put("dis", "application/vnd.mobius.dis"); m.put("mbk", "application/vnd.mobius.mbk"); m.put("mqy", "application/vnd.mobius.mqy"); m.put("msl", "application/vnd.mobius.msl"); m.put("plc", "application/vnd.mobius.plc"); m.put("txf", "application/vnd.mobius.txf"); m.put("mpn", "application/vnd.mophun.application"); m.put("mpc", "application/vnd.mophun.certificate"); m.put("xul", "application/vnd.mozilla.xul+xml"); m.put("cil", "application/vnd.ms-artgalry"); m.put("cab", "application/vnd.ms-cab-compressed"); m.put("xls", "application/vnd.ms-excel"); m.put("xlm", "application/vnd.ms-excel"); m.put("xla", "application/vnd.ms-excel"); m.put("xlc", "application/vnd.ms-excel"); m.put("xlt", "application/vnd.ms-excel"); m.put("xlw", "application/vnd.ms-excel"); m.put("xlam", "application/vnd.ms-excel.addin.macroenabled.12"); m.put("xlsb", "application/vnd.ms-excel.sheet.binary.macroenabled.12"); m.put("xlsm", "application/vnd.ms-excel.sheet.macroenabled.12"); m.put("xltm", "application/vnd.ms-excel.template.macroenabled.12"); m.put("eot", "application/vnd.ms-fontobject"); m.put("chm", "application/vnd.ms-htmlhelp"); m.put("ims", "application/vnd.ms-ims"); m.put("lrm", "application/vnd.ms-lrm"); m.put("thmx", "application/vnd.ms-officetheme"); m.put("cat", "application/vnd.ms-pki.seccat"); m.put("stl", "application/vnd.ms-pki.stl"); m.put("ppt", "application/vnd.ms-powerpoint"); m.put("pps", "application/vnd.ms-powerpoint"); m.put("pot", "application/vnd.ms-powerpoint"); m.put("ppam", "application/vnd.ms-powerpoint.addin.macroenabled.12"); m.put("pptm", "application/vnd.ms-powerpoint.presentation.macroenabled.12"); m.put("sldm", "application/vnd.ms-powerpoint.slide.macroenabled.12"); m.put("ppsm", "application/vnd.ms-powerpoint.slideshow.macroenabled.12"); m.put("potm", "application/vnd.ms-powerpoint.template.macroenabled.12"); m.put("mpp", "application/vnd.ms-project"); m.put("mpt", "application/vnd.ms-project"); m.put("docm", "application/vnd.ms-word.document.macroenabled.12"); m.put("dotm", "application/vnd.ms-word.template.macroenabled.12"); m.put("wps", "application/vnd.ms-works"); m.put("wks", "application/vnd.ms-works"); m.put("wcm", "application/vnd.ms-works"); m.put("wdb", "application/vnd.ms-works"); m.put("wpl", "application/vnd.ms-wpl"); m.put("xps", "application/vnd.ms-xpsdocument"); m.put("mseq", "application/vnd.mseq"); m.put("mus", "application/vnd.musician"); m.put("msty", "application/vnd.muvee.style"); m.put("taglet", "application/vnd.mynfc"); m.put("nlu", "application/vnd.neurolanguage.nlu"); m.put("ntf", "application/vnd.nitf"); m.put("nitf", "application/vnd.nitf"); m.put("nnd", "application/vnd.noblenet-directory"); m.put("nns", "application/vnd.noblenet-sealer"); m.put("nnw", "application/vnd.noblenet-web"); m.put("ngdat", "application/vnd.nokia.n-gage.data"); m.put("n-gage", "application/vnd.nokia.n-gage.symbian.install"); m.put("rpst", "application/vnd.nokia.radio-preset"); m.put("rpss", "application/vnd.nokia.radio-presets"); m.put("edm", "application/vnd.novadigm.edm"); m.put("edx", "application/vnd.novadigm.edx"); m.put("ext", "application/vnd.novadigm.ext"); m.put("odc", "application/vnd.oasis.opendocument.chart"); m.put("otc", "application/vnd.oasis.opendocument.chart-template"); m.put("odb", "application/vnd.oasis.opendocument.database"); m.put("odf", "application/vnd.oasis.opendocument.formula"); m.put("odft", "application/vnd.oasis.opendocument.formula-template"); m.put("odg", "application/vnd.oasis.opendocument.graphics"); m.put("otg", "application/vnd.oasis.opendocument.graphics-template"); m.put("odi", "application/vnd.oasis.opendocument.image"); m.put("oti", "application/vnd.oasis.opendocument.image-template"); m.put("odp", "application/vnd.oasis.opendocument.presentation"); m.put("otp", "application/vnd.oasis.opendocument.presentation-template"); m.put("ods", "application/vnd.oasis.opendocument.spreadsheet"); m.put("ots", "application/vnd.oasis.opendocument.spreadsheet-template"); m.put("odt", "application/vnd.oasis.opendocument.text"); m.put("odm", "application/vnd.oasis.opendocument.text-master"); m.put("ott", "application/vnd.oasis.opendocument.text-template"); m.put("oth", "application/vnd.oasis.opendocument.text-web"); m.put("xo", "application/vnd.olpc-sugar"); m.put("dd2", "application/vnd.oma.dd2+xml"); m.put("oxt", "application/vnd.openofficeorg.extension"); m.put("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"); m.put("sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"); m.put("ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"); m.put("potx", "application/vnd.openxmlformats-officedocument.presentationml.template"); m.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); m.put("xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"); m.put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); m.put("dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"); m.put("mgp", "application/vnd.osgeo.mapguide.package"); m.put("dp", "application/vnd.osgi.dp"); m.put("esa", "application/vnd.osgi.subsystem"); m.put("pdb", "application/vnd.palm"); m.put("pqa", "application/vnd.palm"); m.put("oprc", "application/vnd.palm"); m.put("paw", "application/vnd.pawaafile"); m.put("str", "application/vnd.pg.format"); m.put("ei6", "application/vnd.pg.osasli"); m.put("efif", "application/vnd.picsel"); m.put("wg", "application/vnd.pmi.widget"); m.put("plf", "application/vnd.pocketlearn"); m.put("pbd", "application/vnd.powerbuilder6"); m.put("box", "application/vnd.previewsystems.box"); m.put("mgz", "application/vnd.proteus.magazine"); m.put("qps", "application/vnd.publishare-delta-tree"); m.put("ptid", "application/vnd.pvi.ptid1"); m.put("qxd", "application/vnd.quark.quarkxpress"); m.put("qxt", "application/vnd.quark.quarkxpress"); m.put("qwd", "application/vnd.quark.quarkxpress"); m.put("qwt", "application/vnd.quark.quarkxpress"); m.put("qxl", "application/vnd.quark.quarkxpress"); m.put("qxb", "application/vnd.quark.quarkxpress"); m.put("bed", "application/vnd.realvnc.bed"); m.put("mxl", "application/vnd.recordare.musicxml"); m.put("musicxml", "application/vnd.recordare.musicxml+xml"); m.put("cryptonote", "application/vnd.rig.cryptonote"); m.put("cod", "application/vnd.rim.cod"); m.put("rm", "application/vnd.rn-realmedia"); m.put("rmvb", "application/vnd.rn-realmedia-vbr"); m.put("link66", "application/vnd.route66.link66+xml"); m.put("st", "application/vnd.sailingtracker.track"); m.put("see", "application/vnd.seemail"); m.put("sema", "application/vnd.sema"); m.put("semd", "application/vnd.semd"); m.put("semf", "application/vnd.semf"); m.put("ifm", "application/vnd.shana.informed.formdata"); m.put("itp", "application/vnd.shana.informed.formtemplate"); m.put("iif", "application/vnd.shana.informed.interchange"); m.put("ipk", "application/vnd.shana.informed.package"); m.put("twd", "application/vnd.simtech-mindmapper"); m.put("twds", "application/vnd.simtech-mindmapper"); m.put("mmf", "application/vnd.smaf"); m.put("teacher", "application/vnd.smart.teacher"); m.put("sdkm", "application/vnd.solent.sdkm+xml"); m.put("sdkd", "application/vnd.solent.sdkm+xml"); m.put("dxp", "application/vnd.spotfire.dxp"); m.put("sfs", "application/vnd.spotfire.sfs"); m.put("sdc", "application/vnd.stardivision.calc"); m.put("sda", "application/vnd.stardivision.draw"); m.put("sdd", "application/vnd.stardivision.impress"); m.put("smf", "application/vnd.stardivision.math"); m.put("sdw", "application/vnd.stardivision.writer"); m.put("vor", "application/vnd.stardivision.writer"); m.put("sgl", "application/vnd.stardivision.writer-global"); m.put("smzip", "application/vnd.stepmania.package"); m.put("sm", "application/vnd.stepmania.stepchart"); m.put("sxc", "application/vnd.sun.xml.calc"); m.put("stc", "application/vnd.sun.xml.calc.template"); m.put("sxd", "application/vnd.sun.xml.draw"); m.put("std", "application/vnd.sun.xml.draw.template"); m.put("sxi", "application/vnd.sun.xml.impress"); m.put("sti", "application/vnd.sun.xml.impress.template"); m.put("sxm", "application/vnd.sun.xml.math"); m.put("sxw", "application/vnd.sun.xml.writer"); m.put("sxg", "application/vnd.sun.xml.writer.global"); m.put("stw", "application/vnd.sun.xml.writer.template"); m.put("sus", "application/vnd.sus-calendar"); m.put("susp", "application/vnd.sus-calendar"); m.put("svd", "application/vnd.svd"); m.put("sis", "application/vnd.symbian.install"); m.put("sisx", "application/vnd.symbian.install"); m.put("xsm", "application/vnd.syncml+xml"); m.put("bdm", "application/vnd.syncml.dm+wbxml"); m.put("xdm", "application/vnd.syncml.dm+xml"); m.put("tao", "application/vnd.tao.intent-module-archive"); m.put("pcap", "application/vnd.tcpdump.pcap"); m.put("cap", "application/vnd.tcpdump.pcap"); m.put("dmp", "application/vnd.tcpdump.pcap"); m.put("tmo", "application/vnd.tmobile-livetv"); m.put("tpt", "application/vnd.trid.tpt"); m.put("mxs", "application/vnd.triscape.mxs"); m.put("tra", "application/vnd.trueapp"); m.put("ufd", "application/vnd.ufdl"); m.put("ufdl", "application/vnd.ufdl"); m.put("utz", "application/vnd.uiq.theme"); m.put("umj", "application/vnd.umajin"); m.put("unityweb", "application/vnd.unity"); m.put("uoml", "application/vnd.uoml+xml"); m.put("vcx", "application/vnd.vcx"); m.put("vsd", "application/vnd.visio"); m.put("vst", "application/vnd.visio"); m.put("vss", "application/vnd.visio"); m.put("vsw", "application/vnd.visio"); m.put("vis", "application/vnd.visionary"); m.put("vsf", "application/vnd.vsf"); m.put("wbxml", "application/vnd.wap.wbxml"); m.put("wmlc", "application/vnd.wap.wmlc"); m.put("wmlsc", "application/vnd.wap.wmlscriptc"); m.put("wtb", "application/vnd.webturbo"); m.put("nbp", "application/vnd.wolfram.player"); m.put("wpd", "application/vnd.wordperfect"); m.put("wqd", "application/vnd.wqd"); m.put("stf", "application/vnd.wt.stf"); m.put("xar", "application/vnd.xara"); m.put("xfdl", "application/vnd.xfdl"); m.put("hvd", "application/vnd.yamaha.hv-dic"); m.put("hvs", "application/vnd.yamaha.hv-script"); m.put("hvp", "application/vnd.yamaha.hv-voice"); m.put("osf", "application/vnd.yamaha.openscoreformat"); m.put("osfpvg", "application/vnd.yamaha.openscoreformat.osfpvg+xml"); m.put("saf", "application/vnd.yamaha.smaf-audio"); m.put("spf", "application/vnd.yamaha.smaf-phrase"); m.put("cmp", "application/vnd.yellowriver-custom-menu"); m.put("zir", "application/vnd.zul"); m.put("zirz", "application/vnd.zul"); m.put("zaz", "application/vnd.zzazz.deck+xml"); m.put("vxml", "application/voicexml+xml"); m.put("wasm", "application/wasm"); m.put("wgt", "application/widget"); m.put("hlp", "application/winhlp"); m.put("wsdl", "application/wsdl+xml"); m.put("wspolicy", "application/wspolicy+xml"); m.put("7z", "application/x-7z-compressed"); m.put("abw", "application/x-abiword"); m.put("ace", "application/x-ace-compressed"); m.put("dmg", "application/x-apple-diskimage"); m.put("aab", "application/x-authorware-bin"); m.put("x32", "application/x-authorware-bin"); m.put("u32", "application/x-authorware-bin"); m.put("vox", "application/x-authorware-bin"); m.put("aam", "application/x-authorware-map"); m.put("aas", "application/x-authorware-seg"); m.put("bcpio", "application/x-bcpio"); m.put("torrent", "application/x-bittorrent"); m.put("blb", "application/x-blorb"); m.put("blorb", "application/x-blorb"); m.put("bz", "application/x-bzip"); m.put("bz2", "application/x-bzip2"); m.put("boz", "application/x-bzip2"); m.put("cbr", "application/x-cbr"); m.put("cba", "application/x-cbr"); m.put("cbt", "application/x-cbr"); m.put("cbz", "application/x-cbr"); m.put("cb7", "application/x-cbr"); m.put("vcd", "application/x-cdlink"); m.put("cfs", "application/x-cfs-compressed"); m.put("chat", "application/x-chat"); m.put("pgn", "application/x-chess-pgn"); m.put("nsc", "application/x-conference"); m.put("cpio", "application/x-cpio"); m.put("csh", "application/x-csh"); m.put("deb", "application/x-debian-package"); m.put("udeb", "application/x-debian-package"); m.put("dgc", "application/x-dgc-compressed"); m.put("dir", "application/x-director"); m.put("dcr", "application/x-director"); m.put("dxr", "application/x-director"); m.put("cst", "application/x-director"); m.put("cct", "application/x-director"); m.put("cxt", "application/x-director"); m.put("w3d", "application/x-director"); m.put("fgd", "application/x-director"); m.put("swa", "application/x-director"); m.put("wad", "application/x-doom"); m.put("ncx", "application/x-dtbncx+xml"); m.put("dtb", "application/x-dtbook+xml"); m.put("res", "application/x-dtbresource+xml"); m.put("dvi", "application/x-dvi"); m.put("evy", "application/x-envoy"); m.put("eva", "application/x-eva"); m.put("bdf", "application/x-font-bdf"); m.put("gsf", "application/x-font-ghostscript"); m.put("psf", "application/x-font-linux-psf"); m.put("otf", "application/x-font-otf"); m.put("pcf", "application/x-font-pcf"); m.put("snf", "application/x-font-snf"); m.put("ttf", "application/x-font-ttf"); m.put("ttc", "application/x-font-ttf"); m.put("pfa", "application/x-font-type1"); m.put("pfb", "application/x-font-type1"); m.put("pfm", "application/x-font-type1"); m.put("afm", "application/x-font-type1"); m.put("woff", "application/x-font-woff"); m.put("woff2", "font/woff2"); m.put("arc", "application/x-freearc"); m.put("spl", "application/x-futuresplash"); m.put("gca", "application/x-gca-compressed"); m.put("ulx", "application/x-glulx"); m.put("gnumeric", "application/x-gnumeric"); m.put("gramps", "application/x-gramps-xml"); m.put("gtar", "application/x-gtar"); m.put("hdf", "application/x-hdf"); m.put("install", "application/x-install-instructions"); m.put("iso", "application/x-iso9660-image"); m.put("jnlp", "application/x-java-jnlp-file"); m.put("latex", "application/x-latex"); m.put("lzh", "application/x-lzh-compressed"); m.put("lha", "application/x-lzh-compressed"); m.put("mie", "application/x-mie"); m.put("prc", "application/x-mobipocket-ebook"); m.put("mobi", "application/x-mobipocket-ebook"); m.put("application", "application/x-ms-application"); m.put("lnk", "application/x-ms-shortcut"); m.put("wmd", "application/x-ms-wmd"); m.put("wmz", "application/x-ms-wmz"); m.put("xbap", "application/x-ms-xbap"); m.put("mdb", "application/x-msaccess"); m.put("obd", "application/x-msbinder"); m.put("crd", "application/x-mscardfile"); m.put("clp", "application/x-msclip"); m.put("exe", "application/x-msdownload"); m.put("dll", "application/x-msdownload"); m.put("com", "application/x-msdownload"); m.put("bat", "application/x-msdownload"); m.put("msi", "application/x-msdownload"); m.put("mvb", "application/x-msmediaview"); m.put("m13", "application/x-msmediaview"); m.put("m14", "application/x-msmediaview"); m.put("wmf", "application/x-msmetafile"); m.put("emf", "application/x-msmetafile"); m.put("emz", "application/x-msmetafile"); m.put("mny", "application/x-msmoney"); m.put("pub", "application/x-mspublisher"); m.put("scd", "application/x-msschedule"); m.put("trm", "application/x-msterminal"); m.put("wri", "application/x-mswrite"); m.put("nc", "application/x-netcdf"); m.put("cdf", "application/x-netcdf"); m.put("nzb", "application/x-nzb"); m.put("p12", "application/x-pkcs12"); m.put("pfx", "application/x-pkcs12"); m.put("p7b", "application/x-pkcs7-certificates"); m.put("spc", "application/x-pkcs7-certificates"); m.put("p7r", "application/x-pkcs7-certreqresp"); m.put("rar", "application/x-rar-compressed"); m.put("ris", "application/x-research-info-systems"); m.put("sh", "application/x-sh"); m.put("shar", "application/x-shar"); m.put("swf", "application/x-shockwave-flash"); m.put("xap", "application/x-silverlight-app"); m.put("sql", "application/x-sql"); m.put("sit", "application/x-stuffit"); m.put("sitx", "application/x-stuffitx"); m.put("srt", "application/x-subrip"); m.put("sv4cpio", "application/x-sv4cpio"); m.put("sv4crc", "application/x-sv4crc"); m.put("t3", "application/x-t3vm-image"); m.put("gam", "application/x-tads"); m.put("tar", "application/x-tar"); m.put("tcl", "application/x-tcl"); m.put("tex", "application/x-tex"); m.put("tfm", "application/x-tex-tfm"); m.put("texinfo", "application/x-texinfo"); m.put("texi", "application/x-texinfo"); m.put("obj", "application/x-tgif"); m.put("ustar", "application/x-ustar"); m.put("src", "application/x-wais-source"); m.put("der", "application/x-x509-ca-cert"); m.put("crt", "application/x-x509-ca-cert"); m.put("fig", "application/x-xfig"); m.put("xlf", "application/x-xliff+xml"); m.put("xpi", "application/x-xpinstall"); m.put("xz", "application/x-xz"); m.put("yml", "application/x-yaml"); m.put("yaml", "application/x-yaml"); m.put("z1", "application/x-zmachine"); m.put("z2", "application/x-zmachine"); m.put("z3", "application/x-zmachine"); m.put("z4", "application/x-zmachine"); m.put("z5", "application/x-zmachine"); m.put("z6", "application/x-zmachine"); m.put("z7", "application/x-zmachine"); m.put("z8", "application/x-zmachine"); m.put("xaml", "application/xaml+xml"); m.put("xdf", "application/xcap-diff+xml"); m.put("xenc", "application/xenc+xml"); m.put("xhtml", "application/xhtml+xml"); m.put("xht", "application/xhtml+xml"); m.put("xml", "application/xml"); m.put("xsl", "application/xml"); m.put("dtd", "application/xml-dtd"); m.put("xop", "application/xop+xml"); m.put("xpl", "application/xproc+xml"); m.put("xslt", "application/xslt+xml"); m.put("xspf", "application/xspf+xml"); m.put("mxml", "application/xv+xml"); m.put("xhvml", "application/xv+xml"); m.put("xvml", "application/xv+xml"); m.put("xvm", "application/xv+xml"); m.put("yang", "application/yang"); m.put("yin", "application/yin+xml"); m.put("zip", "application/zip"); m.put("adp", "audio/adpcm"); m.put("au", "audio/basic"); m.put("snd", "audio/basic"); m.put("mid", "audio/midi"); m.put("midi", "audio/midi"); m.put("kar", "audio/midi"); m.put("rmi", "audio/midi"); m.put("mp4a", "audio/mp4"); m.put("mpga", "audio/mpeg"); m.put("mp2", "audio/mpeg"); m.put("mp2a", "audio/mpeg"); m.put("mp3", "audio/mpeg"); m.put("m2a", "audio/mpeg"); m.put("m3a", "audio/mpeg"); m.put("oga", "audio/ogg"); m.put("ogg", "audio/ogg"); m.put("spx", "audio/ogg"); m.put("s3m", "audio/s3m"); m.put("sil", "audio/silk"); m.put("uva", "audio/vnd.dece.audio"); m.put("uvva", "audio/vnd.dece.audio"); m.put("eol", "audio/vnd.digital-winds"); m.put("dra", "audio/vnd.dra"); m.put("dts", "audio/vnd.dts"); m.put("dtshd", "audio/vnd.dts.hd"); m.put("lvp", "audio/vnd.lucent.voice"); m.put("pya", "audio/vnd.ms-playready.media.pya"); m.put("ecelp4800", "audio/vnd.nuera.ecelp4800"); m.put("ecelp7470", "audio/vnd.nuera.ecelp7470"); m.put("ecelp9600", "audio/vnd.nuera.ecelp9600"); m.put("rip", "audio/vnd.rip"); m.put("weba", "audio/webm"); m.put("aac", "audio/x-aac"); m.put("aif", "audio/x-aiff"); m.put("aiff", "audio/x-aiff"); m.put("aifc", "audio/x-aiff"); m.put("caf", "audio/x-caf"); m.put("flac", "audio/x-flac"); m.put("mka", "audio/x-matroska"); m.put("m3u", "audio/x-mpegurl"); m.put("wax", "audio/x-ms-wax"); m.put("wma", "audio/x-ms-wma"); m.put("ram", "audio/x-pn-realaudio"); m.put("ra", "audio/x-pn-realaudio"); m.put("rmp", "audio/x-pn-realaudio-plugin"); m.put("wav", "audio/x-wav"); m.put("xm", "audio/xm"); m.put("cdx", "chemical/x-cdx"); m.put("cif", "chemical/x-cif"); m.put("cmdf", "chemical/x-cmdf"); m.put("cml", "chemical/x-cml"); m.put("csml", "chemical/x-csml"); m.put("xyz", "chemical/x-xyz"); m.put("bmp", "image/bmp"); m.put("cgm", "image/cgm"); m.put("g3", "image/g3fax"); m.put("gif", "image/gif"); m.put("ief", "image/ief"); m.put("jpeg", "image/jpeg"); m.put("jpg", "image/jpeg"); m.put("jpe", "image/jpeg"); m.put("ktx", "image/ktx"); m.put("png", "image/png"); m.put("btif", "image/prs.btif"); m.put("sgi", "image/sgi"); m.put("svg", "image/svg+xml"); m.put("svgz", "image/svg+xml"); m.put("tiff", "image/tiff"); m.put("tif", "image/tiff"); m.put("psd", "image/vnd.adobe.photoshop"); m.put("uvi", "image/vnd.dece.graphic"); m.put("uvvi", "image/vnd.dece.graphic"); m.put("uvg", "image/vnd.dece.graphic"); m.put("uvvg", "image/vnd.dece.graphic"); m.put("sub", "image/vnd.dvb.subtitle"); m.put("djvu", "image/vnd.djvu"); m.put("djv", "image/vnd.djvu"); m.put("dwg", "image/vnd.dwg"); m.put("dxf", "image/vnd.dxf"); m.put("fbs", "image/vnd.fastbidsheet"); m.put("fpx", "image/vnd.fpx"); m.put("fst", "image/vnd.fst"); m.put("mmr", "image/vnd.fujixerox.edmics-mmr"); m.put("rlc", "image/vnd.fujixerox.edmics-rlc"); m.put("mdi", "image/vnd.ms-modi"); m.put("wdp", "image/vnd.ms-photo"); m.put("npx", "image/vnd.net-fpx"); m.put("wbmp", "image/vnd.wap.wbmp"); m.put("xif", "image/vnd.xiff"); m.put("webp", "image/webp"); m.put("3ds", "image/x-3ds"); m.put("ras", "image/x-cmu-raster"); m.put("cmx", "image/x-cmx"); m.put("fh", "image/x-freehand"); m.put("fhc", "image/x-freehand"); m.put("fh4", "image/x-freehand"); m.put("fh5", "image/x-freehand"); m.put("fh7", "image/x-freehand"); m.put("ico", "image/x-icon"); m.put("sid", "image/x-mrsid-image"); m.put("pcx", "image/x-pcx"); m.put("pic", "image/x-pict"); m.put("pct", "image/x-pict"); m.put("pnm", "image/x-portable-anymap"); m.put("pbm", "image/x-portable-bitmap"); m.put("pgm", "image/x-portable-graymap"); m.put("ppm", "image/x-portable-pixmap"); m.put("rgb", "image/x-rgb"); m.put("tga", "image/x-tga"); m.put("xbm", "image/x-xbitmap"); m.put("xpm", "image/x-xpixmap"); m.put("xwd", "image/x-xwindowdump"); m.put("eml", "message/rfc822"); m.put("mime", "message/rfc822"); m.put("igs", "model/iges"); m.put("iges", "model/iges"); m.put("msh", "model/mesh"); m.put("mesh", "model/mesh"); m.put("silo", "model/mesh"); m.put("dae", "model/vnd.collada+xml"); m.put("dwf", "model/vnd.dwf"); m.put("gdl", "model/vnd.gdl"); m.put("gtw", "model/vnd.gtw"); m.put("mts", "model/vnd.mts"); m.put("vtu", "model/vnd.vtu"); m.put("wrl", "model/vrml"); m.put("vrml", "model/vrml"); m.put("x3db", "model/x3d+binary"); m.put("x3dbz", "model/x3d+binary"); m.put("x3dv", "model/x3d+vrml"); m.put("x3dvz", "model/x3d+vrml"); m.put("x3d", "model/x3d+xml"); m.put("x3dz", "model/x3d+xml"); m.put("appcache", "text/cache-manifest"); m.put("ics", "text/calendar"); m.put("ifb", "text/calendar"); m.put("css", "text/css"); m.put("csv", "text/csv"); m.put("html", "text/html"); m.put("htm", "text/html"); m.put("n3", "text/n3"); m.put("txt", "text/plain"); m.put("text", "text/plain"); m.put("conf", "text/plain"); m.put("def", "text/plain"); m.put("list", "text/plain"); m.put("log", "text/plain"); m.put("in", "text/plain"); m.put("dsc", "text/prs.lines.tag"); m.put("rtx", "text/richtext"); m.put("sgml", "text/sgml"); m.put("sgm", "text/sgml"); m.put("tsv", "text/tab-separated-values"); m.put("t", "text/troff"); m.put("tr", "text/troff"); m.put("roff", "text/troff"); m.put("man", "text/troff"); m.put("me", "text/troff"); m.put("ms", "text/troff"); m.put("ttl", "text/turtle"); m.put("uri", "text/uri-list"); m.put("uris", "text/uri-list"); m.put("urls", "text/uri-list"); m.put("vcard", "text/vcard"); m.put("curl", "text/vnd.curl"); m.put("dcurl", "text/vnd.curl.dcurl"); m.put("scurl", "text/vnd.curl.scurl"); m.put("mcurl", "text/vnd.curl.mcurl"); m.put("fly", "text/vnd.fly"); m.put("flx", "text/vnd.fmi.flexstor"); m.put("gv", "text/vnd.graphviz"); m.put("3dml", "text/vnd.in3d.3dml"); m.put("spot", "text/vnd.in3d.spot"); m.put("jad", "text/vnd.sun.j2me.app-descriptor"); m.put("wml", "text/vnd.wap.wml"); m.put("wmls", "text/vnd.wap.wmlscript"); m.put("s", "text/x-asm"); m.put("asm", "text/x-asm"); m.put("c", "text/x-c"); m.put("cc", "text/x-c"); m.put("cxx", "text/x-c"); m.put("cpp", "text/x-c"); m.put("h", "text/x-c"); m.put("hh", "text/x-c"); m.put("dic", "text/x-c"); m.put("f", "text/x-fortran"); m.put("for", "text/x-fortran"); m.put("f77", "text/x-fortran"); m.put("f90", "text/x-fortran"); m.put("java", "text/x-java-source"); m.put("opml", "text/x-opml"); m.put("p", "text/x-pascal"); m.put("pas", "text/x-pascal"); m.put("nfo", "text/x-nfo"); m.put("etx", "text/x-setext"); m.put("sfv", "text/x-sfv"); m.put("uu", "text/x-uuencode"); m.put("vcs", "text/x-vcalendar"); m.put("vcf", "text/x-vcard"); m.put("3gp", "video/3gpp"); m.put("3g2", "video/3gpp2"); m.put("h261", "video/h261"); m.put("h263", "video/h263"); m.put("h264", "video/h264"); m.put("jpgv", "video/jpeg"); m.put("jpm", "video/jpm"); m.put("jpgm", "video/jpm"); m.put("mj2", "video/mj2"); m.put("mjp2", "video/mj2"); m.put("mp4", "video/mp4"); m.put("mp4v", "video/mp4"); m.put("mpg4", "video/mp4"); m.put("mpeg", "video/mpeg"); m.put("mpg", "video/mpeg"); m.put("mpe", "video/mpeg"); m.put("m1v", "video/mpeg"); m.put("m2v", "video/mpeg"); m.put("ogv", "video/ogg"); m.put("qt", "video/quicktime"); m.put("mov", "video/quicktime"); m.put("uvh", "video/vnd.dece.hd"); m.put("uvvh", "video/vnd.dece.hd"); m.put("uvm", "video/vnd.dece.mobile"); m.put("uvvm", "video/vnd.dece.mobile"); m.put("uvp", "video/vnd.dece.pd"); m.put("uvvp", "video/vnd.dece.pd"); m.put("uvs", "video/vnd.dece.sd"); m.put("uvvs", "video/vnd.dece.sd"); m.put("uvv", "video/vnd.dece.video"); m.put("uvvv", "video/vnd.dece.video"); m.put("dvb", "video/vnd.dvb.file"); m.put("fvt", "video/vnd.fvt"); m.put("mxu", "video/vnd.mpegurl"); m.put("m4u", "video/vnd.mpegurl"); m.put("pyv", "video/vnd.ms-playready.media.pyv"); m.put("uvu", "video/vnd.uvvu.mp4"); m.put("uvvu", "video/vnd.uvvu.mp4"); m.put("viv", "video/vnd.vivo"); m.put("webm", "video/webm"); m.put("f4v", "video/x-f4v"); m.put("fli", "video/x-fli"); m.put("flv", "video/x-flv"); m.put("m4a", "audio/x-m4a"); m.put("m4v", "video/x-m4v"); m.put("mkv", "video/x-matroska"); m.put("mk3d", "video/x-matroska"); m.put("mks", "video/x-matroska"); m.put("mng", "video/x-mng"); m.put("asf", "video/x-ms-asf"); m.put("asx", "video/x-ms-asf"); m.put("vob", "video/x-ms-vob"); m.put("wm", "video/x-ms-wm"); m.put("wmv", "video/x-ms-wmv"); m.put("wmx", "video/x-ms-wmx"); m.put("wvx", "video/x-ms-wvx"); m.put("avi", "video/x-msvideo"); m.put("movie", "video/x-sgi-movie"); m.put("smv", "video/x-smv"); m.put("ice", "x-conference/x-cooltalk"); } public static String getMimeTypeForExtension(String ext) { return m.get(ext); } public static String getMimeTypeForFilename(String filename) { int li = filename.lastIndexOf('.'); if (li != -1 && li != filename.length() - 1) { String ext = filename.substring(li + 1, filename.length()); return MimeMapping.getMimeTypeForExtension(ext); } return null; } }
eclipse-vertx/vert.x
src/main/java/io/vertx/core/http/impl/MimeMapping.java
41,676
/* * Copyright 2017 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ package org.webrtc; import static org.webrtc.MediaCodecUtils.EXYNOS_PREFIX; import static org.webrtc.MediaCodecUtils.EXYNOS_PREFIX_C2; import static org.webrtc.MediaCodecUtils.HISI_PREFIX; import static org.webrtc.MediaCodecUtils.INTEL_PREFIX; import static org.webrtc.MediaCodecUtils.QCOM_PREFIX; import static org.webrtc.MediaCodecUtils.SOFTWARE_IMPLEMENTATION_PREFIXES; import android.media.MediaCodecInfo; import android.os.Build; import androidx.annotation.Nullable; import org.telegram.messenger.voip.Instance; import org.telegram.messenger.voip.VoIPService; import java.util.ArrayList; import java.util.List; /** Factory for android hardware video encoders. */ @SuppressWarnings("deprecation") // API 16 requires the use of deprecated methods. public class HardwareVideoEncoderFactory implements VideoEncoderFactory { private static final String TAG = "HardwareVideoEncoderFactory"; // Forced key frame interval - used to reduce color distortions on Qualcomm platforms. private static final int QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_L_MS = 15000; private static final int QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_M_MS = 20000; private static final int QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_N_MS = 15000; @Nullable private final EglBase14.Context sharedContext; private final boolean enableIntelVp8Encoder; private final boolean enableH264HighProfile; @Nullable private final Predicate<MediaCodecInfo> codecAllowedPredicate; /** * Creates a HardwareVideoEncoderFactory that supports surface texture encoding. * * @param sharedContext The textures generated will be accessible from this context. May be null, * this disables texture support. * @param enableIntelVp8Encoder true if Intel's VP8 encoder enabled. * @param enableH264HighProfile true if H264 High Profile enabled. */ public HardwareVideoEncoderFactory( EglBase.Context sharedContext, boolean enableIntelVp8Encoder, boolean enableH264HighProfile) { this(sharedContext, enableIntelVp8Encoder, enableH264HighProfile, /* codecAllowedPredicate= */ null); } /** * Creates a HardwareVideoEncoderFactory that supports surface texture encoding. * * @param sharedContext The textures generated will be accessible from this context. May be null, * this disables texture support. * @param enableIntelVp8Encoder true if Intel's VP8 encoder enabled. * @param enableH264HighProfile true if H264 High Profile enabled. * @param codecAllowedPredicate optional predicate to filter codecs. All codecs are allowed * when predicate is not provided. */ public HardwareVideoEncoderFactory(EglBase.Context sharedContext, boolean enableIntelVp8Encoder, boolean enableH264HighProfile, @Nullable Predicate<MediaCodecInfo> codecAllowedPredicate) { // Texture mode requires EglBase14. if (sharedContext instanceof EglBase14.Context) { this.sharedContext = (EglBase14.Context) sharedContext; } else { Logging.w(TAG, "No shared EglBase.Context. Encoders will not use texture mode."); this.sharedContext = null; } this.enableIntelVp8Encoder = enableIntelVp8Encoder; this.enableH264HighProfile = enableH264HighProfile; this.codecAllowedPredicate = codecAllowedPredicate; } @Deprecated public HardwareVideoEncoderFactory(boolean enableIntelVp8Encoder, boolean enableH264HighProfile) { this(null, enableIntelVp8Encoder, enableH264HighProfile); } @Nullable @Override public VideoEncoder createEncoder(VideoCodecInfo input) { // HW encoding is not supported below Android Kitkat. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return null; } VideoCodecMimeType type = VideoCodecMimeType.valueOf(input.name); MediaCodecInfo info = findCodecForType(type); if (info == null) { return null; } String codecName = info.getName(); String mime = type.mimeType(); Integer surfaceColorFormat = MediaCodecUtils.selectColorFormat( MediaCodecUtils.TEXTURE_COLOR_FORMATS, info.getCapabilitiesForType(mime)); Integer yuvColorFormat = MediaCodecUtils.selectColorFormat( MediaCodecUtils.ENCODER_COLOR_FORMATS, info.getCapabilitiesForType(mime)); if (type == VideoCodecMimeType.H264) { boolean isHighProfile = H264Utils.isSameH264Profile( input.params, MediaCodecUtils.getCodecProperties(type, /* highProfile= */ true)); boolean isBaselineProfile = H264Utils.isSameH264Profile( input.params, MediaCodecUtils.getCodecProperties(type, /* highProfile= */ false)); if (!isHighProfile && !isBaselineProfile) { return null; } if (isHighProfile && !isH264HighProfileSupported(info)) { return null; } } return new HardwareVideoEncoder(new MediaCodecWrapperFactoryImpl(), codecName, type, surfaceColorFormat, yuvColorFormat, input.params, getKeyFrameIntervalSec(type), getForcedKeyFrameIntervalMs(type, codecName), createBitrateAdjuster(type, codecName), sharedContext); } @Override public VideoCodecInfo[] getSupportedCodecs() { // HW encoding is not supported below Android Kitkat. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT || VoIPService.getSharedInstance() != null && VoIPService.getSharedInstance().groupCall != null) { return new VideoCodecInfo[0]; } List<VideoCodecInfo> supportedCodecInfos = new ArrayList<VideoCodecInfo>(); // Generate a list of supported codecs in order of preference: // VP8, VP9, H.265(optional), H264 (high profile), and H264 (baseline profile). for (VideoCodecMimeType type : new VideoCodecMimeType[] { VideoCodecMimeType.VP8, VideoCodecMimeType.VP9, VideoCodecMimeType.H264, VideoCodecMimeType.H265}) { MediaCodecInfo codec = findCodecForType(type); if (codec != null) { String name = type.name(); // TODO(sakal): Always add H264 HP once WebRTC correctly removes codecs that are not // supported by the decoder. if (type == VideoCodecMimeType.H264 && isH264HighProfileSupported(codec)) { supportedCodecInfos.add(new VideoCodecInfo( name, MediaCodecUtils.getCodecProperties(type, /* highProfile= */ true))); } supportedCodecInfos.add(new VideoCodecInfo( name, MediaCodecUtils.getCodecProperties(type, /* highProfile= */ false))); } } return supportedCodecInfos.toArray(new VideoCodecInfo[supportedCodecInfos.size()]); } private @Nullable MediaCodecInfo findCodecForType(VideoCodecMimeType type) { ArrayList<MediaCodecInfo> infos = MediaCodecUtils.getSortedCodecsList(); int count = infos.size(); MediaCodecInfo info2 = null; for (int i = 0; i < count; ++i) { MediaCodecInfo info = infos.get(i); if (info == null || !info.isEncoder()) { continue; } if (isSupportedCodec(info, type, true)) { return info; } if (info2 == null && isSupportedCodec(info, type, false)) { info2 = info; } } return info2; } // Returns true if the given MediaCodecInfo indicates a supported encoder for the given type. private boolean isSupportedCodec(MediaCodecInfo info, VideoCodecMimeType type, boolean ensureHardwareSupportedInSdk) { if (!MediaCodecUtils.codecSupportsType(info, type)) { return false; } // Check for a supported color format. if (MediaCodecUtils.selectColorFormat( MediaCodecUtils.ENCODER_COLOR_FORMATS, info.getCapabilitiesForType(type.mimeType())) == null) { return false; } return isHardwareSupportedInCurrentSdk(info, type, ensureHardwareSupportedInSdk) && isMediaCodecAllowed(info); } // Returns true if the given MediaCodecInfo indicates a hardware module that is supported on the // current SDK. private boolean isHardwareSupportedInCurrentSdk(MediaCodecInfo info, VideoCodecMimeType type, boolean ensureHardwareSupported) { if (VoIPService.getSharedInstance() != null && VoIPService.getSharedInstance().groupCall != null) { return false; } Instance.ServerConfig config = Instance.getGlobalServerConfig(); if (!config.enable_h264_encoder && !config.enable_h265_encoder && !config.enable_vp8_encoder && !config.enable_vp9_encoder) { return false; } switch (type) { case VP8: return isHardwareSupportedInCurrentSdkVp8(info, ensureHardwareSupported); case VP9: return isHardwareSupportedInCurrentSdkVp9(info, ensureHardwareSupported); case H264: return isHardwareSupportedInCurrentSdkH264(info); case H265: return isHardwareSupportedInCurrentSdkH265(info); } return false; } private boolean isHardwareSupportedInCurrentSdkVp8(MediaCodecInfo info, boolean ensureHardwareSupproted) { if (!Instance.getGlobalServerConfig().enable_vp8_encoder) { return false; } String name = info.getName(); // QCOM Vp8 encoder is supported in KITKAT or later. if ((name.startsWith(QCOM_PREFIX) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) // Hisi VP8 encoder seems to be supported. Needs more testing. || (name.startsWith(HISI_PREFIX) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) // Exynos VP8 encoder is supported in M or later. || (name.startsWith(EXYNOS_PREFIX) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) // Intel Vp8 encoder is supported in LOLLIPOP or later, with the intel encoder enabled. || (name.startsWith(INTEL_PREFIX) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && enableIntelVp8Encoder) || ((name.startsWith(EXYNOS_PREFIX_C2) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M))) { return true; } if (!ensureHardwareSupproted) { for (int i = 0; i < SOFTWARE_IMPLEMENTATION_PREFIXES.length; i++) { if (name.startsWith(SOFTWARE_IMPLEMENTATION_PREFIXES[i])) { return true; } } } return false; } private boolean isHardwareSupportedInCurrentSdkVp9(MediaCodecInfo info, boolean ensureHardwareSupproted) { if (!Instance.getGlobalServerConfig().enable_vp9_encoder) { return false; } String name = info.getName(); if ((name.startsWith(QCOM_PREFIX) || name.startsWith(EXYNOS_PREFIX) || name.startsWith(HISI_PREFIX)) // Both QCOM and Exynos VP9 encoders are supported in N or later. && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return true; } if (!ensureHardwareSupproted) { for (int i = 0; i < SOFTWARE_IMPLEMENTATION_PREFIXES.length; i++) { if (name.startsWith(SOFTWARE_IMPLEMENTATION_PREFIXES[i])) { return true; } } } return false; } private boolean isHardwareSupportedInCurrentSdkH264(MediaCodecInfo info) { if (!Instance.getGlobalServerConfig().enable_h264_encoder) { return false; } String name = info.getName(); // QCOM H264 encoder is supported in KITKAT or later. return (name.startsWith(QCOM_PREFIX) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) // Exynos H264 encoder is supported in LOLLIPOP or later. || (name.startsWith(EXYNOS_PREFIX) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP); } private boolean isHardwareSupportedInCurrentSdkH265(MediaCodecInfo info) { if (!Instance.getGlobalServerConfig().enable_h265_encoder) { return false; } String name = info.getName(); // QCOM H265 encoder is supported in KITKAT or later. return (name.startsWith(QCOM_PREFIX) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) // Exynos H265 encoder is supported in LOLLIPOP or later. || (name.startsWith(EXYNOS_PREFIX) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) // Hisi VP8 encoder seems to be supported. Needs more testing. /*|| (name.startsWith(HISI_PREFIX) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)*/; } private boolean isMediaCodecAllowed(MediaCodecInfo info) { if (codecAllowedPredicate == null) { return true; } return codecAllowedPredicate.test(info); } private int getKeyFrameIntervalSec(VideoCodecMimeType type) { switch (type) { case VP8: // Fallthrough intended. case VP9: return 100; case H264: case H265: return 20; } throw new IllegalArgumentException("Unsupported VideoCodecMimeType " + type); } private int getForcedKeyFrameIntervalMs(VideoCodecMimeType type, String codecName) { if (type == VideoCodecMimeType.VP8 && codecName.startsWith(QCOM_PREFIX)) { if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP || Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1) { return QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_L_MS; } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) { return QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_M_MS; } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) { return QCOM_VP8_KEY_FRAME_INTERVAL_ANDROID_N_MS; } } // Other codecs don't need key frame forcing. return 0; } private BitrateAdjuster createBitrateAdjuster(VideoCodecMimeType type, String codecName) { if (codecName.startsWith(EXYNOS_PREFIX)) { if (type == VideoCodecMimeType.VP8) { // Exynos VP8 encoders need dynamic bitrate adjustment. return new DynamicBitrateAdjuster(); } else { // Exynos VP9 and H264 encoders need framerate-based bitrate adjustment. return new FramerateBitrateAdjuster(); } } // Other codecs don't need bitrate adjustment. return new BaseBitrateAdjuster(); } private boolean isH264HighProfileSupported(MediaCodecInfo info) { return enableH264HighProfile && Build.VERSION.SDK_INT > Build.VERSION_CODES.M && info.getName().startsWith(EXYNOS_PREFIX); } }
flyun/chatAir
TMessagesProj/src/main/java/org/webrtc/HardwareVideoEncoderFactory.java
41,677
package org.telegram.messenger.voip; import com.google.android.exoplayer2.util.Util; import org.json.JSONException; import org.json.JSONObject; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.BuildVars; import org.telegram.messenger.FileLog; import org.webrtc.ContextUtils; import org.webrtc.VideoSink; import java.util.Arrays; import java.util.List; public final class Instance { public static final List<String> AVAILABLE_VERSIONS = Arrays.asList("2.4.4", "2.7.7", "5.0.0", "6.0.0", "7.0.0", "8.0.0", "9.0.0", "10.0.0", "11.0.0"); public static final int AUDIO_STATE_MUTED = 0; public static final int AUDIO_STATE_ACTIVE = 1; public static final int VIDEO_STATE_INACTIVE = 0; public static final int VIDEO_STATE_PAUSED = 1; public static final int VIDEO_STATE_ACTIVE = 2; //region Constants public static final int NET_TYPE_UNKNOWN = 0; public static final int NET_TYPE_GPRS = 1; public static final int NET_TYPE_EDGE = 2; public static final int NET_TYPE_3G = 3; public static final int NET_TYPE_HSPA = 4; public static final int NET_TYPE_LTE = 5; public static final int NET_TYPE_WIFI = 6; public static final int NET_TYPE_ETHERNET = 7; public static final int NET_TYPE_OTHER_HIGH_SPEED = 8; public static final int NET_TYPE_OTHER_LOW_SPEED = 9; public static final int NET_TYPE_DIALUP = 10; public static final int NET_TYPE_OTHER_MOBILE = 11; public static final int ENDPOINT_TYPE_INET = 0; public static final int ENDPOINT_TYPE_LAN = 1; public static final int ENDPOINT_TYPE_UDP_RELAY = 2; public static final int ENDPOINT_TYPE_TCP_RELAY = 3; public static final int STATE_WAIT_INIT = 1; public static final int STATE_WAIT_INIT_ACK = 2; public static final int STATE_ESTABLISHED = 3; public static final int STATE_FAILED = 4; public static final int STATE_RECONNECTING = 5; public static final int DATA_SAVING_NEVER = 0; public static final int DATA_SAVING_MOBILE = 1; public static final int DATA_SAVING_ALWAYS = 2; public static final int DATA_SAVING_ROAMING = 3; public static final int PEER_CAP_GROUP_CALLS = 1; // Java-side Errors public static final String ERROR_CONNECTION_SERVICE = "ERROR_CONNECTION_SERVICE"; public static final String ERROR_INSECURE_UPGRADE = "ERROR_INSECURE_UPGRADE"; public static final String ERROR_LOCALIZED = "ERROR_LOCALIZED"; public static final String ERROR_PRIVACY = "ERROR_PRIVACY"; public static final String ERROR_PEER_OUTDATED = "ERROR_PEER_OUTDATED"; // Native-side Errors public static final String ERROR_UNKNOWN = "ERROR_UNKNOWN"; public static final String ERROR_INCOMPATIBLE = "ERROR_INCOMPATIBLE"; public static final String ERROR_TIMEOUT = "ERROR_TIMEOUT"; public static final String ERROR_AUDIO_IO = "ERROR_AUDIO_IO"; //endregion private static ServerConfig globalServerConfig = new ServerConfig(new JSONObject()); private static int bufferSize; private static NativeInstance instance; private Instance() { } public static ServerConfig getGlobalServerConfig() { return globalServerConfig; } public static void setGlobalServerConfig(String serverConfigJson) { try { globalServerConfig = new ServerConfig(new JSONObject(serverConfigJson)); if (instance != null) { instance.setGlobalServerConfig(serverConfigJson); } } catch (JSONException e) { if (BuildVars.LOGS_ENABLED) { FileLog.e("failed to parse tgvoip server config", e); } } } public static void destroyInstance() { instance = null; } public static NativeInstance makeInstance(String version, Config config, String persistentStateFilePath, Endpoint[] endpoints, Proxy proxy, int networkType, EncryptionKey encryptionKey, VideoSink remoteSink, long videoCapturer, NativeInstance.AudioLevelsCallback audioLevelsCallback) { if (!"2.4.4".equals(version)) { ContextUtils.initialize(ApplicationLoader.applicationContext); } instance = NativeInstance.make(version, config, persistentStateFilePath, endpoints, proxy, networkType, encryptionKey, remoteSink, videoCapturer, audioLevelsCallback); setGlobalServerConfig(globalServerConfig.jsonObject.toString()); setBufferSize(bufferSize); return instance; } public static void setBufferSize(int size) { bufferSize = size; if (instance != null) { instance.setBufferSize(size); } } public static int getConnectionMaxLayer() { return 92; } public static String getVersion() { return instance != null ? instance.getVersion() : null; } private static void checkHasDelegate() { if (instance == null) { throw new IllegalStateException("tgvoip version is not set"); } } public interface OnStateUpdatedListener { void onStateUpdated(int state, boolean inTransition); } public interface OnSignalBarsUpdatedListener { void onSignalBarsUpdated(int signalBars); } public interface OnSignalingDataListener { void onSignalingData(byte[] data); } public interface OnRemoteMediaStateUpdatedListener { void onMediaStateUpdated(int audioState, int videoState); } public static final class Config { public final double initializationTimeout; public final double receiveTimeout; public final int dataSaving; public final boolean enableP2p; public final boolean enableAec; public final boolean enableNs; public final boolean enableAgc; public final boolean enableCallUpgrade; public final String logPath; public final String statsLogPath; public final int maxApiLayer; public final boolean enableSm; public Config(double initializationTimeout, double receiveTimeout, int dataSaving, boolean enableP2p, boolean enableAec, boolean enableNs, boolean enableAgc, boolean enableCallUpgrade, boolean enableSm, String logPath, String statsLogPath, int maxApiLayer) { this.initializationTimeout = initializationTimeout; this.receiveTimeout = receiveTimeout; this.dataSaving = dataSaving; this.enableP2p = enableP2p; this.enableAec = enableAec; this.enableNs = enableNs; this.enableAgc = enableAgc; this.enableCallUpgrade = enableCallUpgrade; this.logPath = logPath; this.statsLogPath = statsLogPath; this.maxApiLayer = maxApiLayer; this.enableSm = enableSm; } @Override public String toString() { return "Config{" + "initializationTimeout=" + initializationTimeout + ", receiveTimeout=" + receiveTimeout + ", dataSaving=" + dataSaving + ", enableP2p=" + enableP2p + ", enableAec=" + enableAec + ", enableNs=" + enableNs + ", enableAgc=" + enableAgc + ", enableCallUpgrade=" + enableCallUpgrade + ", logPath='" + logPath + '\'' + ", statsLogPath='" + statsLogPath + '\'' + ", maxApiLayer=" + maxApiLayer + ", enableSm=" + enableSm + '}'; } } public static final class Endpoint { public final boolean isRtc; public final long id; public final String ipv4; public final String ipv6; public final int port; public final int type; public final byte[] peerTag; public final boolean turn; public final boolean stun; public final String username; public final String password; public final boolean tcp; public int reflectorId; public Endpoint(boolean isRtc, long id, String ipv4, String ipv6, int port, int type, byte[] peerTag, boolean turn, boolean stun, String username, String password, boolean tcp) { this.isRtc = isRtc; this.id = id; this.ipv4 = ipv4; this.ipv6 = ipv6; this.port = port; this.type = type; this.peerTag = peerTag; this.turn = turn; this.stun = stun; if (isRtc) { this.username = username; this.password = password; } else if (peerTag != null) { this.username = "reflector"; this.password = Util.toHexString(peerTag); } else { this.username = null; this.password = null; } this.tcp = tcp; } @Override public String toString() { return "Endpoint{" + "id=" + id + ", ipv4='" + ipv4 + '\'' + ", ipv6='" + ipv6 + '\'' + ", port=" + port + ", type=" + type + ", peerTag=" + Arrays.toString(peerTag) + ", turn=" + turn + ", stun=" + stun + ", username=" + username + ", password=" + password + ", tcp=" + tcp + '}'; } } public static final class Proxy { public final String host; public final int port; public final String login; public final String password; public Proxy(String host, int port, String login, String password) { this.host = host; this.port = port; this.login = login; this.password = password; } @Override public String toString() { return "Proxy{" + "host='" + host + '\'' + ", port=" + port + ", login='" + login + '\'' + ", password='" + password + '\'' + '}'; } } public static final class EncryptionKey { public final byte[] value; public final boolean isOutgoing; public EncryptionKey(byte[] value, boolean isOutgoing) { this.value = value; this.isOutgoing = isOutgoing; } @Override public String toString() { return "EncryptionKey{" + "value=" + Arrays.toString(value) + ", isOutgoing=" + isOutgoing + '}'; } } public static final class FinalState { public final byte[] persistentState; public String debugLog; public final TrafficStats trafficStats; public final boolean isRatingSuggested; public FinalState(byte[] persistentState, String debugLog, TrafficStats trafficStats, boolean isRatingSuggested) { this.persistentState = persistentState; this.debugLog = debugLog; this.trafficStats = trafficStats; this.isRatingSuggested = isRatingSuggested; } @Override public String toString() { return "FinalState{" + "persistentState=" + Arrays.toString(persistentState) + ", debugLog='" + debugLog + '\'' + ", trafficStats=" + trafficStats + ", isRatingSuggested=" + isRatingSuggested + '}'; } } public static final class TrafficStats { public final long bytesSentWifi; public final long bytesReceivedWifi; public final long bytesSentMobile; public final long bytesReceivedMobile; public TrafficStats(long bytesSentWifi, long bytesReceivedWifi, long bytesSentMobile, long bytesReceivedMobile) { this.bytesSentWifi = bytesSentWifi; this.bytesReceivedWifi = bytesReceivedWifi; this.bytesSentMobile = bytesSentMobile; this.bytesReceivedMobile = bytesReceivedMobile; } @Override public String toString() { return "TrafficStats{" + "bytesSentWifi=" + bytesSentWifi + ", bytesReceivedWifi=" + bytesReceivedWifi + ", bytesSentMobile=" + bytesSentMobile + ", bytesReceivedMobile=" + bytesReceivedMobile + '}'; } } public static final class Fingerprint { public final String hash; public final String setup; public final String fingerprint; public Fingerprint(String hash, String setup, String fingerprint) { this.hash = hash; this.setup = setup; this.fingerprint = fingerprint; } @Override public String toString() { return "Fingerprint{" + "hash=" + hash + ", setup=" + setup + ", fingerprint=" + fingerprint + '}'; } } public static final class Candidate { public final String port; public final String protocol; public final String network; public final String generation; public final String id; public final String component; public final String foundation; public final String priority; public final String ip; public final String type; public final String tcpType; public final String relAddr; public final String relPort; public Candidate(String port, String protocol, String network, String generation, String id, String component, String foundation, String priority, String ip, String type, String tcpType, String relAddr, String relPort) { this.port = port; this.protocol = protocol; this.network = network; this.generation = generation; this.id = id; this.component = component; this.foundation = foundation; this.priority = priority; this.ip = ip; this.type = type; this.tcpType = tcpType; this.relAddr = relAddr; this.relPort = relPort; } @Override public String toString() { return "Candidate{" + "port=" + port + ", protocol=" + protocol + ", network=" + network + ", generation=" + generation + ", id=" + id + ", component=" + component + ", foundation=" + foundation + ", priority=" + priority + ", ip=" + ip + ", type=" + type + ", tcpType=" + tcpType + ", relAddr=" + relAddr + ", relPort=" + relPort + '}'; } } public static final class ServerConfig { public final boolean useSystemNs; public final boolean useSystemAec; public final boolean enableStunMarking; public final double hangupUiTimeout; public final boolean enable_vp8_encoder; public final boolean enable_vp8_decoder; public final boolean enable_vp9_encoder; public final boolean enable_vp9_decoder; public final boolean enable_h265_encoder; public final boolean enable_h265_decoder; public final boolean enable_h264_encoder; public final boolean enable_h264_decoder; private final JSONObject jsonObject; private ServerConfig(JSONObject jsonObject) { this.jsonObject = jsonObject; this.useSystemNs = jsonObject.optBoolean("use_system_ns", true); this.useSystemAec = jsonObject.optBoolean("use_system_aec", true); this.enableStunMarking = jsonObject.optBoolean("voip_enable_stun_marking", false); this.hangupUiTimeout = jsonObject.optDouble("hangup_ui_timeout", 5); this.enable_vp8_encoder = jsonObject.optBoolean("enable_vp8_encoder", true); this.enable_vp8_decoder = jsonObject.optBoolean("enable_vp8_decoder", true); this.enable_vp9_encoder = jsonObject.optBoolean("enable_vp9_encoder", true); this.enable_vp9_decoder = jsonObject.optBoolean("enable_vp9_decoder", true); this.enable_h265_encoder = jsonObject.optBoolean("enable_h265_encoder", true); this.enable_h265_decoder = jsonObject.optBoolean("enable_h265_decoder", true); this.enable_h264_encoder = jsonObject.optBoolean("enable_h264_encoder", true); this.enable_h264_decoder = jsonObject.optBoolean("enable_h264_decoder", true); } public String getString(String key) { return getString(key, ""); } public String getString(String key, String fallback) { return jsonObject.optString(key, fallback); } } }
NekoX-Dev/NekoX
TMessagesProj/src/main/java/org/telegram/messenger/voip/Instance.java
41,678
package org.telegram.ui.Components; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PointF; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.text.TextUtils; import android.util.SparseArray; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import androidx.annotation.Nullable; import androidx.recyclerview.widget.RecyclerView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.DialogObject; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.ImageLocation; import org.telegram.messenger.ImageReceiver; import org.telegram.messenger.MessagesController; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.UserConfig; import org.telegram.messenger.UserObject; import org.telegram.messenger.Utilities; import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.ActionBar; import org.telegram.ui.PinchToZoomHelper; import org.telegram.ui.ProfileActivity; import java.util.ArrayList; public class ProfileGalleryView extends CircularViewPager implements NotificationCenter.NotificationCenterDelegate { private final PointF downPoint = new PointF(); private final int touchSlop; private final ActionBar parentActionBar; private boolean isScrollingListView = true; private boolean isSwipingViewPager = true; private final RecyclerListView parentListView; private ViewPagerAdapter adapter; private final int parentClassGuid; private long dialogId; private TLRPC.ChatFull chatInfo; private final Callback callback; public boolean scrolledByUser; private boolean isDownReleased; private final boolean isProfileFragment; private ImageLocation uploadingImageLocation; private int currentAccount = UserConfig.selectedAccount; Path path = new Path(); RectF rect = new RectF(); float[] radii = new float[8]; private ImageLocation prevImageLocation; private ImageLocation prevThumbLocation; private VectorAvatarThumbDrawable prevVectorAvatarThumbDrawable; private ArrayList<String> videoFileNames = new ArrayList<>(); private ArrayList<String> thumbsFileNames = new ArrayList<>(); private ArrayList<TLRPC.Photo> photos = new ArrayList<>(); private ArrayList<ImageLocation> videoLocations = new ArrayList<>(); private ArrayList<ImageLocation> imagesLocations = new ArrayList<>(); private ArrayList<ImageLocation> thumbsLocations = new ArrayList<>(); private ArrayList<VectorAvatarThumbDrawable> vectorAvatars = new ArrayList<>(); private ArrayList<Integer> imagesLocationsSizes = new ArrayList<>(); private ArrayList<Float> imagesUploadProgress = new ArrayList<>(); private int settingMainPhoto; private final SparseArray<RadialProgress2> radialProgresses = new SparseArray<>(); private boolean createThumbFromParent = true; private boolean forceResetPosition; private boolean invalidateWithParent; PinchToZoomHelper pinchToZoomHelper; private boolean hasActiveVideo; private int customAvatarIndex = -1; private int fallbackPhotoIndex = -1; private TLRPC.TL_groupCallParticipant participant; private int imagesLayerNum; public void setHasActiveVideo(boolean hasActiveVideo) { this.hasActiveVideo = hasActiveVideo; } public View findVideoActiveView() { if (!hasActiveVideo) { return null; } for (int i = 0; i < getChildCount(); i++) { View view = getChildAt(i); if (view instanceof TextureStubView) { return view; } } return null; } public void clearPrevImages() { prevImageLocation = null; } private static class Item { boolean isActiveVideo; private View textureViewStubView; private AvatarImageView imageView; } public interface Callback { void onDown(boolean left); void onRelease(); void onPhotosLoaded(); void onVideoSet(); } private int roundTopRadius; private int roundBottomRadius; int selectedPage; int prevPage; public ProfileGalleryView(Context context, ActionBar parentActionBar, RecyclerListView parentListView, Callback callback) { super(context); setOffscreenPageLimit(2); this.isProfileFragment = false; this.parentListView = parentListView; this.parentClassGuid = ConnectionsManager.generateClassGuid(); this.parentActionBar = parentActionBar; this.touchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); this.callback = callback; addOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { checkCustomAvatar(position, positionOffset); if (positionOffsetPixels == 0) { position = adapter.getRealPosition(position); if (hasActiveVideo) { position--; } BackupImageView currentView = getCurrentItemView(); int count = getChildCount(); for (int a = 0; a < count; a++) { View child = getChildAt(a); if (!(child instanceof BackupImageView)) { continue; } int p = adapter.getRealPosition(adapter.imageViews.indexOf(child)); if (hasActiveVideo) { p--; } BackupImageView imageView = (BackupImageView) child; ImageReceiver imageReceiver = imageView.getImageReceiver(); boolean currentAllow = imageReceiver.getAllowStartAnimation(); if (p == position) { if (!currentAllow) { imageReceiver.setAllowStartAnimation(true); imageReceiver.startAnimation(); } ImageLocation location = videoLocations.get(p); if (location != null) { FileLoader.getInstance(currentAccount).setForceStreamLoadingFile(location.location, "mp4"); } } else { if (currentAllow) { AnimatedFileDrawable fileDrawable = imageReceiver.getAnimation(); if (fileDrawable != null) { ImageLocation location = videoLocations.get(p); if (location != null) { fileDrawable.seekTo(location.videoSeekTo, false, true); } } imageReceiver.setAllowStartAnimation(false); imageReceiver.stopAnimation(); } } } } } @Override public void onPageSelected(int position) { if (position != selectedPage) { prevPage = selectedPage; selectedPage = position; } } @Override public void onPageScrollStateChanged(int state) { } }); setAdapter(adapter = new ViewPagerAdapter(getContext(), null, parentActionBar)); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.dialogPhotosLoaded); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.fileLoaded); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.fileLoadProgressChanged); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.reloadDialogPhotos); } private void checkCustomAvatar(int position, float positionOffset) { float progressToCustomAvatar = 0; if (customAvatarIndex >= 0 || fallbackPhotoIndex >= 0) { int index = customAvatarIndex >= 0 ? customAvatarIndex : fallbackPhotoIndex; int p = adapter.getRealPosition(position); if (hasActiveVideo) { p--; } if (p == index) { progressToCustomAvatar = 1f - positionOffset; } else if ((p - 1) % getRealCount() == index) { progressToCustomAvatar = 1f - positionOffset - 1f; } else if ((p + 1) % getRealCount() == index) { progressToCustomAvatar = 1f - positionOffset + 1f; } if (progressToCustomAvatar > 1f) { progressToCustomAvatar = 2f - progressToCustomAvatar; } progressToCustomAvatar = Utilities.clamp(progressToCustomAvatar, 1f ,0); } setCustomAvatarProgress(progressToCustomAvatar); } protected void setCustomAvatarProgress(float progress) { } public void setImagesLayerNum(int value) { imagesLayerNum = value; } public ProfileGalleryView(Context context, long dialogId, ActionBar parentActionBar, RecyclerListView parentListView, ProfileActivity.AvatarImageView parentAvatarImageView, int parentClassGuid, Callback callback) { super(context); setVisibility(View.GONE); setOverScrollMode(View.OVER_SCROLL_NEVER); setOffscreenPageLimit(2); this.isProfileFragment = true; this.dialogId = dialogId; this.parentListView = parentListView; this.parentClassGuid = parentClassGuid; this.parentActionBar = parentActionBar; setAdapter(adapter = new ViewPagerAdapter(getContext(), parentAvatarImageView, parentActionBar)); this.touchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); this.callback = callback; addOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { checkCustomAvatar(position, positionOffset); if (positionOffsetPixels == 0) { position = adapter.getRealPosition(position); BackupImageView currentView = getCurrentItemView(); int count = getChildCount(); for (int a = 0; a < count; a++) { View child = getChildAt(a); if (!(child instanceof BackupImageView)) { continue; } int p = adapter.getRealPosition(adapter.imageViews.indexOf(child)); BackupImageView imageView = (BackupImageView) child; ImageReceiver imageReceiver = imageView.getImageReceiver(); boolean currentAllow = imageReceiver.getAllowStartAnimation(); if (p == position) { if (!currentAllow) { imageReceiver.setAllowStartAnimation(true); imageReceiver.startAnimation(); } ImageLocation location = videoLocations.get(p); if (location != null) { FileLoader.getInstance(currentAccount).setForceStreamLoadingFile(location.location, "mp4"); } } else { if (currentAllow) { AnimatedFileDrawable fileDrawable = imageReceiver.getAnimation(); if (fileDrawable != null) { ImageLocation location = videoLocations.get(p); if (location != null) { fileDrawable.seekTo(location.videoSeekTo, false, true); } } imageReceiver.setAllowStartAnimation(false); imageReceiver.stopAnimation(); } } } } } @Override public void onPageSelected(int position) { if (position != selectedPage) { prevPage = selectedPage; selectedPage = position; } } @Override public void onPageScrollStateChanged(int state) { } }); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.dialogPhotosLoaded); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.fileLoaded); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.fileLoadProgressChanged); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.reloadDialogPhotos); MessagesController.getInstance(currentAccount).loadDialogPhotos(dialogId, 80, 0, true, parentClassGuid); } public void onDestroy() { NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.dialogPhotosLoaded); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileLoaded); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileLoadProgressChanged); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileLoadProgressChanged); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.reloadDialogPhotos); int count = getChildCount(); for (int a = 0; a < count; a++) { View child = getChildAt(a); if (!(child instanceof BackupImageView)) { continue; } BackupImageView imageView = (BackupImageView) child; if (imageView.getImageReceiver().hasStaticThumb()) { Drawable drawable = imageView.getImageReceiver().getDrawable(); if (drawable instanceof AnimatedFileDrawable) { ((AnimatedFileDrawable) drawable).removeSecondParentView(imageView); } } } } public void setAnimatedFileMaybe(AnimatedFileDrawable drawable) { if (drawable == null || adapter == null) { return; } int count = getChildCount(); for (int a = 0; a < count; a++) { View child = getChildAt(a); if (!(child instanceof BackupImageView)) { continue; } int p = adapter.getRealPosition(adapter.imageViews.indexOf(child)); if (p != 0) { continue; } BackupImageView imageView = (BackupImageView) child; ImageReceiver imageReceiver = imageView.getImageReceiver(); AnimatedFileDrawable currentDrawable = imageReceiver.getAnimation(); if (currentDrawable == drawable) { continue; } if (currentDrawable != null) { currentDrawable.removeSecondParentView(imageView); } imageView.setImageDrawable(drawable); drawable.addSecondParentView(this); drawable.setInvalidateParentViewWithSecond(true); } } @Override public boolean onTouchEvent(MotionEvent ev) { if (adapter == null) { return false; } if (parentListView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE && !isScrollingListView && isSwipingViewPager) { isSwipingViewPager = false; final MotionEvent cancelEvent = MotionEvent.obtain(ev); cancelEvent.setAction(MotionEvent.ACTION_CANCEL); super.onTouchEvent(cancelEvent); cancelEvent.recycle(); return false; } final int action = ev.getAction(); if (pinchToZoomHelper != null && getCurrentItemView() != null) { if (action != MotionEvent.ACTION_DOWN && isDownReleased && !pinchToZoomHelper.isInOverlayMode()) { pinchToZoomHelper.checkPinchToZoom(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0, 0, 0), this, getCurrentItemView().getImageReceiver(), null); } else if (pinchToZoomHelper.checkPinchToZoom(ev, this, getCurrentItemView().getImageReceiver(), null)) { if (!isDownReleased) { isDownReleased = true; callback.onRelease(); } return true; } } if (action == MotionEvent.ACTION_DOWN) { isScrollingListView = true; isSwipingViewPager = true; scrolledByUser = true; downPoint.set(ev.getX(), ev.getY()); if (adapter.getCount() > 1) { callback.onDown(ev.getX() < getWidth() / 3f); } isDownReleased = false; } else if (action == MotionEvent.ACTION_UP) { if (!isDownReleased) { final int itemsCount = adapter.getCount(); int currentItem = getCurrentItem(); if (itemsCount > 1) { if (ev.getX() > getWidth() / 3f) { final int extraCount = adapter.getExtraCount(); if (++currentItem >= itemsCount - extraCount) { currentItem = extraCount; } } else { final int extraCount = adapter.getExtraCount(); if (--currentItem < extraCount) { currentItem = itemsCount - extraCount - 1; } } callback.onRelease(); setCurrentItem(currentItem, false); } } } else if (action == MotionEvent.ACTION_MOVE) { final float dx = ev.getX() - downPoint.x; final float dy = ev.getY() - downPoint.y; boolean move = Math.abs(dy) >= touchSlop || Math.abs(dx) >= touchSlop; if (move) { isDownReleased = true; callback.onRelease(); } if (isSwipingViewPager && isScrollingListView) { if (move) { if (Math.abs(dy) > Math.abs(dx)) { isSwipingViewPager = false; final MotionEvent cancelEvent = MotionEvent.obtain(ev); cancelEvent.setAction(MotionEvent.ACTION_CANCEL); super.onTouchEvent(cancelEvent); cancelEvent.recycle(); } else { isScrollingListView = false; final MotionEvent cancelEvent = MotionEvent.obtain(ev); cancelEvent.setAction(MotionEvent.ACTION_CANCEL); parentListView.onTouchEvent(cancelEvent); cancelEvent.recycle(); } } } else if (isSwipingViewPager && !canScrollHorizontally(-1) && dx > touchSlop) { return false; } } boolean result = false; if (isScrollingListView) { result = parentListView.onTouchEvent(ev); } if (isSwipingViewPager) { try { result |= super.onTouchEvent(ev); } catch (Exception e) { FileLog.e(e); } } if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { isScrollingListView = false; isSwipingViewPager = false; } return result; } public void setChatInfo(TLRPC.ChatFull chatFull) { chatInfo = chatFull; if (!photos.isEmpty() && photos.get(0) == null && chatInfo != null && FileLoader.isSamePhoto(imagesLocations.get(0).location, chatInfo.chat_photo)) { photos.set(0, chatInfo.chat_photo); if (!chatInfo.chat_photo.video_sizes.isEmpty()) { final TLRPC.VideoSize videoSize = FileLoader.getClosestVideoSizeWithSize(chatInfo.chat_photo.video_sizes, 1000); videoLocations.set(0, ImageLocation.getForPhoto(videoSize, chatInfo.chat_photo)); videoFileNames.set(0, FileLoader.getAttachFileName(videoSize)); callback.onPhotosLoaded(); } else { videoLocations.set(0, null); videoFileNames.add(0, null); } imagesUploadProgress.set(0, null); adapter.notifyDataSetChanged(); } } public boolean initIfEmpty(VectorAvatarThumbDrawable vectorAvatar, ImageLocation imageLocation, ImageLocation thumbLocation, boolean reload) { if (imageLocation == null || thumbLocation == null || settingMainPhoto != 0) { return false; } if (prevImageLocation == null || prevImageLocation.location.local_id != imageLocation.location.local_id) { if (!imagesLocations.isEmpty()) { prevImageLocation = imageLocation; if (reload) { MessagesController.getInstance(currentAccount).loadDialogPhotos(dialogId, 80, 0, true, parentClassGuid); } return true; } else { if (reload) { MessagesController.getInstance(currentAccount).loadDialogPhotos(dialogId, 80, 0, true, parentClassGuid); } } } if (!imagesLocations.isEmpty()) { return false; } prevImageLocation = imageLocation; prevThumbLocation = thumbLocation; prevVectorAvatarThumbDrawable = vectorAvatar; thumbsFileNames.add(null); videoFileNames.add(null); imagesLocations.add(imageLocation); thumbsLocations.add(thumbLocation); vectorAvatars.add(vectorAvatar); videoLocations.add(null); photos.add(null); imagesLocationsSizes.add(-1); imagesUploadProgress.add(null); getAdapter().notifyDataSetChanged(); resetCurrentItem(); return true; } ImageLocation currentUploadingImageLocation; ImageLocation curreantUploadingThumbLocation; public void addUploadingImage(ImageLocation imageLocation, ImageLocation thumbLocation) { prevImageLocation = imageLocation; thumbsFileNames.add(0, null); videoFileNames.add(0, null); imagesLocations.add(0, imageLocation); thumbsLocations.add(0, thumbLocation); vectorAvatars.add(0, null); videoLocations.add(0, null); photos.add(0, null); imagesLocationsSizes.add(0, -1); imagesUploadProgress.add(0, 0f); adapter.notifyDataSetChanged(); resetCurrentItem(); currentUploadingImageLocation = imageLocation; curreantUploadingThumbLocation = thumbLocation; } public void removeUploadingImage(ImageLocation imageLocation) { uploadingImageLocation = imageLocation; currentUploadingImageLocation = null; curreantUploadingThumbLocation = null; } public ImageLocation getImageLocation(int index) { if (index < 0 || index >= imagesLocations.size()) { return null; } ImageLocation location = videoLocations.get(index); if (location != null) { return location; } return imagesLocations.get(index); } public ImageLocation getRealImageLocation(int index) { if (index < 0 || index >= imagesLocations.size()) { return null; } return imagesLocations.get(index); } public ImageLocation getThumbLocation(int index) { if (index < 0 || index >= thumbsLocations.size()) { return null; } return thumbsLocations.get(index); } public boolean hasImages() { return !imagesLocations.isEmpty(); } public BackupImageView getCurrentItemView() { if (adapter != null && !adapter.objects.isEmpty()) { return adapter.objects.get(getCurrentItem()).imageView; } else { return null; } } public boolean isLoadingCurrentVideo() { if (videoLocations.get(hasActiveVideo ? getRealPosition() - 1 : getRealPosition()) == null) { return false; } BackupImageView imageView = getCurrentItemView(); if (imageView == null) { return false; } AnimatedFileDrawable drawable = imageView.getImageReceiver().getAnimation(); return drawable == null || !drawable.hasBitmap(); } public float getCurrentItemProgress() { BackupImageView imageView = getCurrentItemView(); if (imageView == null) { return 0.0f; } AnimatedFileDrawable drawable = imageView.getImageReceiver().getAnimation(); if (drawable == null) { return 0.0f; } return drawable.getCurrentProgress(); } public boolean isCurrentItemVideo() { int i = getRealPosition(); if (hasActiveVideo) { if (i == 0) { return false; } i--; } return videoLocations.get(i) != null; } public ImageLocation getCurrentVideoLocation(ImageLocation thumbLocation, ImageLocation imageLocation) { if (thumbLocation == null) { return null; } for (int b = 0; b < 2; b++) { ArrayList<ImageLocation> arrayList = b == 0 ? thumbsLocations : imagesLocations; for (int a = 0, N = arrayList.size(); a < N; a++) { ImageLocation loc = arrayList.get(a); if (loc == null || loc.location == null) { continue; } if (loc.dc_id == thumbLocation.dc_id && loc.location.local_id == thumbLocation.location.local_id && loc.location.volume_id == thumbLocation.location.volume_id || loc.dc_id == imageLocation.dc_id && loc.location.local_id == imageLocation.location.local_id && loc.location.volume_id == imageLocation.location.volume_id) { return videoLocations.get(a); } } } return null; } public void resetCurrentItem() { setCurrentItem(adapter.getExtraCount(), false); } public int getRealCount() { int size = photos.size(); if (hasActiveVideo) { size++; } return size; } public int getRealPosition(int position) { return adapter.getRealPosition(position); } public int getRealPosition() { return adapter.getRealPosition(getCurrentItem()); } public TLRPC.Photo getPhoto(int index) { if (index < 0 || index >= photos.size()) { return null; } return photos.get(index); } public void replaceFirstPhoto(TLRPC.Photo oldPhoto, TLRPC.Photo photo) { if (photos.isEmpty()) { return; } int idx = photos.indexOf(oldPhoto); if (idx < 0) { return; } photos.set(idx, photo); } public void finishSettingMainPhoto() { settingMainPhoto--; } public void startMovePhotoToBegin(int index) { if (index <= 0 || index >= photos.size()) { return; } settingMainPhoto++; TLRPC.Photo photo = photos.get(index); photos.remove(index); photos.add(0, photo); String name = thumbsFileNames.get(index); thumbsFileNames.remove(index); thumbsFileNames.add(0, name); videoFileNames.add(0, videoFileNames.remove(index)); ImageLocation location = videoLocations.get(index); videoLocations.remove(index); videoLocations.add(0, location); location = imagesLocations.get(index); imagesLocations.remove(index); imagesLocations.add(0, location); location = thumbsLocations.get(index); thumbsLocations.remove(index); thumbsLocations.add(0, location); VectorAvatarThumbDrawable vectorAvatar = vectorAvatars.get(index); vectorAvatars.remove(index); vectorAvatars.add(0, vectorAvatar); Integer size = imagesLocationsSizes.get(index); imagesLocationsSizes.remove(index); imagesLocationsSizes.add(0, size); Float uploadProgress = imagesUploadProgress.get(index); imagesUploadProgress.remove(index); imagesUploadProgress.add(0, uploadProgress); prevImageLocation = imagesLocations.get(0); } public void commitMoveToBegin() { adapter.notifyDataSetChanged(); resetCurrentItem(); } public boolean removePhotoAtIndex(int index) { if (index < 0 || index >= photos.size()) { return false; } photos.remove(index); thumbsFileNames.remove(index); videoFileNames.remove(index); videoLocations.remove(index); imagesLocations.remove(index); thumbsLocations.remove(index); vectorAvatars.remove(index); imagesLocationsSizes.remove(index); radialProgresses.delete(index); imagesUploadProgress.remove(index); if (index == 0 && !imagesLocations.isEmpty()) { prevImageLocation = imagesLocations.get(0); } adapter.notifyDataSetChanged(); return photos.isEmpty(); } @Override public boolean onInterceptTouchEvent(MotionEvent e) { if (parentListView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE) { return false; } if (getParent() != null && getParent().getParent() != null) { getParent().getParent().requestDisallowInterceptTouchEvent(canScrollHorizontally(-1)); } return super.onInterceptTouchEvent(e); } private void loadNeighboringThumbs() { final int locationsCount = thumbsLocations.size(); if (locationsCount > 1) { for (int i = 0; i < (locationsCount > 2 ? 2 : 1); i++) { final int pos = i == 0 ? 1 : locationsCount - 1; FileLoader.getInstance(currentAccount).loadFile(thumbsLocations.get(pos), null, null, FileLoader.PRIORITY_LOW, 1); } } } @SuppressWarnings("unchecked") @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.dialogPhotosLoaded) { int guid = (Integer) args[3]; long did = (Long) args[0]; if (did == dialogId && parentClassGuid == guid && adapter != null) { boolean fromCache = (Boolean) args[2]; ArrayList<TLRPC.Photo> arrayList = new ArrayList<>((ArrayList<TLRPC.Photo>) args[4]); if (arrayList.isEmpty() && fromCache) { return; } customAvatarIndex = -1; fallbackPhotoIndex = -1; TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(did); TLRPC.UserFull fullUser = MessagesController.getInstance(currentAccount).getUserFull(did); if (fullUser != null && fullUser.personal_photo != null) { arrayList.add(0, fullUser.personal_photo); customAvatarIndex = 0; } if (user != null && user.self) { if (UserObject.hasFallbackPhoto(fullUser)) { arrayList.add(fullUser.fallback_photo); fallbackPhotoIndex = arrayList.size() - 1; } } thumbsFileNames.clear(); videoFileNames.clear(); imagesLocations.clear(); videoLocations.clear(); thumbsLocations.clear(); vectorAvatars.clear(); photos.clear(); imagesLocationsSizes.clear(); imagesUploadProgress.clear(); ImageLocation currentImageLocation = null; if (DialogObject.isChatDialog(did)) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-did); currentImageLocation = ImageLocation.getForUserOrChat(chat, ImageLocation.TYPE_BIG); if (currentImageLocation != null) { imagesLocations.add(currentImageLocation); thumbsLocations.add(ImageLocation.getForUserOrChat(chat, ImageLocation.TYPE_SMALL)); vectorAvatars.add(null); thumbsFileNames.add(null); if (chatInfo != null && FileLoader.isSamePhoto(currentImageLocation.location, chatInfo.chat_photo)) { photos.add(chatInfo.chat_photo); if (!chatInfo.chat_photo.video_sizes.isEmpty()) { final TLRPC.VideoSize videoSize = FileLoader.getClosestVideoSizeWithSize(chatInfo.chat_photo.video_sizes, 1000); videoLocations.add(ImageLocation.getForPhoto(videoSize, chatInfo.chat_photo)); videoFileNames.add(FileLoader.getAttachFileName(videoSize)); } else { videoLocations.add(null); videoFileNames.add(null); } } else { photos.add(null); videoFileNames.add(null); videoLocations.add(null); } imagesLocationsSizes.add(-1); imagesUploadProgress.add(null); } } for (int a = 0; a < arrayList.size(); a++) { TLRPC.Photo photo = arrayList.get(a); if (photo == null || photo instanceof TLRPC.TL_photoEmpty || photo.sizes == null) { continue; } TLRPC.PhotoSize sizeThumb = FileLoader.getClosestPhotoSizeWithSize(photo.sizes, 50); for (int b = 0, N = photo.sizes.size(); b < N; b++) { TLRPC.PhotoSize photoSize = photo.sizes.get(b); if (photoSize instanceof TLRPC.TL_photoStrippedSize) { sizeThumb = photoSize; break; } } if (currentImageLocation != null) { boolean cont = false; for (int b = 0, N = photo.sizes.size(); b < N; b++) { TLRPC.PhotoSize size = photo.sizes.get(b); if (size.location != null && size.location.local_id == currentImageLocation.location.local_id && size.location.volume_id == currentImageLocation.location.volume_id) { photos.set(0, photo); if (!photo.video_sizes.isEmpty()) { videoLocations.set(0, ImageLocation.getForPhoto(FileLoader.getClosestVideoSizeWithSize(photo.video_sizes, 1000), photo)); } cont = true; break; } } if (cont) { continue; } } TLRPC.PhotoSize sizeFull = FileLoader.getClosestPhotoSizeWithSize(photo.sizes, 640); if (sizeFull != null) { if (photo.dc_id != 0) { sizeFull.location.dc_id = photo.dc_id; sizeFull.location.file_reference = photo.file_reference; } ImageLocation location = ImageLocation.getForPhoto(sizeFull, photo); if (location != null) { if (prevImageLocation != null && prevImageLocation.photoId == location.photoId) { thumbsFileNames.add(null); videoFileNames.add(null); imagesLocations.add(prevImageLocation); ImageLocation thumbLocation = prevThumbLocation; if (thumbLocation == null) { thumbLocation = ImageLocation.getForPhoto(sizeThumb, photo); } thumbsLocations.add(thumbLocation); vectorAvatars.add(prevVectorAvatarThumbDrawable); videoLocations.add(null); photos.add(null); imagesLocationsSizes.add(-1); imagesUploadProgress.add(null); } else { imagesLocations.add(location); thumbsFileNames.add(FileLoader.getAttachFileName(sizeThumb instanceof TLRPC.TL_photoStrippedSize ? sizeFull : sizeThumb)); thumbsLocations.add(ImageLocation.getForPhoto(sizeThumb, photo)); if (!photo.video_sizes.isEmpty()) { final TLRPC.VideoSize videoSize = FileLoader.getClosestVideoSizeWithSize(photo.video_sizes, 1000); final TLRPC.VideoSize vectorMarkupVideoSize = FileLoader.getVectorMarkupVideoSize(photo); if (vectorMarkupVideoSize != null) { vectorAvatars.add(new VectorAvatarThumbDrawable(vectorMarkupVideoSize, user != null && user.premium, VectorAvatarThumbDrawable.TYPE_PROFILE)); videoLocations.add(null); videoFileNames.add(null); } else { vectorAvatars.add(null); videoLocations.add(ImageLocation.getForPhoto(videoSize, photo)); videoFileNames.add(FileLoader.getAttachFileName(videoSize)); } } else { videoLocations.add(null); videoFileNames.add(null); vectorAvatars.add(null); } photos.add(photo); imagesLocationsSizes.add(sizeFull.size); imagesUploadProgress.add(null); } } } } loadNeighboringThumbs(); getAdapter().notifyDataSetChanged(); if (isProfileFragment) { if (!scrolledByUser || forceResetPosition) { resetCurrentItem(); } } else { if (!scrolledByUser || forceResetPosition) { resetCurrentItem(); getAdapter().notifyDataSetChanged(); checkCustomAvatar(getRealPosition(), 0); } } if (fallbackPhotoIndex < 0 && customAvatarIndex < 0) { checkCustomAvatar(0, 0); } forceResetPosition = false; if (fromCache) { MessagesController.getInstance(currentAccount).loadDialogPhotos(did, 80, 0, false, parentClassGuid); } if (callback != null) { callback.onPhotosLoaded(); } if (currentUploadingImageLocation != null) { addUploadingImage(currentUploadingImageLocation, curreantUploadingThumbLocation); } } } else if (id == NotificationCenter.fileLoaded) { final String fileName = (String) args[0]; for (int i = 0; i < thumbsFileNames.size(); i++) { String fileName2 = videoFileNames.get(i); if (fileName2 == null) { fileName2 = thumbsFileNames.get(i); } if (fileName2 != null && TextUtils.equals(fileName, fileName2)) { final RadialProgress2 radialProgress = radialProgresses.get(i); if (radialProgress != null) { radialProgress.setProgress(1f, true); } } } } else if (id == NotificationCenter.fileLoadProgressChanged) { String fileName = (String) args[0]; for (int i = 0; i < thumbsFileNames.size(); i++) { String fileName2 = videoFileNames.get(i); if (fileName2 == null) { fileName2 = thumbsFileNames.get(i); } if (fileName2 != null && TextUtils.equals(fileName, fileName2)) { final RadialProgress2 radialProgress = radialProgresses.get(i); if (radialProgress != null) { Long loadedSize = (Long) args[1]; Long totalSize = (Long) args[2]; float progress = Math.min(1f, loadedSize / (float) totalSize); radialProgress.setProgress(progress, true); } } } } else if (id == NotificationCenter.reloadDialogPhotos) { if (settingMainPhoto != 0) { return; } MessagesController.getInstance(currentAccount).loadDialogPhotos(dialogId, 80, 0, true, parentClassGuid); } } public class ViewPagerAdapter extends Adapter { private final ArrayList<Item> objects = new ArrayList<>(); private final ArrayList<BackupImageView> imageViews = new ArrayList<>(); private final Context context; private final Paint placeholderPaint; private BackupImageView parentAvatarImageView; private final ActionBar parentActionBar; public ViewPagerAdapter(Context context, ProfileActivity.AvatarImageView parentAvatarImageView, ActionBar parentActionBar) { this.context = context; this.parentAvatarImageView = parentAvatarImageView; this.parentActionBar = parentActionBar; placeholderPaint = new Paint(Paint.ANTI_ALIAS_FLAG); placeholderPaint.setColor(Color.BLACK); } @Override public int getCount() { return objects.size(); } @Override public boolean isViewFromObject(View view, Object object) { Item item = ((Item) object); if (item.isActiveVideo) { return view == item.textureViewStubView; } return view == item.imageView; } @Override public int getItemPosition(Object object) { final int idx = objects.indexOf((Item) object); return idx == -1 ? POSITION_NONE : idx; } @Override public Item instantiateItem(ViewGroup container, int position) { final Item item = objects.get(position); final int realPosition = getRealPosition(position); if (hasActiveVideo && realPosition == 0) { item.isActiveVideo = true; if (item.textureViewStubView == null) { item.textureViewStubView = new TextureStubView(context); } if (item.textureViewStubView.getParent() == null) { container.addView(item.textureViewStubView); } return item; } else { item.isActiveVideo = false; } if (item.textureViewStubView != null && item.textureViewStubView.getParent() != null) { container.removeView(item.textureViewStubView); } if (item.imageView == null) { item.imageView = new AvatarImageView(context, position, placeholderPaint); imageViews.set(position, item.imageView); } if (item.imageView.getParent() == null) { container.addView(item.imageView); } item.imageView.getImageReceiver().setAllowDecodeSingleFrame(true); int imageLocationPosition = hasActiveVideo ? realPosition - 1 : realPosition; boolean needProgress = false; if (imageLocationPosition == 0) { Drawable drawable = parentAvatarImageView == null ? null : parentAvatarImageView.getImageReceiver().getDrawable(); if (drawable instanceof AnimatedFileDrawable && ((AnimatedFileDrawable) drawable).hasBitmap()) { AnimatedFileDrawable animatedFileDrawable = (AnimatedFileDrawable) drawable; item.imageView.setImageDrawable(drawable); animatedFileDrawable.addSecondParentView(item.imageView); animatedFileDrawable.setInvalidateParentViewWithSecond(true); } else { ImageLocation videoLocation = videoLocations.get(imageLocationPosition); item.imageView.isVideo = videoLocation != null; needProgress = vectorAvatars.get(imageLocationPosition) == null; String filter; if (isProfileFragment && videoLocation != null && videoLocation.imageType == FileLoader.IMAGE_TYPE_ANIMATION) { filter = "avatar"; } else { filter = null; } ImageLocation location = thumbsLocations.get(imageLocationPosition); Bitmap thumb = (parentAvatarImageView == null || !createThumbFromParent) ? null : parentAvatarImageView.getImageReceiver().getBitmap(); String parent = "avatar_" + dialogId; if (thumb != null && vectorAvatars.get(imageLocationPosition) == null) { item.imageView.setImageMedia(videoLocations.get(imageLocationPosition), filter, imagesLocations.get(imageLocationPosition), null, thumb, imagesLocationsSizes.get(imageLocationPosition), 1, parent); } else if (uploadingImageLocation != null) { item.imageView.setImageMedia(vectorAvatars.get(imageLocationPosition), videoLocations.get(imageLocationPosition), filter, imagesLocations.get(imageLocationPosition), null, uploadingImageLocation, null, null, imagesLocationsSizes.get(imageLocationPosition), 1, parent); } else { String thumbFilter = location.photoSize instanceof TLRPC.TL_photoStrippedSize ? "b" : null; item.imageView.setImageMedia(vectorAvatars.get(imageLocationPosition), videoLocation, null, imagesLocations.get(imageLocationPosition), null, thumbsLocations.get(imageLocationPosition), thumbFilter, null, imagesLocationsSizes.get(imageLocationPosition), 1, parent); } } } else { final ImageLocation videoLocation = videoLocations.get(imageLocationPosition); item.imageView.isVideo = videoLocation != null; needProgress = vectorAvatars.get(imageLocationPosition) == null; ImageLocation location = thumbsLocations.get(imageLocationPosition); String filter = (location != null && location.photoSize instanceof TLRPC.TL_photoStrippedSize) ? "b" : null; String parent = "avatar_" + dialogId; item.imageView.setImageMedia(vectorAvatars.get(imageLocationPosition), videoLocation, null, imagesLocations.get(imageLocationPosition), null, thumbsLocations.get(imageLocationPosition), filter, null, imagesLocationsSizes.get(imageLocationPosition), 1, parent); } if (imagesUploadProgress.get(imageLocationPosition) != null) { needProgress = true; } if (needProgress) { item.imageView.radialProgress = radialProgresses.get(imageLocationPosition); if (item.imageView.radialProgress == null) { item.imageView.radialProgress = new RadialProgress2(item.imageView); item.imageView.radialProgress.setOverrideAlpha(0.0f); item.imageView.radialProgress.setIcon(MediaActionDrawable.ICON_EMPTY, false, false); item.imageView.radialProgress.setColors(0x42000000, 0x42000000, Color.WHITE, Color.WHITE); radialProgresses.append(imageLocationPosition, item.imageView.radialProgress); } if (invalidateWithParent) { invalidate(); } else { postInvalidateOnAnimation(); } } item.imageView.getImageReceiver().setDelegate(new ImageReceiver.ImageReceiverDelegate() { @Override public void didSetImage(ImageReceiver imageReceiver, boolean set, boolean thumb, boolean memCache) { } @Override public void onAnimationReady(ImageReceiver imageReceiver) { callback.onVideoSet(); } }); item.imageView.getImageReceiver().setCrossfadeAlpha((byte) 2); item.imageView.setRoundRadius(roundTopRadius, roundTopRadius, roundBottomRadius, roundBottomRadius); item.imageView.setTag(realPosition); return item; } @Override public void destroyItem(ViewGroup container, int position, Object object) { Item item = (Item) object; if (item.textureViewStubView != null) { container.removeView(item.textureViewStubView); } if (item.isActiveVideo) { return; } BackupImageView imageView = item.imageView; if (imageView.getImageReceiver().hasStaticThumb()) { Drawable drawable = imageView.getImageReceiver().getDrawable(); if (drawable instanceof AnimatedFileDrawable) { ((AnimatedFileDrawable) drawable).removeSecondParentView(imageView); } } imageView.setRoundRadius(0); container.removeView(imageView); imageView.getImageReceiver().cancelLoadImage(); } @Nullable @Override public CharSequence getPageTitle(int position) { return (getRealPosition(position) + 1) + "/" + (getCount() - getExtraCount() * 2); } @Override public void notifyDataSetChanged() { for (int i = 0; i < imageViews.size(); i++) { if (imageViews.get(i) != null) { imageViews.get(i).getImageReceiver().cancelLoadImage(); } } objects.clear(); imageViews.clear(); int size = imagesLocations.size(); if (hasActiveVideo) { size++; } for (int a = 0, N = size + getExtraCount() * 2; a < N; a++) { objects.add(new Item()); imageViews.add(null); } super.notifyDataSetChanged(); } @Override public int getExtraCount() { int count = imagesLocations.size(); if (hasActiveVideo) { count++; } if (count >= 2) { return getOffscreenPageLimit(); } else { return 0; } } } public void setData(long dialogId) { setData(dialogId, false); } public void setData(long dialogId, boolean forceReset) { if (this.dialogId == dialogId && !forceReset) { resetCurrentItem(); return; } forceResetPosition = true; reset(); this.dialogId = dialogId; // if (dialogId != 0) { // MessagesController.getInstance(currentAccount).loadDialogPhotos(dialogId, 80, 0, true, parentClassGuid); // } } public long getDialogId() { return dialogId; } private void reset() { videoFileNames.clear(); thumbsFileNames.clear(); photos.clear(); videoLocations.clear(); imagesLocations.clear(); thumbsLocations.clear(); imagesLocationsSizes.clear(); imagesUploadProgress.clear(); adapter.notifyDataSetChanged(); setCurrentItem(0 , false); selectedPage = 0; uploadingImageLocation = null; prevImageLocation = null; } public void setRoundRadius(int topRadius, int bottomRadius) { this.roundTopRadius = topRadius; this.roundBottomRadius = bottomRadius; if (adapter != null) { for (int i = 0; i < adapter.objects.size(); i++) { if (adapter.objects.get(i).imageView != null) { adapter.objects.get(i).imageView.setRoundRadius(roundTopRadius, roundTopRadius, roundBottomRadius, roundBottomRadius); } } } } public void setParentAvatarImage(BackupImageView parentImageView) { if (adapter != null) { adapter.parentAvatarImageView = parentImageView; } } public void setUploadProgress(ImageLocation imageLocation, float p) { if (imageLocation == null) { return; } for (int i = 0; i < imagesLocations.size(); i++) { if (imagesLocations.get(i) == imageLocation) { imagesUploadProgress.set(i, p); if (radialProgresses.get(i) != null) { radialProgresses.get(i).setProgress(p, true); } break; } } for (int i = 0; i < getChildCount(); i++) { getChildAt(i).invalidate(); } } public void setCreateThumbFromParent(boolean createThumbFromParent) { this.createThumbFromParent = createThumbFromParent; } private class AvatarImageView extends BackupImageView { private final int radialProgressSize = AndroidUtilities.dp(64f); private RadialProgress2 radialProgress; private ValueAnimator radialProgressHideAnimator; private float radialProgressHideAnimatorStartValue; private long firstDrawTime = -1; public boolean isVideo; private final int position; private final Paint placeholderPaint; public AvatarImageView(Context context, int position, Paint placeholderPaint) { super(context); this.position = position; this.placeholderPaint = placeholderPaint; setLayerNum(imagesLayerNum); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); if (radialProgress != null) { int paddingTop = (parentActionBar.getOccupyStatusBar() ? AndroidUtilities.statusBarHeight : 0) + ActionBar.getCurrentActionBarHeight(); int paddingBottom = AndroidUtilities.dp2(80f); radialProgress.setProgressRect((w - radialProgressSize) / 2, paddingTop + (h - paddingTop - paddingBottom - radialProgressSize) / 2, (w + radialProgressSize) / 2, paddingTop + (h - paddingTop - paddingBottom + radialProgressSize) / 2); } } @Override protected void onDraw(Canvas canvas) { if (pinchToZoomHelper != null && pinchToZoomHelper.isInOverlayMode()) { return; } if (radialProgress != null) { int realPosition = getRealPosition(position); if (hasActiveVideo) { realPosition--; } final Drawable drawable = getImageReceiver().getDrawable(); boolean hideProgress; if (realPosition < imagesUploadProgress.size() && imagesUploadProgress.get(realPosition) != null) { hideProgress = imagesUploadProgress.get(realPosition) >= 1f; } else { hideProgress = drawable != null && (!isVideo || (drawable instanceof AnimatedFileDrawable && ((AnimatedFileDrawable) drawable).getDurationMs() > 0)); } if (hideProgress) { if (radialProgressHideAnimator == null) { long startDelay = 0; if (radialProgress.getProgress() < 1f) { radialProgress.setProgress(1f, true); startDelay = 100; } radialProgressHideAnimatorStartValue = radialProgress.getOverrideAlpha(); radialProgressHideAnimator = ValueAnimator.ofFloat(0f, 1f); radialProgressHideAnimator.setStartDelay(startDelay); radialProgressHideAnimator.setDuration((long) (radialProgressHideAnimatorStartValue * 250f)); radialProgressHideAnimator.setInterpolator(CubicBezierInterpolator.DEFAULT); radialProgressHideAnimator.addUpdateListener(anim -> radialProgress.setOverrideAlpha(AndroidUtilities.lerp(radialProgressHideAnimatorStartValue, 0f, anim.getAnimatedFraction()))); int finalRealPosition = realPosition; radialProgressHideAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { radialProgress = null; radialProgresses.delete(finalRealPosition); } }); radialProgressHideAnimator.start(); } } else { if (firstDrawTime < 0) { firstDrawTime = System.currentTimeMillis(); } else { final long elapsedTime = System.currentTimeMillis() - firstDrawTime; final long startDelay = isVideo ? 250 : 750; final long duration = 250; if (elapsedTime <= startDelay + duration) { if (elapsedTime > startDelay) { radialProgress.setOverrideAlpha(CubicBezierInterpolator.DEFAULT.getInterpolation((elapsedTime - startDelay) / (float) duration)); } } } if (invalidateWithParent) { invalidate(); } else { postInvalidateOnAnimation(); } invalidate(); } if (roundTopRadius == 0 && roundBottomRadius == 0) { canvas.drawRect(0, 0, getWidth(), getHeight(), placeholderPaint); } else if (roundTopRadius == roundBottomRadius) { rect.set(0, 0, getWidth(), getHeight()); canvas.drawRoundRect(rect, roundTopRadius, roundTopRadius, placeholderPaint); } else { path.reset(); rect.set(0, 0, getWidth(), getHeight()); for (int i = 0; i < 4; i++) { radii[i] = roundTopRadius; radii[4 + i] = roundBottomRadius; } path.addRoundRect(rect, radii, Path.Direction.CW); canvas.drawPath(path, placeholderPaint); } } super.onDraw(canvas); if (radialProgress != null && radialProgress.getOverrideAlpha() > 0f) { radialProgress.draw(canvas); } } @Override public void invalidate() { super.invalidate(); if (invalidateWithParent) { ProfileGalleryView.this.invalidate(); } } } public void setPinchToZoomHelper(PinchToZoomHelper pinchToZoomHelper) { this.pinchToZoomHelper = pinchToZoomHelper; } public void setInvalidateWithParent(boolean invalidateWithParent) { this.invalidateWithParent = invalidateWithParent; } private class TextureStubView extends View { public TextureStubView(Context context) { super(context); } } public void scrollToLastItem() { int p = 0; while (getRealPosition(p) != getRealCount() - 1) { p++; } setCurrentItem(p, true); } }
flyun/chatAir
TMessagesProj/src/main/java/org/telegram/ui/Components/ProfileGalleryView.java
41,679
/* * Copyright 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ package org.webrtc; import android.content.Context; import android.os.Process; import androidx.annotation.Nullable; import java.util.List; import org.webrtc.Logging.Severity; import org.webrtc.PeerConnection; import org.webrtc.audio.AudioDeviceModule; import org.webrtc.audio.JavaAudioDeviceModule; /** * Java wrapper for a C++ PeerConnectionFactoryInterface. Main entry point to * the PeerConnection API for clients. */ public class PeerConnectionFactory { public static final String TRIAL_ENABLED = "Enabled"; @Deprecated public static final String VIDEO_FRAME_EMIT_TRIAL = "VideoFrameEmit"; private static final String TAG = "PeerConnectionFactory"; private static final String VIDEO_CAPTURER_THREAD_NAME = "VideoCapturerThread"; /** Helper class holding both Java and C++ thread info. */ private static class ThreadInfo { final Thread thread; final int tid; public static ThreadInfo getCurrent() { return new ThreadInfo(Thread.currentThread(), Process.myTid()); } private ThreadInfo(Thread thread, int tid) { this.thread = thread; this.tid = tid; } } private static volatile boolean internalTracerInitialized; // Remove these once deprecated static printStackTrace() is gone. @Nullable private static ThreadInfo staticNetworkThread; @Nullable private static ThreadInfo staticWorkerThread; @Nullable private static ThreadInfo staticSignalingThread; private long nativeFactory; @Nullable private volatile ThreadInfo networkThread; @Nullable private volatile ThreadInfo workerThread; @Nullable private volatile ThreadInfo signalingThread; public static class InitializationOptions { final Context applicationContext; final String fieldTrials; final boolean enableInternalTracer; final String nativeLibraryName; @Nullable Loggable loggable; @Nullable Severity loggableSeverity; private InitializationOptions(Context applicationContext, String fieldTrials, boolean enableInternalTracer, String nativeLibraryName, @Nullable Loggable loggable, @Nullable Severity loggableSeverity) { this.applicationContext = applicationContext; this.fieldTrials = fieldTrials; this.enableInternalTracer = enableInternalTracer; this.nativeLibraryName = nativeLibraryName; this.loggable = loggable; this.loggableSeverity = loggableSeverity; } public static Builder builder(Context applicationContext) { return new Builder(applicationContext); } public static class Builder { private final Context applicationContext; private String fieldTrials = ""; private boolean enableInternalTracer; private String nativeLibraryName = "jingle_peerconnection_so"; @Nullable private Loggable loggable; @Nullable private Severity loggableSeverity; Builder(Context applicationContext) { this.applicationContext = applicationContext; } public Builder setFieldTrials(String fieldTrials) { this.fieldTrials = fieldTrials; return this; } public Builder setEnableInternalTracer(boolean enableInternalTracer) { this.enableInternalTracer = enableInternalTracer; return this; } public Builder setNativeLibraryName(String nativeLibraryName) { this.nativeLibraryName = nativeLibraryName; return this; } public Builder setInjectableLogger(Loggable loggable, Severity severity) { this.loggable = loggable; this.loggableSeverity = severity; return this; } public PeerConnectionFactory.InitializationOptions createInitializationOptions() { return new PeerConnectionFactory.InitializationOptions(applicationContext, fieldTrials, enableInternalTracer, nativeLibraryName, loggable, loggableSeverity); } } } public static class Options { // Keep in sync with webrtc/rtc_base/network.h! // // These bit fields are defined for |networkIgnoreMask| below. static final int ADAPTER_TYPE_UNKNOWN = 0; static final int ADAPTER_TYPE_ETHERNET = 1 << 0; static final int ADAPTER_TYPE_WIFI = 1 << 1; static final int ADAPTER_TYPE_CELLULAR = 1 << 2; static final int ADAPTER_TYPE_VPN = 1 << 3; static final int ADAPTER_TYPE_LOOPBACK = 1 << 4; static final int ADAPTER_TYPE_ANY = 1 << 5; public int networkIgnoreMask; public boolean disableEncryption; public boolean disableNetworkMonitor; @CalledByNative("Options") int getNetworkIgnoreMask() { return networkIgnoreMask; } @CalledByNative("Options") boolean getDisableEncryption() { return disableEncryption; } @CalledByNative("Options") boolean getDisableNetworkMonitor() { return disableNetworkMonitor; } } public static class Builder { @Nullable private Options options; @Nullable private AudioDeviceModule audioDeviceModule; private AudioEncoderFactoryFactory audioEncoderFactoryFactory = new BuiltinAudioEncoderFactoryFactory(); private AudioDecoderFactoryFactory audioDecoderFactoryFactory = new BuiltinAudioDecoderFactoryFactory(); @Nullable private VideoEncoderFactory videoEncoderFactory; @Nullable private VideoDecoderFactory videoDecoderFactory; @Nullable private AudioProcessingFactory audioProcessingFactory; @Nullable private FecControllerFactoryFactoryInterface fecControllerFactoryFactory; @Nullable private NetworkControllerFactoryFactory networkControllerFactoryFactory; @Nullable private NetworkStatePredictorFactoryFactory networkStatePredictorFactoryFactory; @Nullable private NetEqFactoryFactory neteqFactoryFactory; private Builder() {} public Builder setOptions(Options options) { this.options = options; return this; } public Builder setAudioDeviceModule(AudioDeviceModule audioDeviceModule) { this.audioDeviceModule = audioDeviceModule; return this; } public Builder setAudioEncoderFactoryFactory( AudioEncoderFactoryFactory audioEncoderFactoryFactory) { if (audioEncoderFactoryFactory == null) { throw new IllegalArgumentException( "PeerConnectionFactory.Builder does not accept a null AudioEncoderFactoryFactory."); } this.audioEncoderFactoryFactory = audioEncoderFactoryFactory; return this; } public Builder setAudioDecoderFactoryFactory( AudioDecoderFactoryFactory audioDecoderFactoryFactory) { if (audioDecoderFactoryFactory == null) { throw new IllegalArgumentException( "PeerConnectionFactory.Builder does not accept a null AudioDecoderFactoryFactory."); } this.audioDecoderFactoryFactory = audioDecoderFactoryFactory; return this; } public Builder setVideoEncoderFactory(VideoEncoderFactory videoEncoderFactory) { this.videoEncoderFactory = videoEncoderFactory; return this; } public Builder setVideoDecoderFactory(VideoDecoderFactory videoDecoderFactory) { this.videoDecoderFactory = videoDecoderFactory; return this; } public Builder setAudioProcessingFactory(AudioProcessingFactory audioProcessingFactory) { if (audioProcessingFactory == null) { throw new NullPointerException( "PeerConnectionFactory builder does not accept a null AudioProcessingFactory."); } this.audioProcessingFactory = audioProcessingFactory; return this; } public Builder setFecControllerFactoryFactoryInterface( FecControllerFactoryFactoryInterface fecControllerFactoryFactory) { this.fecControllerFactoryFactory = fecControllerFactoryFactory; return this; } public Builder setNetworkControllerFactoryFactory( NetworkControllerFactoryFactory networkControllerFactoryFactory) { this.networkControllerFactoryFactory = networkControllerFactoryFactory; return this; } public Builder setNetworkStatePredictorFactoryFactory( NetworkStatePredictorFactoryFactory networkStatePredictorFactoryFactory) { this.networkStatePredictorFactoryFactory = networkStatePredictorFactoryFactory; return this; } /** * Sets a NetEqFactoryFactory for the PeerConnectionFactory. When using a * custom NetEqFactoryFactory, the AudioDecoderFactoryFactory will be set * to null. The AudioDecoderFactoryFactory should be wrapped in the * NetEqFactoryFactory. */ public Builder setNetEqFactoryFactory(NetEqFactoryFactory neteqFactoryFactory) { this.neteqFactoryFactory = neteqFactoryFactory; return this; } public PeerConnectionFactory createPeerConnectionFactory() { checkInitializeHasBeenCalled(); if (audioDeviceModule == null) { audioDeviceModule = JavaAudioDeviceModule.builder(ContextUtils.getApplicationContext()) .createAudioDeviceModule(); } return nativeCreatePeerConnectionFactory(ContextUtils.getApplicationContext(), options, audioDeviceModule.getNativeAudioDeviceModulePointer(), audioEncoderFactoryFactory.createNativeAudioEncoderFactory(), audioDecoderFactoryFactory.createNativeAudioDecoderFactory(), videoEncoderFactory, videoDecoderFactory, audioProcessingFactory == null ? 0 : audioProcessingFactory.createNative(), fecControllerFactoryFactory == null ? 0 : fecControllerFactoryFactory.createNative(), networkControllerFactoryFactory == null ? 0 : networkControllerFactoryFactory.createNativeNetworkControllerFactory(), networkStatePredictorFactoryFactory == null ? 0 : networkStatePredictorFactoryFactory.createNativeNetworkStatePredictorFactory(), neteqFactoryFactory == null ? 0 : neteqFactoryFactory.createNativeNetEqFactory()); } } public static Builder builder() { return new Builder(); } /** * Loads and initializes WebRTC. This must be called at least once before creating a * PeerConnectionFactory. Replaces all the old initialization methods. Must not be called while * a PeerConnectionFactory is alive. */ public static void initialize(InitializationOptions options) { ContextUtils.initialize(options.applicationContext); nativeInitializeAndroidGlobals(); nativeInitializeFieldTrials(options.fieldTrials); if (options.enableInternalTracer && !internalTracerInitialized) { initializeInternalTracer(); } if (options.loggable != null) { Logging.injectLoggable(options.loggable, options.loggableSeverity); nativeInjectLoggable(new JNILogging(options.loggable), options.loggableSeverity.ordinal()); } else { Logging.d(TAG, "PeerConnectionFactory was initialized without an injected Loggable. " + "Any existing Loggable will be deleted."); Logging.deleteInjectedLoggable(); nativeDeleteLoggable(); } } private static void checkInitializeHasBeenCalled() { if (ContextUtils.getApplicationContext() == null) { throw new IllegalStateException( "PeerConnectionFactory.initialize was not called before creating a " + "PeerConnectionFactory."); } } private static void initializeInternalTracer() { internalTracerInitialized = true; nativeInitializeInternalTracer(); } public static void shutdownInternalTracer() { internalTracerInitialized = false; nativeShutdownInternalTracer(); } // Field trial initialization. Must be called before PeerConnectionFactory // is created. // Deprecated, use PeerConnectionFactory.initialize instead. @Deprecated public static void initializeFieldTrials(String fieldTrialsInitString) { nativeInitializeFieldTrials(fieldTrialsInitString); } // Wrapper of webrtc::field_trial::FindFullName. Develop the feature with default behaviour off. // Example usage: // if (PeerConnectionFactory.fieldTrialsFindFullName("WebRTCExperiment").equals("Enabled")) { // method1(); // } else { // method2(); // } public static String fieldTrialsFindFullName(String name) { return nativeFindFieldTrialsFullName(name); } // Start/stop internal capturing of internal tracing. public static boolean startInternalTracingCapture(String tracingFilename) { return nativeStartInternalTracingCapture(tracingFilename); } public static void stopInternalTracingCapture() { nativeStopInternalTracingCapture(); } @CalledByNative PeerConnectionFactory(long nativeFactory) { checkInitializeHasBeenCalled(); if (nativeFactory == 0) { throw new RuntimeException("Failed to initialize PeerConnectionFactory!"); } this.nativeFactory = nativeFactory; } /** * Internal helper function to pass the parameters down into the native JNI bridge. */ @Nullable PeerConnection createPeerConnectionInternal(PeerConnection.RTCConfiguration rtcConfig, MediaConstraints constraints, PeerConnection.Observer observer, SSLCertificateVerifier sslCertificateVerifier) { checkPeerConnectionFactoryExists(); long nativeObserver = PeerConnection.createNativePeerConnectionObserver(observer); if (nativeObserver == 0) { return null; } long nativePeerConnection = nativeCreatePeerConnection( nativeFactory, rtcConfig, constraints, nativeObserver, sslCertificateVerifier); if (nativePeerConnection == 0) { return null; } return new PeerConnection(nativePeerConnection); } /** * Deprecated. PeerConnection constraints are deprecated. Supply values in rtcConfig struct * instead and use the method without constraints in the signature. */ @Nullable @Deprecated public PeerConnection createPeerConnection(PeerConnection.RTCConfiguration rtcConfig, MediaConstraints constraints, PeerConnection.Observer observer) { return createPeerConnectionInternal( rtcConfig, constraints, observer, /* sslCertificateVerifier= */ null); } /** * Deprecated. PeerConnection constraints are deprecated. Supply values in rtcConfig struct * instead and use the method without constraints in the signature. */ @Nullable @Deprecated public PeerConnection createPeerConnection(List<PeerConnection.IceServer> iceServers, MediaConstraints constraints, PeerConnection.Observer observer) { PeerConnection.RTCConfiguration rtcConfig = new PeerConnection.RTCConfiguration(iceServers); return createPeerConnection(rtcConfig, constraints, observer); } @Nullable public PeerConnection createPeerConnection( List<PeerConnection.IceServer> iceServers, PeerConnection.Observer observer) { PeerConnection.RTCConfiguration rtcConfig = new PeerConnection.RTCConfiguration(iceServers); return createPeerConnection(rtcConfig, observer); } @Nullable public PeerConnection createPeerConnection( PeerConnection.RTCConfiguration rtcConfig, PeerConnection.Observer observer) { return createPeerConnection(rtcConfig, null /* constraints */, observer); } @Nullable public PeerConnection createPeerConnection( PeerConnection.RTCConfiguration rtcConfig, PeerConnectionDependencies dependencies) { return createPeerConnectionInternal(rtcConfig, null /* constraints */, dependencies.getObserver(), dependencies.getSSLCertificateVerifier()); } public MediaStream createLocalMediaStream(String label) { checkPeerConnectionFactoryExists(); return new MediaStream(nativeCreateLocalMediaStream(nativeFactory, label)); } /** * Create video source with given parameters. If alignTimestamps is false, the caller is * responsible for aligning the frame timestamps to rtc::TimeNanos(). This can be used to achieve * higher accuracy if there is a big delay between frame creation and frames being delivered to * the returned video source. If alignTimestamps is true, timestamps will be aligned to * rtc::TimeNanos() when they arrive to the returned video source. */ public VideoSource createVideoSource(boolean isScreencast, boolean alignTimestamps) { checkPeerConnectionFactoryExists(); return new VideoSource(nativeCreateVideoSource(nativeFactory, isScreencast, alignTimestamps)); } /** * Same as above with alignTimestamps set to true. * * @see #createVideoSource(boolean, boolean) */ public VideoSource createVideoSource(boolean isScreencast) { return createVideoSource(isScreencast, /* alignTimestamps= */ true); } public VideoTrack createVideoTrack(String id, VideoSource source) { checkPeerConnectionFactoryExists(); return new VideoTrack( nativeCreateVideoTrack(nativeFactory, id, source.getNativeVideoTrackSource())); } public AudioSource createAudioSource(MediaConstraints constraints) { checkPeerConnectionFactoryExists(); return new AudioSource(nativeCreateAudioSource(nativeFactory, constraints)); } public AudioTrack createAudioTrack(String id, AudioSource source) { checkPeerConnectionFactoryExists(); return new AudioTrack(nativeCreateAudioTrack(nativeFactory, id, source.getNativeAudioSource())); } // Starts recording an AEC dump. Ownership of the file is transfered to the // native code. If an AEC dump is already in progress, it will be stopped and // a new one will start using the provided file. public boolean startAecDump(int file_descriptor, int filesize_limit_bytes) { checkPeerConnectionFactoryExists(); return nativeStartAecDump(nativeFactory, file_descriptor, filesize_limit_bytes); } // Stops recording an AEC dump. If no AEC dump is currently being recorded, // this call will have no effect. public void stopAecDump() { checkPeerConnectionFactoryExists(); nativeStopAecDump(nativeFactory); } public void dispose() { checkPeerConnectionFactoryExists(); nativeFreeFactory(nativeFactory); networkThread = null; workerThread = null; signalingThread = null; nativeFactory = 0; } /** Returns a pointer to the native webrtc::PeerConnectionFactoryInterface. */ public long getNativePeerConnectionFactory() { checkPeerConnectionFactoryExists(); return nativeGetNativePeerConnectionFactory(nativeFactory); } /** Returns a pointer to the native OwnedFactoryAndThreads object */ public long getNativeOwnedFactoryAndThreads() { checkPeerConnectionFactoryExists(); return nativeFactory; } private void checkPeerConnectionFactoryExists() { if (nativeFactory == 0) { throw new IllegalStateException("PeerConnectionFactory has been disposed."); } } private static void printStackTrace( @Nullable ThreadInfo threadInfo, boolean printNativeStackTrace) { if (threadInfo == null) { // Thread callbacks have not been completed yet, ignore call. return; } final String threadName = threadInfo.thread.getName(); StackTraceElement[] stackTraces = threadInfo.thread.getStackTrace(); if (stackTraces.length > 0) { Logging.w(TAG, threadName + " stacktrace:"); for (StackTraceElement stackTrace : stackTraces) { Logging.w(TAG, stackTrace.toString()); } } if (printNativeStackTrace) { // Imitate output from debuggerd/tombstone so that stack trace can easily be symbolized with // ndk-stack. Logging.w(TAG, "*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***"); Logging.w(TAG, "pid: " + Process.myPid() + ", tid: " + threadInfo.tid + ", name: " + threadName + " >>> WebRTC <<<"); nativePrintStackTrace(threadInfo.tid); } } /** Deprecated, use non-static version instead. */ @Deprecated public static void printStackTraces() { printStackTrace(staticNetworkThread, /* printNativeStackTrace= */ false); printStackTrace(staticWorkerThread, /* printNativeStackTrace= */ false); printStackTrace(staticSignalingThread, /* printNativeStackTrace= */ false); } /** * Print the Java stack traces for the critical threads used by PeerConnectionFactory, namely; * signaling thread, worker thread, and network thread. If printNativeStackTraces is true, also * attempt to print the C++ stack traces for these (and some other) threads. */ public void printInternalStackTraces(boolean printNativeStackTraces) { printStackTrace(signalingThread, printNativeStackTraces); printStackTrace(workerThread, printNativeStackTraces); printStackTrace(networkThread, printNativeStackTraces); if (printNativeStackTraces) { nativePrintStackTracesOfRegisteredThreads(); } } @CalledByNative private void onNetworkThreadReady() { networkThread = ThreadInfo.getCurrent(); staticNetworkThread = networkThread; Logging.d(TAG, "onNetworkThreadReady"); } @CalledByNative private void onWorkerThreadReady() { workerThread = ThreadInfo.getCurrent(); staticWorkerThread = workerThread; Logging.d(TAG, "onWorkerThreadReady"); } @CalledByNative private void onSignalingThreadReady() { signalingThread = ThreadInfo.getCurrent(); staticSignalingThread = signalingThread; Logging.d(TAG, "onSignalingThreadReady"); } // Must be called at least once before creating a PeerConnectionFactory // (for example, at application startup time). private static native void nativeInitializeAndroidGlobals(); private static native void nativeInitializeFieldTrials(String fieldTrialsInitString); private static native String nativeFindFieldTrialsFullName(String name); private static native void nativeInitializeInternalTracer(); // Internal tracing shutdown, called to prevent resource leaks. Must be called after // PeerConnectionFactory is gone to prevent races with code performing tracing. private static native void nativeShutdownInternalTracer(); private static native boolean nativeStartInternalTracingCapture(String tracingFilename); private static native void nativeStopInternalTracingCapture(); private static native PeerConnectionFactory nativeCreatePeerConnectionFactory(Context context, Options options, long nativeAudioDeviceModule, long audioEncoderFactory, long audioDecoderFactory, VideoEncoderFactory encoderFactory, VideoDecoderFactory decoderFactory, long nativeAudioProcessor, long nativeFecControllerFactory, long nativeNetworkControllerFactory, long nativeNetworkStatePredictorFactory, long neteqFactory); private static native long nativeCreatePeerConnection(long factory, PeerConnection.RTCConfiguration rtcConfig, MediaConstraints constraints, long nativeObserver, SSLCertificateVerifier sslCertificateVerifier); private static native long nativeCreateLocalMediaStream(long factory, String label); private static native long nativeCreateVideoSource( long factory, boolean is_screencast, boolean alignTimestamps); private static native long nativeCreateVideoTrack( long factory, String id, long nativeVideoSource); private static native long nativeCreateAudioSource(long factory, MediaConstraints constraints); private static native long nativeCreateAudioTrack(long factory, String id, long nativeSource); private static native boolean nativeStartAecDump( long factory, int file_descriptor, int filesize_limit_bytes); private static native void nativeStopAecDump(long factory); private static native void nativeFreeFactory(long factory); private static native long nativeGetNativePeerConnectionFactory(long factory); private static native void nativeInjectLoggable(JNILogging jniLogging, int severity); private static native void nativeDeleteLoggable(); private static native void nativePrintStackTrace(int tid); private static native void nativePrintStackTracesOfRegisteredThreads(); }
NekoX-Dev/NekoX
TMessagesProj/src/main/java/org/webrtc/PeerConnectionFactory.java
41,680
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.ui; import android.animation.Animator; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.Context; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.StatFs; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextUtils; import android.text.style.RelativeSizeSpan; import android.util.LongSparseArray; import android.util.SparseArray; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.FrameLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.core.graphics.ColorUtils; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.BotWebViewVibrationEffect; import org.telegram.messenger.CacheByChatsController; import org.telegram.messenger.Emoji; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.FilePathDatabase; import org.telegram.messenger.FilesMigrationService; import org.telegram.messenger.ImageLoader; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MediaDataController; import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesStorage; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.SharedConfig; import org.telegram.messenger.Utilities; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.ActionBar; import org.telegram.ui.ActionBar.ActionBarMenu; import org.telegram.ui.ActionBar.ActionBarMenuItem; import org.telegram.ui.ActionBar.ActionBarMenuSubItem; import org.telegram.ui.ActionBar.ActionBarPopupWindow; import org.telegram.ui.ActionBar.AlertDialog; import org.telegram.ui.ActionBar.BackDrawable; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.BottomSheet; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.ThemeDescription; import org.telegram.ui.Cells.CheckBoxCell; import org.telegram.ui.Cells.HeaderCell; import org.telegram.ui.Cells.TextCell; import org.telegram.ui.Cells.TextCheckBoxCell; import org.telegram.ui.Cells.TextInfoPrivacyCell; import org.telegram.ui.Cells.TextSettingsCell; import org.telegram.ui.Components.AlertsCreator; import org.telegram.ui.Components.AnimatedFloat; import org.telegram.ui.Components.AnimatedTextView; import org.telegram.ui.Components.BackupImageView; import org.telegram.ui.Components.CacheChart; import org.telegram.ui.Components.CheckBox2; import org.telegram.ui.Components.CubicBezierInterpolator; import org.telegram.ui.Components.FlickerLoadingView; import org.telegram.ui.Components.HideViewAfterAnimation; import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.ListView.AdapterWithDiffUtils; import org.telegram.ui.Components.LoadingDrawable; import org.telegram.ui.Components.NestedSizeNotifierLayout; import org.telegram.ui.Components.RecyclerListView; import org.telegram.ui.Components.SlideChooseView; import org.telegram.ui.Components.StorageDiagramView; import org.telegram.ui.Components.StorageUsageView; import org.telegram.ui.Components.TypefaceSpan; import org.telegram.ui.Components.UndoView; import org.telegram.ui.Storage.CacheModel; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Objects; public class CacheControlActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate { private static final int VIEW_TYPE_INFO = 1; private static final int VIEW_TYPE_STORAGE = 2; private static final int VIEW_TYPE_HEADER = 3; private static final int VIEW_TYPE_CHOOSER = 4; private static final int VIEW_TYPE_CHAT = 5; private static final int VIEW_FLICKER_LOADING_DIALOG = 6; private static final int VIEW_TYPE_KEEP_MEDIA_CELL = 7; private static final int VIEW_TYPE_TEXT_SETTINGS = 0; private static final int VIEW_TYPE_CACHE_VIEW_PAGER = 8; private static final int VIEW_TYPE_CHART = 9; private static final int VIEW_TYPE_CHART_HEADER = 10; public static final int VIEW_TYPE_SECTION = 11; private static final int VIEW_TYPE_SECTION_LOADING = 12; private static final int VIEW_TYPE_CLEAR_CACHE_BUTTON = 13; private static final int VIEW_TYPE_MAX_CACHE_SIZE = 14; public static final int KEEP_MEDIA_TYPE_USER = 0; public static final int KEEP_MEDIA_TYPE_GROUP = 1; public static final int KEEP_MEDIA_TYPE_CHANNEL = 2; public static final long UNKNOWN_CHATS_DIALOG_ID = Long.MAX_VALUE; private ListAdapter listAdapter; private RecyclerListView listView; @SuppressWarnings("FieldCanBeLocal") private LinearLayoutManager layoutManager; AlertDialog progressDialog; private boolean[] selected = new boolean[] { true, true, true, true, true, true, true, true, true }; private long databaseSize = -1; private long cacheSize = -1, cacheEmojiSize = -1, cacheTempSize = -1; private long documentsSize = -1; private long audioSize = -1; private long musicSize = -1; private long photoSize = -1; private long videoSize = -1; private long stickersCacheSize = -1; private long totalSize = -1; private long totalDeviceSize = -1; private long totalDeviceFreeSize = -1; private long migrateOldFolderRow = -1; private boolean calculating = true; private boolean collapsed = true; private CachedMediaLayout cachedMediaLayout; private int[] percents; private float[] tempSizes; private int sectionsStartRow = -1; private int sectionsEndRow = -1; private CacheChart cacheChart; private CacheChartHeader cacheChartHeader; private ClearCacheButtonInternal clearCacheButton; public static volatile boolean canceled = false; private View bottomSheetView; private BottomSheet bottomSheet; private View actionTextView; private UndoView cacheRemovedTooltip; long fragmentCreateTime; private boolean updateDatabaseSize; public final static int TYPE_PHOTOS = 0; public final static int TYPE_VIDEOS = 1; public final static int TYPE_DOCUMENTS = 2; public final static int TYPE_MUSIC = 3; public final static int TYPE_VOICE = 4; public final static int TYPE_ANIMATED_STICKERS_CACHE = 5; public final static int TYPE_OTHER = 6; private static final int delete_id = 1; private static final int other_id = 2; private static final int clear_database_id = 3; private boolean loadingDialogs; private NestedSizeNotifierLayout nestedSizeNotifierLayout; private ActionBarMenuSubItem clearDatabaseItem; private void updateDatabaseItemSize() { if (clearDatabaseItem != null) { SpannableStringBuilder string = new SpannableStringBuilder(); string.append(LocaleController.getString("ClearLocalDatabase", R.string.ClearLocalDatabase)); // string.append("\t"); // SpannableString databaseSizeString = new SpannableString(AndroidUtilities.formatFileSize(databaseSize)); // databaseSizeString.setSpan(new ForegroundColorSpan(Theme.getColor(Theme.key_windowBackgroundWhiteBlueText)), 0, databaseSizeString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // string.append(databaseSizeString); clearDatabaseItem.setText(string); } } private static long lastTotalSizeCalculatedTime; private static Long lastTotalSizeCalculated; private static Long lastDeviceTotalSize, lastDeviceTotalFreeSize; public static void calculateTotalSize(Utilities.Callback<Long> onDone) { if (onDone == null) { return; } if (lastTotalSizeCalculated != null) { onDone.run(lastTotalSizeCalculated); if (System.currentTimeMillis() - lastTotalSizeCalculatedTime < 5000) { return; } } Utilities.globalQueue.postRunnable(() -> { canceled = false; long cacheSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 5); long cacheTempSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 4); long photoSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE), 0); photoSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE_PUBLIC), 0); long videoSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO), 0); videoSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO_PUBLIC), 0); long documentsSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT), 1); documentsSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES), 1); long musicSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT), 2); musicSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES), 2); long stickersCacheSize = getDirectorySize(new File(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), "acache"), 0); stickersCacheSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 3); long audioSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_AUDIO), 0); final long totalSize = lastTotalSizeCalculated = cacheSize + cacheTempSize + videoSize + audioSize + photoSize + documentsSize + musicSize + stickersCacheSize; lastTotalSizeCalculatedTime = System.currentTimeMillis(); if (!canceled) { AndroidUtilities.runOnUIThread(() -> { onDone.run(totalSize); }); } }); } public static void resetCalculatedTotalSIze() { lastTotalSizeCalculated = null; } public static void getDeviceTotalSize(Utilities.Callback2<Long, Long> onDone) { if (lastDeviceTotalSize != null && lastDeviceTotalFreeSize != null) { if (onDone != null) { onDone.run(lastDeviceTotalSize, lastDeviceTotalFreeSize); } return; } File path; if (Build.VERSION.SDK_INT >= 19) { ArrayList<File> storageDirs = AndroidUtilities.getRootDirs(); String dir = (path = storageDirs.get(0)).getAbsolutePath(); if (!TextUtils.isEmpty(SharedConfig.storageCacheDir)) { for (int a = 0, N = storageDirs.size(); a < N; a++) { File file = storageDirs.get(a); if (file.getAbsolutePath().startsWith(SharedConfig.storageCacheDir) && file.canWrite()) { path = file; break; } } } } else { path = new File(SharedConfig.storageCacheDir); } try { StatFs stat = new StatFs(path.getPath()); long blockSize; long blockSizeExternal; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blockSize = stat.getBlockSizeLong(); } else { blockSize = stat.getBlockSize(); } long availableBlocks; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { availableBlocks = stat.getAvailableBlocksLong(); } else { availableBlocks = stat.getAvailableBlocks(); } long blocksTotal; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blocksTotal = stat.getBlockCountLong(); } else { blocksTotal = stat.getBlockCount(); } lastDeviceTotalSize = blocksTotal * blockSize; lastDeviceTotalFreeSize = availableBlocks * blockSize; if (onDone != null) { onDone.run(lastDeviceTotalSize, lastDeviceTotalFreeSize); } return; } catch (Exception e) { FileLog.e(e); } } @Override public boolean onFragmentCreate() { super.onFragmentCreate(); canceled = false; getNotificationCenter().addObserver(this, NotificationCenter.didClearDatabase); databaseSize = MessagesStorage.getInstance(currentAccount).getDatabaseSize(); loadingDialogs = true; Utilities.globalQueue.postRunnable(() -> { cacheSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 5); if (canceled) { return; } cacheTempSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 4); if (canceled) { return; } photoSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE), 0); photoSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE_PUBLIC), 0); if (canceled) { return; } videoSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO), 0); videoSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO_PUBLIC), 0); if (canceled) { return; } documentsSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT), 1); documentsSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES), 1); if (canceled) { return; } musicSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT), 2); musicSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES), 2); if (canceled) { return; } stickersCacheSize = getDirectorySize(new File(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), "acache"), 0); if (canceled) { return; } cacheEmojiSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 3); if (canceled) { return; } stickersCacheSize += cacheEmojiSize; audioSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_AUDIO), 0); if (canceled) { return; } totalSize = lastTotalSizeCalculated = cacheSize + cacheTempSize + videoSize + audioSize + photoSize + documentsSize + musicSize + stickersCacheSize; lastTotalSizeCalculatedTime = System.currentTimeMillis(); File path; if (Build.VERSION.SDK_INT >= 19) { ArrayList<File> storageDirs = AndroidUtilities.getRootDirs(); String dir = (path = storageDirs.get(0)).getAbsolutePath(); if (!TextUtils.isEmpty(SharedConfig.storageCacheDir)) { for (int a = 0, N = storageDirs.size(); a < N; a++) { File file = storageDirs.get(a); if (file.getAbsolutePath().startsWith(SharedConfig.storageCacheDir)) { path = file; break; } } } } else { path = new File(SharedConfig.storageCacheDir); } try { StatFs stat = new StatFs(path.getPath()); long blockSize; long blockSizeExternal; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blockSize = stat.getBlockSizeLong(); } else { blockSize = stat.getBlockSize(); } long availableBlocks; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { availableBlocks = stat.getAvailableBlocksLong(); } else { availableBlocks = stat.getAvailableBlocks(); } long blocksTotal; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blocksTotal = stat.getBlockCountLong(); } else { blocksTotal = stat.getBlockCount(); } totalDeviceSize = blocksTotal * blockSize; totalDeviceFreeSize = availableBlocks * blockSize; } catch (Exception e) { FileLog.e(e); } AndroidUtilities.runOnUIThread(() -> { resumeDelayedFragmentAnimation(); calculating = false; updateRows(true); updateChart(); }); loadDialogEntities(); }); fragmentCreateTime = System.currentTimeMillis(); updateRows(false); updateChart(); return true; } private void updateChart() { if (cacheChart != null) { if (!calculating && totalSize > 0) { CacheChart.SegmentSize[] segments = new CacheChart.SegmentSize[9]; for (int i = 0; i < itemInners.size(); ++i) { ItemInner item = itemInners.get(i); if (item.viewType == VIEW_TYPE_SECTION) { if (item.index < 0) { if (collapsed) { segments[8] = CacheChart.SegmentSize.of(item.size, selected[8]); } } else { segments[item.index] = CacheChart.SegmentSize.of(item.size, selected[item.index]); } } } if (System.currentTimeMillis() - fragmentCreateTime < 80) { cacheChart.loadingFloat.set(0, true); } cacheChart.setSegments(totalSize, true, segments); } else if (calculating) { cacheChart.setSegments(-1, true); } else { cacheChart.setSegments(0, true); } } if (clearCacheButton != null && !calculating) { clearCacheButton.updateSize(); } } private void loadDialogEntities() { getFileLoader().getFileDatabase().getQueue().postRunnable(() -> { getFileLoader().getFileDatabase().ensureDatabaseCreated(); CacheModel cacheModel = new CacheModel(false); LongSparseArray<DialogFileEntities> dilogsFilesEntities = new LongSparseArray<>(); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), TYPE_OTHER, dilogsFilesEntities, null); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE), TYPE_PHOTOS, dilogsFilesEntities, cacheModel); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE_PUBLIC), TYPE_PHOTOS, dilogsFilesEntities, cacheModel); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO), TYPE_VIDEOS, dilogsFilesEntities, cacheModel); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO_PUBLIC), TYPE_VIDEOS, dilogsFilesEntities, cacheModel); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_AUDIO), TYPE_VOICE, dilogsFilesEntities, cacheModel); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT), TYPE_DOCUMENTS, dilogsFilesEntities, cacheModel); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES), TYPE_DOCUMENTS, dilogsFilesEntities, cacheModel); ArrayList<DialogFileEntities> entities = new ArrayList<>(); ArrayList<Long> unknownUsers = new ArrayList<>(); ArrayList<Long> unknownChats = new ArrayList<>(); for (int i = 0; i < dilogsFilesEntities.size(); i++) { DialogFileEntities dialogEntities = dilogsFilesEntities.valueAt(i); entities.add(dialogEntities); if (getMessagesController().getUserOrChat(entities.get(i).dialogId) == null) { if (dialogEntities.dialogId > 0) { unknownUsers.add(dialogEntities.dialogId); } else { unknownChats.add(dialogEntities.dialogId); } } } cacheModel.sortBySize(); getMessagesStorage().getStorageQueue().postRunnable(() -> { ArrayList<TLRPC.User> users = new ArrayList<>(); ArrayList<TLRPC.Chat> chats = new ArrayList<>(); if (!unknownUsers.isEmpty()) { try { getMessagesStorage().getUsersInternal(TextUtils.join(",", unknownUsers), users); } catch (Exception e) { FileLog.e(e); } } if (!unknownChats.isEmpty()) { try { getMessagesStorage().getChatsInternal(TextUtils.join(",", unknownChats), chats); } catch (Exception e) { FileLog.e(e); } } for (int i = 0; i < entities.size(); i++) { if (entities.get(i).totalSize <= 0) { entities.remove(i); i--; } } sort(entities); AndroidUtilities.runOnUIThread(() -> { loadingDialogs = false; getMessagesController().putUsers(users, true); getMessagesController().putChats(chats, true); DialogFileEntities unknownChatsEntity = null; for (int i = 0; i < entities.size(); i++) { DialogFileEntities dialogEntities = entities.get(i); boolean changed = false; if (getMessagesController().getUserOrChat(dialogEntities.dialogId) == null) { dialogEntities.dialogId = UNKNOWN_CHATS_DIALOG_ID; if (unknownChatsEntity != null) { changed = true; unknownChatsEntity.merge(dialogEntities); entities.remove(i); i--; } else { unknownChatsEntity = dialogEntities; } if (changed) { sort(entities); } } } cacheModel.setEntities(entities); if (!canceled) { setCacheModel(cacheModel); updateRows(); updateChart(); if (cacheChartHeader != null && !calculating && System.currentTimeMillis() - fragmentCreateTime > 120) { cacheChartHeader.setData( totalSize > 0, totalDeviceSize <= 0 ? 0 : (float) totalSize / totalDeviceSize, totalDeviceFreeSize <= 0 || totalDeviceSize <= 0 ? 0 : (float) (totalDeviceSize - totalDeviceFreeSize) / totalDeviceSize ); } } }); }); }); } private void sort(ArrayList<DialogFileEntities> entities) { Collections.sort(entities, (o1, o2) -> { if (o2.totalSize > o1.totalSize) { return 1; } else if (o2.totalSize < o1.totalSize) { return -1; } return 0; }); } CacheModel cacheModel; public void setCacheModel(CacheModel cacheModel) { this.cacheModel = cacheModel; if (cachedMediaLayout != null) { cachedMediaLayout.setCacheModel(cacheModel); } } public void fillDialogsEntitiesRecursive(final File fromFolder, int type, LongSparseArray<DialogFileEntities> dilogsFilesEntities, CacheModel cacheModel) { if (fromFolder == null) { return; } File[] files = fromFolder.listFiles(); if (files == null) { return; } for (final File fileEntry : files) { if (canceled) { return; } if (fileEntry.isDirectory()) { fillDialogsEntitiesRecursive(fileEntry, type, dilogsFilesEntities, cacheModel); } else { if (fileEntry.getName().equals(".nomedia")) { continue; } FilePathDatabase.FileMeta fileMetadata = getFileLoader().getFileDatabase().getFileDialogId(fileEntry, null); int addToType = type; String fileName = fileEntry.getName().toLowerCase(); if (fileName.endsWith(".mp3") || fileName.endsWith(".m4a") ) { addToType = TYPE_MUSIC; } CacheModel.FileInfo fileInfo = new CacheModel.FileInfo(fileEntry); fileInfo.type = addToType; if (fileMetadata != null) { fileInfo.dialogId = fileMetadata.dialogId; fileInfo.messageId = fileMetadata.messageId; fileInfo.messageType = fileMetadata.messageType; } fileInfo.size = fileEntry.length(); if (fileInfo.dialogId != 0) { DialogFileEntities dilogEntites = dilogsFilesEntities.get(fileInfo.dialogId, null); if (dilogEntites == null) { dilogEntites = new DialogFileEntities(fileInfo.dialogId); dilogsFilesEntities.put(fileInfo.dialogId, dilogEntites); } dilogEntites.addFile(fileInfo, addToType); } if (cacheModel != null) { cacheModel.add(addToType, fileInfo); } //TODO measure for other accounts // for (int i = 0; i < UserConfig.MAX_ACCOUNT_COUNT; i++) { // if (i != currentAccount && UserConfig.getInstance(currentAccount).isClientActivated()) { // FileLoader.getInstance(currentAccount).getFileDatabase().getFileDialogId(fileEntry); // } // } } } } private ArrayList<ItemInner> oldItems = new ArrayList<>(); private ArrayList<ItemInner> itemInners = new ArrayList<>(); private String formatPercent(float k) { return formatPercent(k, true); } private String formatPercent(float k, boolean minimize) { if (minimize && k < 0.001f) { return String.format("<%.1f%%", 0.1f); } final float p = Math.round(k * 100f); if (minimize && p <= 0) { return String.format("<%d%%", 1); } return String.format("%d%%", (int) p); } private CharSequence getCheckBoxTitle(CharSequence header, int percent) { return getCheckBoxTitle(header, percent, false); } private CharSequence getCheckBoxTitle(CharSequence header, int percent, boolean addArrow) { String percentString = percent <= 0 ? String.format("<%.1f%%", 1f) : String.format("%d%%", percent); SpannableString percentStr = new SpannableString(percentString); percentStr.setSpan(new RelativeSizeSpan(.834f), 0, percentStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); percentStr.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")), 0, percentStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); SpannableStringBuilder string = new SpannableStringBuilder(header); string.append(" "); string.append(percentStr); return string; } private void updateRows() { updateRows(true); } private void updateRows(boolean animated) { if (animated && System.currentTimeMillis() - fragmentCreateTime < 80) { animated = false; } oldItems.clear(); oldItems.addAll(itemInners); itemInners.clear(); itemInners.add(new ItemInner(VIEW_TYPE_CHART, null, null)); itemInners.add(new ItemInner(VIEW_TYPE_CHART_HEADER, null, null)); sectionsStartRow = itemInners.size(); boolean hasCache = false; if (calculating) { itemInners.add(new ItemInner(VIEW_TYPE_SECTION_LOADING, null, null)); itemInners.add(new ItemInner(VIEW_TYPE_SECTION_LOADING, null, null)); itemInners.add(new ItemInner(VIEW_TYPE_SECTION_LOADING, null, null)); itemInners.add(new ItemInner(VIEW_TYPE_SECTION_LOADING, null, null)); itemInners.add(new ItemInner(VIEW_TYPE_SECTION_LOADING, null, null)); hasCache = true; } else { ArrayList<ItemInner> sections = new ArrayList<>(); if (photoSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalPhotoCache), 0, photoSize, Theme.key_statisticChartLine_lightblue)); } if (videoSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalVideoCache), 1, videoSize, Theme.key_statisticChartLine_blue)); } if (documentsSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalDocumentCache), 2, documentsSize, Theme.key_statisticChartLine_green)); } if (musicSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalMusicCache), 3, musicSize, Theme.key_statisticChartLine_red)); } if (audioSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalAudioCache), 4, audioSize, Theme.key_statisticChartLine_lightgreen)); } if (stickersCacheSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalStickersCache), 5, stickersCacheSize, Theme.key_statisticChartLine_orange)); } if (cacheSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalProfilePhotosCache), 6, cacheSize, Theme.key_statisticChartLine_cyan)); } if (cacheTempSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalMiscellaneousCache), 7, cacheTempSize, Theme.key_statisticChartLine_purple)); } if (!sections.isEmpty()) { Collections.sort(sections, (a, b) -> Long.compare(b.size, a.size)); sections.get(sections.size() - 1).last = true; hasCache = true; if (tempSizes == null) { tempSizes = new float[9]; } for (int i = 0; i < tempSizes.length; ++i) { tempSizes[i] = (float) size(i); } if (percents == null) { percents = new int[9]; } AndroidUtilities.roundPercents(tempSizes, percents); final int MAX_NOT_COLLAPSED = 4; if (sections.size() > MAX_NOT_COLLAPSED + 1) { itemInners.addAll(sections.subList(0, MAX_NOT_COLLAPSED)); int sumPercents = 0; long sum = 0; for (int i = MAX_NOT_COLLAPSED; i < sections.size(); ++i) { sections.get(i).pad = true; sum += sections.get(i).size; sumPercents += percents[sections.get(i).index]; } percents[8] = sumPercents; itemInners.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalOther), -1, sum, Theme.key_statisticChartLine_golden)); if (!collapsed) { itemInners.addAll(sections.subList(MAX_NOT_COLLAPSED, sections.size())); } } else { itemInners.addAll(sections); } } } if (hasCache) { sectionsEndRow = itemInners.size(); itemInners.add(new ItemInner(VIEW_TYPE_CLEAR_CACHE_BUTTON, null, null)); itemInners.add(ItemInner.asInfo(LocaleController.getString("StorageUsageInfo", R.string.StorageUsageInfo))); } else { sectionsEndRow = -1; } itemInners.add(new ItemInner(VIEW_TYPE_HEADER, LocaleController.getString("AutoDeleteCachedMedia", R.string.AutoDeleteCachedMedia), null)); itemInners.add(new ItemInner(VIEW_TYPE_KEEP_MEDIA_CELL, KEEP_MEDIA_TYPE_USER)); itemInners.add(new ItemInner(VIEW_TYPE_KEEP_MEDIA_CELL, KEEP_MEDIA_TYPE_GROUP)); itemInners.add(new ItemInner(VIEW_TYPE_KEEP_MEDIA_CELL, KEEP_MEDIA_TYPE_CHANNEL)); itemInners.add(ItemInner.asInfo(LocaleController.getString("KeepMediaInfoPart", R.string.KeepMediaInfoPart))); if (totalDeviceSize > 0) { itemInners.add(new ItemInner(VIEW_TYPE_HEADER, LocaleController.getString("MaxCacheSize", R.string.MaxCacheSize), null)); itemInners.add(new ItemInner(VIEW_TYPE_MAX_CACHE_SIZE)); itemInners.add(ItemInner.asInfo(LocaleController.getString("MaxCacheSizeInfo", R.string.MaxCacheSizeInfo))); } if (hasCache && cacheModel != null && !cacheModel.isEmpty()) { itemInners.add(new ItemInner(VIEW_TYPE_CACHE_VIEW_PAGER, null, null)); } if (listAdapter != null) { if (animated) { listAdapter.setItems(oldItems, itemInners); } else { listAdapter.notifyDataSetChanged(); } } if (cachedMediaLayout != null) { cachedMediaLayout.update(); } } @Override public boolean needDelayOpenAnimation() { return true; } @Override public void onFragmentDestroy() { super.onFragmentDestroy(); getNotificationCenter().removeObserver(this, NotificationCenter.didClearDatabase); try { if (progressDialog != null) { progressDialog.dismiss(); } } catch (Exception e) { } progressDialog = null; canceled = true; } private static long getDirectorySize(File dir, int documentsMusicType) { if (dir == null || canceled) { return 0; } long size = 0; if (dir.isDirectory()) { size = Utilities.getDirSize(dir.getAbsolutePath(), documentsMusicType, false); } else if (dir.isFile()) { size += dir.length(); } return size; } private void cleanupFolders() { if (cacheModel != null) { cacheModel.clearSelection(); } if (cachedMediaLayout != null) { cachedMediaLayout.updateVisibleRows(); cachedMediaLayout.showActionMode(false); } progressDialog = new AlertDialog(getParentActivity(), AlertDialog.ALERT_TYPE_SPINNER); progressDialog.setCanCancel(false); progressDialog.showDelayed(500); getFileLoader().cancelLoadAllFiles(); getFileLoader().getFileLoaderQueue().postRunnable(() -> Utilities.globalQueue.postRunnable(() -> { cleanupFoldersInternal(); })); setCacheModel(null); loadingDialogs = true; // updateRows(); } private void cleanupFoldersInternal() { boolean imagesCleared = false; long clearedSize = 0; boolean allItemsClear = true; for (int a = 0; a < 8; a++) { if (!selected[a]) { allItemsClear = false; continue; } int type = -1; int documentsMusicType = 0; if (a == 0) { type = FileLoader.MEDIA_DIR_IMAGE; clearedSize += photoSize; } else if (a == 1) { type = FileLoader.MEDIA_DIR_VIDEO; clearedSize += videoSize; } else if (a == 2) { type = FileLoader.MEDIA_DIR_DOCUMENT; documentsMusicType = 1; clearedSize += documentsSize; } else if (a == 3) { type = FileLoader.MEDIA_DIR_DOCUMENT; documentsMusicType = 2; clearedSize += musicSize; } else if (a == 4) { type = FileLoader.MEDIA_DIR_AUDIO; clearedSize += audioSize; } else if (a == 5) { type = 100; clearedSize += stickersCacheSize + cacheEmojiSize; } else if (a == 6) { clearedSize += cacheSize; documentsMusicType = 5; type = FileLoader.MEDIA_DIR_CACHE; } else if (a == 7) { clearedSize += cacheTempSize; documentsMusicType = 4; type = FileLoader.MEDIA_DIR_CACHE; } if (type == -1) { continue; } File file; if (type == 100) { file = new File(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), "acache"); } else { file = FileLoader.checkDirectory(type); } if (file != null) { Utilities.clearDir(file.getAbsolutePath(), documentsMusicType, Long.MAX_VALUE, false); } if (type == 100) { file = FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE); if (file != null) { Utilities.clearDir(file.getAbsolutePath(), 3, Long.MAX_VALUE, false); } } if (type == FileLoader.MEDIA_DIR_IMAGE || type == FileLoader.MEDIA_DIR_VIDEO) { int publicDirectoryType; if (type == FileLoader.MEDIA_DIR_IMAGE) { publicDirectoryType = FileLoader.MEDIA_DIR_IMAGE_PUBLIC; } else { publicDirectoryType = FileLoader.MEDIA_DIR_VIDEO_PUBLIC; } file = FileLoader.checkDirectory(publicDirectoryType); if (file != null) { Utilities.clearDir(file.getAbsolutePath(), documentsMusicType, Long.MAX_VALUE, false); } } if (type == FileLoader.MEDIA_DIR_DOCUMENT) { file = FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES); if (file != null) { Utilities.clearDir(file.getAbsolutePath(), documentsMusicType, Long.MAX_VALUE, false); } } if (type == FileLoader.MEDIA_DIR_CACHE) { cacheSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 5); cacheTempSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 4); imagesCleared = true; } else if (type == FileLoader.MEDIA_DIR_AUDIO) { audioSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_AUDIO), documentsMusicType); } else if (type == FileLoader.MEDIA_DIR_DOCUMENT) { if (documentsMusicType == 1) { documentsSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT), documentsMusicType); documentsSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES), documentsMusicType); } else { musicSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT), documentsMusicType); musicSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES), documentsMusicType); } } else if (type == FileLoader.MEDIA_DIR_IMAGE) { imagesCleared = true; photoSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE), documentsMusicType); photoSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE_PUBLIC), documentsMusicType); } else if (type == FileLoader.MEDIA_DIR_VIDEO) { videoSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO), documentsMusicType); videoSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO_PUBLIC), documentsMusicType); } else if (type == 100) { imagesCleared = true; stickersCacheSize = getDirectorySize(new File(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), "acache"), documentsMusicType); cacheEmojiSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 3); stickersCacheSize += cacheEmojiSize; } } final boolean imagesClearedFinal = imagesCleared; totalSize = lastTotalSizeCalculated = cacheSize + cacheTempSize + videoSize + audioSize + photoSize + documentsSize + musicSize + stickersCacheSize; lastTotalSizeCalculatedTime = System.currentTimeMillis(); Arrays.fill(selected, true); File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) { blockSize = stat.getBlockSizeLong(); } else { blockSize = stat.getBlockSize(); } long availableBlocks; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) { availableBlocks = stat.getAvailableBlocksLong(); } else { availableBlocks = stat.getAvailableBlocks(); } long blocksTotal; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) { blocksTotal = stat.getBlockCountLong(); } else { blocksTotal = stat.getBlockCount(); } totalDeviceSize = blocksTotal * blockSize; totalDeviceFreeSize = availableBlocks * blockSize; long finalClearedSize = clearedSize; if (allItemsClear) { FileLoader.getInstance(currentAccount).clearFilePaths(); } FileLoader.getInstance(currentAccount).checkCurrentDownloadsFiles(); AndroidUtilities.runOnUIThread(() -> { if (imagesClearedFinal) { ImageLoader.getInstance().clearMemory(); } try { if (progressDialog != null) { progressDialog.dismiss(); progressDialog = null; } } catch (Exception e) { FileLog.e(e); } getMediaDataController().ringtoneDataStore.checkRingtoneSoundsLoaded(); AndroidUtilities.runOnUIThread(() -> { cacheRemovedTooltip.setInfoText(LocaleController.formatString("CacheWasCleared", R.string.CacheWasCleared, AndroidUtilities.formatFileSize(finalClearedSize))); cacheRemovedTooltip.showWithAction(0, UndoView.ACTION_CACHE_WAS_CLEARED, null, null); }, 150); MediaDataController.getInstance(currentAccount).chekAllMedia(true); loadDialogEntities(); }); } private boolean changeStatusBar; @Override public void onTransitionAnimationProgress(boolean isOpen, float progress) { if (progress > .5f && !changeStatusBar) { changeStatusBar = true; NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.needCheckSystemBarColors); } super.onTransitionAnimationProgress(isOpen, progress); } @Override public boolean isLightStatusBar() { if (!changeStatusBar) { return super.isLightStatusBar(); } return AndroidUtilities.computePerceivedBrightness(Theme.getColor(Theme.key_windowBackgroundGray)) > 0.721f; } private long size(int type) { switch (type) { case 0: return photoSize; case 1: return videoSize; case 2: return documentsSize; case 3: return musicSize; case 4: return audioSize; case 5: return stickersCacheSize; case 6: return cacheSize; case 7: return cacheTempSize; default: return 0; } } private int sectionsSelected() { int count = 0; for (int i = 0; i < 8; ++i) { if (selected[i] && size(i) > 0) { count++; } } return count; } private ActionBarMenu actionMode; private AnimatedTextView actionModeTitle; private AnimatedTextView actionModeSubtitle; private TextView actionModeClearButton; @Override public View createView(Context context) { actionBar.setBackgroundDrawable(null); actionBar.setCastShadows(false); actionBar.setAddToContainer(false); actionBar.setOccupyStatusBar(true); actionBar.setTitleColor(ColorUtils.setAlphaComponent(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText), 0)); actionBar.setItemsColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText), false); actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_listSelector), false); actionBar.setBackButtonDrawable(new BackDrawable(false)); actionBar.setAllowOverlayTitle(false); actionBar.setTitle(LocaleController.getString("StorageUsage", R.string.StorageUsage)); actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override public void onItemClick(int id) { if (id == -1) { if (actionBar.isActionModeShowed()) { if (cacheModel != null) { cacheModel.clearSelection(); } if (cachedMediaLayout != null) { cachedMediaLayout.showActionMode(false); cachedMediaLayout.updateVisibleRows(); } return; } finishFragment(); } else if (id == delete_id) { clearSelectedFiles(); } else if (id == clear_database_id) { clearDatabase(); } } }); actionMode = actionBar.createActionMode(); FrameLayout actionModeLayout = new FrameLayout(context); actionMode.addView(actionModeLayout, LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, 72, 0, 0, 0)); actionModeTitle = new AnimatedTextView(context, true, true, true); actionModeTitle.setAnimationProperties(.35f, 0, 350, CubicBezierInterpolator.EASE_OUT_QUINT); actionModeTitle.setTextSize(AndroidUtilities.dp(18)); actionModeTitle.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); actionModeTitle.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); actionModeLayout.addView(actionModeTitle, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.LEFT | Gravity.CENTER_VERTICAL, 0, -11, 0, 0)); actionModeSubtitle = new AnimatedTextView(context, true, true, true); actionModeSubtitle.setAnimationProperties(.35f, 0, 350, CubicBezierInterpolator.EASE_OUT_QUINT); actionModeSubtitle.setTextSize(AndroidUtilities.dp(14)); actionModeSubtitle.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText)); actionModeLayout.addView(actionModeSubtitle, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.LEFT | Gravity.CENTER_VERTICAL, 0, 10, 0, 0)); actionModeClearButton = new TextView(context); actionModeClearButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); actionModeClearButton.setPadding(AndroidUtilities.dp(14), 0, AndroidUtilities.dp(14), 0); actionModeClearButton.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText)); actionModeClearButton.setBackground(Theme.AdaptiveRipple.filledRect(Theme.key_featuredStickers_addButton, 6)); actionModeClearButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); actionModeClearButton.setGravity(Gravity.CENTER); actionModeClearButton.setText(LocaleController.getString("CacheClear", R.string.CacheClear)); actionModeClearButton.setOnClickListener(e -> clearSelectedFiles()); actionModeLayout.addView(actionModeClearButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 28, Gravity.RIGHT | Gravity.CENTER_VERTICAL, 0, 0, 14, 0)); ActionBarMenuItem otherItem = actionBar.createMenu().addItem(other_id, R.drawable.ic_ab_other); clearDatabaseItem = otherItem.addSubItem(clear_database_id, R.drawable.msg_delete, LocaleController.getString("ClearLocalDatabase", R.string.ClearLocalDatabase)); clearDatabaseItem.setIconColor(Theme.getColor(Theme.key_dialogRedIcon)); clearDatabaseItem.setTextColor(Theme.getColor(Theme.key_dialogTextRed)); updateDatabaseItemSize(); listAdapter = new ListAdapter(context); nestedSizeNotifierLayout = new NestedSizeNotifierLayout(context) { @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); boolean show = !isPinnedToTop(); if (!show && actionBarShadowAlpha != 0) { actionBarShadowAlpha -= 16f / 100f; invalidate(); } else if (show && actionBarShadowAlpha != 1f) { actionBarShadowAlpha += 16f / 100f; invalidate(); } actionBarShadowAlpha = Utilities.clamp(actionBarShadowAlpha, 1f, 0); if (parentLayout != null) { parentLayout.drawHeaderShadow(canvas, (int) (0xFF * actionBarShownT * actionBarShadowAlpha), AndroidUtilities.statusBarHeight + ActionBar.getCurrentActionBarHeight()); } } }; fragmentView = nestedSizeNotifierLayout; FrameLayout frameLayout = nestedSizeNotifierLayout; frameLayout.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray)); listView = new RecyclerListView(context) { @Override protected void dispatchDraw(Canvas canvas) { if (sectionsStartRow >= 0 && sectionsEndRow >= 0) { drawSectionBackgroundExclusive(canvas, sectionsStartRow - 1, sectionsEndRow, Theme.getColor(Theme.key_windowBackgroundWhite)); } super.dispatchDraw(canvas); } @Override protected boolean allowSelectChildAtPosition(View child) { return child != cacheChart; } }; listView.setVerticalScrollBarEnabled(false); listView.setClipToPadding(false); listView.setPadding(0, AndroidUtilities.statusBarHeight + ActionBar.getCurrentActionBarHeight() / 2, 0, 0); listView.setLayoutManager(layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)); frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); listView.setAdapter(listAdapter); DefaultItemAnimator itemAnimator = new DefaultItemAnimator() { @Override protected void onMoveAnimationUpdate(RecyclerView.ViewHolder holder) { listView.invalidate(); } }; itemAnimator.setDurations(350); itemAnimator.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); itemAnimator.setDelayAnimations(false); itemAnimator.setSupportsChangeAnimations(false); listView.setItemAnimator(itemAnimator); listView.setOnItemClickListener((view, position, x, y) -> { if (getParentActivity() == null) { return; } if (position < 0 || position >= itemInners.size()) { return; } ItemInner item = itemInners.get(position); // if (position == databaseRow) { // clearDatabase(); // } else if (item.viewType == VIEW_TYPE_SECTION && view instanceof CheckBoxCell) { if (item.index < 0) { collapsed = !collapsed; updateRows(); updateChart(); return; } toggleSection(item, view); } else if (item.entities != null) { // if (view instanceof UserCell && selectedDialogs.size() > 0) { // selectDialog((UserCell) view, itemInners.get(position).entities.dialogId); // return; // } showClearCacheDialog(item.entities); } else if (item.keepMediaType >= 0) { KeepMediaPopupView windowLayout = new KeepMediaPopupView(this, view.getContext()); ActionBarPopupWindow popupWindow = AlertsCreator.createSimplePopup(CacheControlActivity.this, windowLayout, view, x, y); windowLayout.update(itemInners.get(position).keepMediaType); windowLayout.setParentWindow(popupWindow); windowLayout.setCallback((type, keepMedia) -> { AndroidUtilities.updateVisibleRows(listView); }); } }); listView.addOnScrollListener(new RecyclerView.OnScrollListener() { boolean pinned; @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); updateActionBar(layoutManager.findFirstVisibleItemPosition() > 0 || actionBar.isActionModeShowed()); if (pinned != nestedSizeNotifierLayout.isPinnedToTop()) { pinned = nestedSizeNotifierLayout.isPinnedToTop(); nestedSizeNotifierLayout.invalidate(); } } }); frameLayout.addView(actionBar, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); cacheRemovedTooltip = new UndoView(context); frameLayout.addView(cacheRemovedTooltip, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 8, 0, 8, 8)); nestedSizeNotifierLayout.setTargetListView(listView); return fragmentView; } private void clearSelectedFiles() { if (cacheModel.getSelectedFiles() == 0 || getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setTitle(LocaleController.getString("ClearCache", R.string.ClearCache)); builder.setMessage(LocaleController.getString("ClearCacheForChats", R.string.ClearCacheForChats)); builder.setPositiveButton(LocaleController.getString("Clear", R.string.Clear), (di, which) -> { DialogFileEntities mergedEntities = cacheModel.removeSelectedFiles(); if (mergedEntities.totalSize > 0) { cleanupDialogFiles(mergedEntities, null, null); } cacheModel.clearSelection(); if (cachedMediaLayout != null) { cachedMediaLayout.update(); cachedMediaLayout.showActionMode(false); } updateRows(); updateChart(); }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); AlertDialog dialog = builder.create(); showDialog(dialog); TextView button = (TextView) dialog.getButton(DialogInterface.BUTTON_POSITIVE); if (button != null) { button.setTextColor(Theme.getColor(Theme.key_dialogTextRed)); } } private ValueAnimator actionBarAnimator; private float actionBarShownT; private boolean actionBarShown; private float actionBarShadowAlpha = 1f; private void updateActionBar(boolean show) { if (show != actionBarShown) { if (actionBarAnimator != null) { actionBarAnimator.cancel(); } actionBarAnimator = ValueAnimator.ofFloat(actionBarShownT, (actionBarShown = show) ? 1f : 0f); actionBarAnimator.addUpdateListener(anm -> { actionBarShownT = (float) anm.getAnimatedValue(); actionBar.setTitleColor(ColorUtils.setAlphaComponent(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText), (int) (255 * actionBarShownT))); actionBar.setBackgroundColor(ColorUtils.setAlphaComponent(Theme.getColor(Theme.key_windowBackgroundWhite), (int) (255 * actionBarShownT))); fragmentView.invalidate(); }); actionBarAnimator.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); actionBarAnimator.setDuration(380); actionBarAnimator.start(); } } private void showClearCacheDialog(DialogFileEntities entities) { if (totalSize <= 0 || getParentActivity() == null) { return; } bottomSheet = new DilogCacheBottomSheet(CacheControlActivity.this, entities, entities.createCacheModel(), new DilogCacheBottomSheet.Delegate() { @Override public void onAvatarClick() { bottomSheet.dismiss(); Bundle args = new Bundle(); if (entities.dialogId > 0) { args.putLong("user_id", entities.dialogId); } else { args.putLong("chat_id", -entities.dialogId); } presentFragment(new ProfileActivity(args, null)); } @Override public void cleanupDialogFiles(DialogFileEntities entities, StorageDiagramView.ClearViewData[] clearViewData, CacheModel cacheModel) { CacheControlActivity.this.cleanupDialogFiles(entities, clearViewData, cacheModel); } }); showDialog(bottomSheet); } private void cleanupDialogFiles(DialogFileEntities dialogEntities, StorageDiagramView.ClearViewData[] clearViewData, CacheModel dialogCacheModel) { final AlertDialog progressDialog = new AlertDialog(getParentActivity(), AlertDialog.ALERT_TYPE_SPINNER); progressDialog.setCanCancel(false); progressDialog.showDelayed(500); HashSet<CacheModel.FileInfo> filesToRemove = new HashSet<>(); long totalSizeBefore = totalSize; for (int a = 0; a < 7; a++) { if (clearViewData != null) { if (clearViewData[a] == null || !clearViewData[a].clear) { continue; } } FileEntities entitiesToDelete = dialogEntities.entitiesByType.get(a); if (entitiesToDelete == null) { continue; } filesToRemove.addAll(entitiesToDelete.files); dialogEntities.totalSize -= entitiesToDelete.totalSize; totalSize -= entitiesToDelete.totalSize; totalDeviceFreeSize += entitiesToDelete.totalSize; dialogEntities.entitiesByType.delete(a); if (a == TYPE_PHOTOS) { photoSize -= entitiesToDelete.totalSize; } else if (a == TYPE_VIDEOS) { videoSize -= entitiesToDelete.totalSize; } else if (a == TYPE_DOCUMENTS) { documentsSize -= entitiesToDelete.totalSize; } else if (a == TYPE_MUSIC) { musicSize -= entitiesToDelete.totalSize; } else if (a == TYPE_VOICE) { audioSize -= entitiesToDelete.totalSize; } else if (a == TYPE_ANIMATED_STICKERS_CACHE) { stickersCacheSize -= entitiesToDelete.totalSize; } else { cacheSize -= entitiesToDelete.totalSize; } } if (dialogEntities.entitiesByType.size() == 0) { cacheModel.remove(dialogEntities); } updateRows(); if (dialogCacheModel != null) { for (CacheModel.FileInfo fileInfo : dialogCacheModel.selectedFiles) { if (!filesToRemove.contains(fileInfo)) { totalSize -= fileInfo.size; totalDeviceFreeSize += fileInfo.size; filesToRemove.add(fileInfo); dialogEntities.removeFile(fileInfo); if (fileInfo.type == TYPE_PHOTOS) { photoSize -= fileInfo.size; } else if (fileInfo.type == TYPE_VIDEOS) { videoSize -= fileInfo.size; } else if (fileInfo.size == TYPE_DOCUMENTS) { documentsSize -= fileInfo.size; } else if (fileInfo.size == TYPE_MUSIC) { musicSize -= fileInfo.size; } else if (fileInfo.size == TYPE_VOICE) { audioSize -= fileInfo.size; } } } } for (CacheModel.FileInfo fileInfo : filesToRemove) { this.cacheModel.onFileDeleted(fileInfo); } cacheRemovedTooltip.setInfoText(LocaleController.formatString("CacheWasCleared", R.string.CacheWasCleared, AndroidUtilities.formatFileSize(totalSizeBefore - totalSize))); cacheRemovedTooltip.showWithAction(0, UndoView.ACTION_CACHE_WAS_CLEARED, null, null); ArrayList<CacheModel.FileInfo> fileInfos = new ArrayList<>(filesToRemove); getFileLoader().getFileDatabase().removeFiles(fileInfos); getFileLoader().cancelLoadAllFiles(); getFileLoader().getFileLoaderQueue().postRunnable(() -> { for (int i = 0; i < fileInfos.size(); i++) { fileInfos.get(i).file.delete(); } AndroidUtilities.runOnUIThread(() -> { FileLoader.getInstance(currentAccount).checkCurrentDownloadsFiles(); try { progressDialog.dismiss(); } catch (Exception e) { FileLog.e(e); } }); }); } @RequiresApi(api = Build.VERSION_CODES.R) private void migrateOldFolder() { FilesMigrationService.checkBottomSheet(this); } private void clearDatabase() { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("LocalDatabaseClearTextTitle", R.string.LocalDatabaseClearTextTitle)); SpannableStringBuilder message = new SpannableStringBuilder(); message.append(LocaleController.getString("LocalDatabaseClearText", R.string.LocalDatabaseClearText)); message.append("\n\n"); message.append(AndroidUtilities.replaceTags(LocaleController.formatString("LocalDatabaseClearText2", R.string.LocalDatabaseClearText2, AndroidUtilities.formatFileSize(databaseSize)))); builder.setMessage(message); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); builder.setPositiveButton(LocaleController.getString("CacheClear", R.string.CacheClear), (dialogInterface, i) -> { if (getParentActivity() == null) { return; } progressDialog = new AlertDialog(getParentActivity(), AlertDialog.ALERT_TYPE_SPINNER); progressDialog.setCanCancel(false); progressDialog.showDelayed(500); MessagesController.getInstance(currentAccount).clearQueryTime(); getMessagesStorage().clearLocalDatabase(); }); AlertDialog alertDialog = builder.create(); showDialog(alertDialog); TextView button = (TextView) alertDialog.getButton(DialogInterface.BUTTON_POSITIVE); if (button != null) { button.setTextColor(Theme.getColor(Theme.key_dialogTextRed)); } } @Override public void onResume() { super.onResume(); listAdapter.notifyDataSetChanged(); if (!calculating) { // loadDialogEntities(); } } @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.didClearDatabase) { try { if (progressDialog != null) { progressDialog.dismiss(); } } catch (Exception e) { FileLog.e(e); } progressDialog = null; if (listAdapter != null) { databaseSize = MessagesStorage.getInstance(currentAccount).getDatabaseSize(); updateDatabaseSize = true; updateDatabaseItemSize(); updateRows(); } } } class CacheChartHeader extends FrameLayout { AnimatedTextView title; TextView[] subtitle = new TextView[3]; View bottomImage; RectF progressRect = new RectF(); LoadingDrawable loadingDrawable = new LoadingDrawable(); Float percent, usedPercent; AnimatedFloat percentAnimated = new AnimatedFloat(this, 450, CubicBezierInterpolator.EASE_OUT_QUINT); AnimatedFloat usedPercentAnimated = new AnimatedFloat(this, 450, CubicBezierInterpolator.EASE_OUT_QUINT); AnimatedFloat loadingFloat = new AnimatedFloat(this, 450, CubicBezierInterpolator.EASE_OUT_QUINT); Paint loadingBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG); Paint percentPaint = new Paint(Paint.ANTI_ALIAS_FLAG); Paint usedPercentPaint = new Paint(Paint.ANTI_ALIAS_FLAG); boolean firstSet = true; public CacheChartHeader(Context context) { super(context); title = new AnimatedTextView(context); title.setAnimationProperties(.35f, 0, 350, CubicBezierInterpolator.EASE_OUT_QUINT); title.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); title.setTextSize(AndroidUtilities.dp(20)); title.setText(LocaleController.getString("StorageUsage", R.string.StorageUsage)); title.setGravity(Gravity.CENTER); title.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); addView(title, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 26, Gravity.TOP | Gravity.CENTER_HORIZONTAL)); for (int i = 0; i < 3; ++i) { subtitle[i] = new TextView(context); subtitle[i].setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13); subtitle[i].setGravity(Gravity.CENTER); subtitle[i].setPadding(AndroidUtilities.dp(24), 0, AndroidUtilities.dp(24), 0); if (i == 0) { subtitle[i].setText(LocaleController.getString("StorageUsageCalculating", R.string.StorageUsageCalculating)); } else if (i == 1) { subtitle[i].setAlpha(0); subtitle[i].setText(LocaleController.getString("StorageUsageTelegram", R.string.StorageUsageTelegram)); subtitle[i].setVisibility(View.INVISIBLE); } else if (i == 2) { subtitle[i].setText(LocaleController.getString("StorageCleared2", R.string.StorageCleared2)); subtitle[i].setAlpha(0); subtitle[i].setVisibility(View.INVISIBLE); } subtitle[i].setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText4)); addView(subtitle[i], LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, i == 2 ? 12 : -6, 0, 0)); } bottomImage = new View(context) { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec) + getPaddingLeft() + getPaddingRight(), MeasureSpec.EXACTLY), heightMeasureSpec); } }; Drawable bottomImageDrawable = getContext().getResources().getDrawable(R.drawable.popup_fixed_alert2).mutate(); bottomImageDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhite), PorterDuff.Mode.MULTIPLY)); bottomImage.setBackground(bottomImageDrawable); MarginLayoutParams bottomImageParams = LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 24, Gravity.BOTTOM | Gravity.FILL_HORIZONTAL); bottomImageParams.leftMargin = -bottomImage.getPaddingLeft(); bottomImageParams.bottomMargin = -AndroidUtilities.dp(11); bottomImageParams.rightMargin = -bottomImage.getPaddingRight(); addView(bottomImage, bottomImageParams); int color = Theme.getColor(Theme.key_windowBackgroundWhiteGrayText4); loadingDrawable.setColors( Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), Theme.multAlpha(color, .2f) ); loadingDrawable.setRadiiDp(4); loadingDrawable.setCallback(this); } public void setData(boolean hasCache, float percent, float usedPercent) { title.setText( hasCache ? LocaleController.getString("StorageUsage", R.string.StorageUsage) : LocaleController.getString("StorageCleared", R.string.StorageCleared) ); if (hasCache) { if (percent < 0.01f) { subtitle[1].setText(LocaleController.formatString("StorageUsageTelegramLess", R.string.StorageUsageTelegramLess, formatPercent(percent))); } else { subtitle[1].setText(LocaleController.formatString("StorageUsageTelegram", R.string.StorageUsageTelegram, formatPercent(percent))); } switchSubtitle(1); } else { switchSubtitle(2); } bottomImage.animate().cancel(); if (firstSet) { bottomImage.setAlpha(hasCache ? 1 : 0); } else { bottomImage.animate().alpha(hasCache ? 1 : 0).setDuration(365).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).start(); } firstSet = false; this.percent = percent; this.usedPercent = usedPercent; invalidate(); } private void switchSubtitle(int type) { boolean animated = System.currentTimeMillis() - fragmentCreateTime > 40; updateViewVisible(subtitle[0], type == 0, animated); updateViewVisible(subtitle[1], type == 1, animated); updateViewVisible(subtitle[2], type == 2, animated); } private void updateViewVisible(View view, boolean show, boolean animated) { if (view == null) { return; } if (view.getParent() == null) { animated = false; } view.animate().setListener(null).cancel(); if (!animated) { view.setVisibility(show ? View.VISIBLE : View.INVISIBLE); view.setTag(show ? 1 : null); view.setAlpha(show ? 1f : 0f); view.setTranslationY(show ? 0 : AndroidUtilities.dp(8)); invalidate(); } else if (show) { if (view.getVisibility() != View.VISIBLE) { view.setVisibility(View.VISIBLE); view.setAlpha(0f); view.setTranslationY(AndroidUtilities.dp(8)); } view.animate().alpha(1f).translationY(0).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).setDuration(340).setUpdateListener(anm -> invalidate()).start(); } else { view.animate().alpha(0).translationY(AndroidUtilities.dp(8)).setListener(new HideViewAfterAnimation(view)).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).setDuration(340).setUpdateListener(anm -> invalidate()).start(); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int fullWidth = MeasureSpec.getSize(widthMeasureSpec); int width = (int) Math.min(AndroidUtilities.dp(174), fullWidth * .8); super.measureChildren(MeasureSpec.makeMeasureSpec(fullWidth, MeasureSpec.EXACTLY), heightMeasureSpec); int height = AndroidUtilities.dp(90 - 18); int maxSubtitleHeight = 0; for (int i = 0; i < subtitle.length; ++i) { maxSubtitleHeight = Math.max(maxSubtitleHeight, subtitle[i].getMeasuredHeight() - (i == 2 ? AndroidUtilities.dp(16) : 0)); } height += maxSubtitleHeight; setMeasuredDimension(fullWidth, height); progressRect.set( (fullWidth - width) / 2f, height - AndroidUtilities.dp(30), (fullWidth + width) / 2f, height - AndroidUtilities.dp(30 - 4) ); } @Override protected void dispatchDraw(Canvas canvas) { float barAlpha = 1f - subtitle[2].getAlpha(); float loading = this.loadingFloat.set(this.percent == null ? 1f : 0f); float percent = this.percentAnimated.set(this.percent == null ? 0 : this.percent); float usedPercent = this.usedPercentAnimated.set(this.usedPercent == null ? 0 : this.usedPercent); loadingBackgroundPaint.setColor(Theme.getColor(Theme.key_actionBarActionModeDefaultSelector)); loadingBackgroundPaint.setAlpha((int) (loadingBackgroundPaint.getAlpha() * barAlpha)); AndroidUtilities.rectTmp.set( Math.max( progressRect.left + (1f - loading) * Math.max(AndroidUtilities.dp(4), usedPercent * progressRect.width()), progressRect.left + (1f - loading) * Math.max(AndroidUtilities.dp(4), percent * progressRect.width()) ) + AndroidUtilities.dp(1), progressRect.top, progressRect.right, progressRect.bottom ); if (AndroidUtilities.rectTmp.left < AndroidUtilities.rectTmp.right && AndroidUtilities.rectTmp.width() > AndroidUtilities.dp(3)) { drawRoundRect(canvas, AndroidUtilities.rectTmp, AndroidUtilities.dp(AndroidUtilities.lerp(1, 2, loading)), AndroidUtilities.dp(2), loadingBackgroundPaint); } loadingDrawable.setBounds(progressRect); loadingDrawable.setAlpha((int) (0xFF * barAlpha * loading)); loadingDrawable.draw(canvas); usedPercentPaint.setColor(Theme.percentSV(Theme.getColor(Theme.key_radioBackgroundChecked), Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), .922f, 1.8f)); usedPercentPaint.setAlpha((int) (usedPercentPaint.getAlpha() * barAlpha)); AndroidUtilities.rectTmp.set( progressRect.left + (1f - loading) * Math.max(AndroidUtilities.dp(4), percent * progressRect.width()) + AndroidUtilities.dp(1), progressRect.top, progressRect.left + (1f - loading) * Math.max(AndroidUtilities.dp(4), usedPercent * progressRect.width()), progressRect.bottom ); if (AndroidUtilities.rectTmp.width() > AndroidUtilities.dp(3)) { drawRoundRect(canvas, AndroidUtilities.rectTmp, AndroidUtilities.dp(1), AndroidUtilities.dp(usedPercent > .97f ? 2 : 1), usedPercentPaint); } percentPaint.setColor(Theme.getColor(Theme.key_radioBackgroundChecked)); percentPaint.setAlpha((int) (percentPaint.getAlpha() * barAlpha)); AndroidUtilities.rectTmp.set(progressRect.left, progressRect.top, progressRect.left + (1f - loading) * Math.max(AndroidUtilities.dp(4), percent * progressRect.width()), progressRect.bottom); drawRoundRect(canvas, AndroidUtilities.rectTmp, AndroidUtilities.dp(2), AndroidUtilities.dp(percent > .97f ? 2 : 1), percentPaint); if (loading > 0 || this.percentAnimated.isInProgress()) { invalidate(); } super.dispatchDraw(canvas); } private Path roundPath; private float[] radii; private void drawRoundRect(Canvas canvas, RectF rect, float left, float right, Paint paint) { if (roundPath == null) { roundPath = new Path(); } else { roundPath.rewind(); } if (radii == null) { radii = new float[8]; } radii[0] = radii[1] = radii[6] = radii[7] = left; radii[2] = radii[3] = radii[4] = radii[5] = right; roundPath.addRoundRect(rect, radii, Path.Direction.CW); canvas.drawPath(roundPath, paint); } } private class ClearCacheButtonInternal extends ClearCacheButton { public ClearCacheButtonInternal(Context context) { super(context); ((MarginLayoutParams) button.getLayoutParams()).topMargin = AndroidUtilities.dp(5); button.setOnClickListener(e -> { cleanupFolders(); }); } public void updateSize() { long size = ( (selected[0] ? photoSize : 0) + (selected[1] ? videoSize : 0) + (selected[2] ? documentsSize : 0) + (selected[3] ? musicSize : 0) + (selected[4] ? audioSize : 0) + (selected[5] ? stickersCacheSize : 0) + (selected[6] ? cacheSize : 0) + (selected[7] ? cacheTempSize : 0) ); setSize( isAllSectionsSelected(), size ); } } private boolean isAllSectionsSelected() { for (int i = 0; i < itemInners.size(); ++i) { ItemInner item = itemInners.get(i); if (item.viewType != VIEW_TYPE_SECTION) { continue; } int index = item.index; if (index < 0) { index = selected.length - 1; } if (!selected[index]) { return false; } } return true; } public static class ClearCacheButton extends FrameLayout { FrameLayout button; AnimatedTextView.AnimatedTextDrawable textView; AnimatedTextView.AnimatedTextDrawable valueTextView; TextView rtlTextView; public ClearCacheButton(Context context) { super(context); button = new FrameLayout(context) { @Override protected void dispatchDraw(Canvas canvas) { final int margin = AndroidUtilities.dp(8); int x = (getMeasuredWidth() - margin - (int) valueTextView.getCurrentWidth() + (int) textView.getCurrentWidth()) / 2; if (LocaleController.isRTL) { super.dispatchDraw(canvas); } else { textView.setBounds(0, 0, x, getHeight()); textView.draw(canvas); valueTextView.setBounds(x + AndroidUtilities.dp(8), 0, getWidth(), getHeight()); valueTextView.draw(canvas); } } @Override protected boolean verifyDrawable(@NonNull Drawable who) { return who == valueTextView || who == textView || super.verifyDrawable(who); } @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setClassName("android.widget.Button"); } }; button.setBackground(Theme.AdaptiveRipple.filledRect(Theme.key_featuredStickers_addButton, 8)); button.setFocusable(true); button.setFocusableInTouchMode(true); button.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); if (LocaleController.isRTL) { rtlTextView = new TextView(context); rtlTextView.setText(LocaleController.getString("ClearCache", R.string.ClearCache)); rtlTextView.setGravity(Gravity.CENTER); rtlTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); rtlTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); rtlTextView.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText)); button.addView(rtlTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER)); } textView = new AnimatedTextView.AnimatedTextDrawable(true, true, true); textView.setAnimationProperties(.25f, 0, 300, CubicBezierInterpolator.EASE_OUT_QUINT); textView.setCallback(button); textView.setTextSize(AndroidUtilities.dp(14)); textView.setText(LocaleController.getString("ClearCache", R.string.ClearCache)); textView.setGravity(Gravity.RIGHT); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText)); valueTextView = new AnimatedTextView.AnimatedTextDrawable(true, true, true); valueTextView.setAnimationProperties(.25f, 0, 300, CubicBezierInterpolator.EASE_OUT_QUINT); valueTextView.setCallback(button); valueTextView.setTextSize(AndroidUtilities.dp(14)); valueTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); valueTextView.setTextColor(Theme.adaptHSV(Theme.getColor(Theme.key_featuredStickers_addButton), -.46f, +.08f)); valueTextView.setText(""); setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); addView(button, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.FILL, 16, 16, 16, 16)); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure( MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), heightMeasureSpec ); } public void setSize(boolean allSelected, long size) { textView.setText(( allSelected ? LocaleController.getString("ClearCache", R.string.ClearCache) : LocaleController.getString("ClearSelectedCache", R.string.ClearSelectedCache) )); valueTextView.setText(size <= 0 ? "" : AndroidUtilities.formatFileSize(size)); setDisabled(size <= 0); button.invalidate(); button.setContentDescription(TextUtils.concat(textView.getText(), "\t", valueTextView.getText())); } public void setDisabled(boolean disabled) { button.animate().cancel(); button.animate().alpha(disabled ? .65f : 1f).start(); button.setClickable(!disabled); } } private boolean isOtherSelected() { boolean[] indexes = new boolean[CacheControlActivity.this.selected.length]; for (int i = 0; i < itemInners.size(); ++i) { ItemInner item2 = itemInners.get(i); if (item2.viewType == VIEW_TYPE_SECTION && !item2.pad && item2.index >= 0) { indexes[item2.index] = true; } } for (int i = 0; i < indexes.length; ++i) { if (!indexes[i] && !CacheControlActivity.this.selected[i]) { return false; } } return true; } private void toggleSection(ItemInner item, View cell) { if (item.index < 0) { toggleOtherSelected(cell); return; } if (selected[item.index] && sectionsSelected() <= 1) { BotWebViewVibrationEffect.APP_ERROR.vibrate(); if (cell != null) { AndroidUtilities.shakeViewSpring(cell, -3); } return; } if (cell instanceof CheckBoxCell) { ((CheckBoxCell) cell).setChecked(selected[item.index] = !selected[item.index], true); } else { selected[item.index] = !selected[item.index]; int position = itemInners.indexOf(item); if (position >= 0) { for (int i = 0; i < listView.getChildCount(); ++i) { View child = listView.getChildAt(i); if (child instanceof CheckBoxCell && position == listView.getChildAdapterPosition(child)) { ((CheckBoxCell) child).setChecked(selected[item.index], true); } } } } if (item.pad) { for (int i = 0; i < listView.getChildCount(); ++i) { View child = listView.getChildAt(i); if (child instanceof CheckBoxCell) { int pos = listView.getChildAdapterPosition(child); if (pos >= 0 && pos < itemInners.size() && itemInners.get(pos).index < 0) { ((CheckBoxCell) child).setChecked(isOtherSelected(), true); break; } } } } updateChart(); } private void toggleOtherSelected(View cell) { boolean selected = isOtherSelected(); if (selected) { boolean hasNonOtherSelected = false; for (int i = 0; i < itemInners.size(); ++i) { ItemInner item2 = itemInners.get(i); if (item2.viewType == VIEW_TYPE_SECTION && !item2.pad && item2.index >= 0 && CacheControlActivity.this.selected[item2.index]) { hasNonOtherSelected = true; break; } } if (!hasNonOtherSelected) { BotWebViewVibrationEffect.APP_ERROR.vibrate(); if (cell != null) { AndroidUtilities.shakeViewSpring(cell, -3); } return; } } if (collapsed) { boolean[] indexes = new boolean[CacheControlActivity.this.selected.length]; for (int i = 0; i < itemInners.size(); ++i) { ItemInner item2 = itemInners.get(i); if (item2.viewType == VIEW_TYPE_SECTION && !item2.pad && item2.index >= 0) { indexes[item2.index] = true; } } for (int i = 0; i < indexes.length; ++i) { if (!indexes[i]) { CacheControlActivity.this.selected[i] = !selected; } } } else { for (int i = 0; i < itemInners.size(); ++i) { ItemInner item2 = itemInners.get(i); if (item2.viewType == VIEW_TYPE_SECTION && item2.pad && item2.index >= 0) { CacheControlActivity.this.selected[item2.index] = !selected; } } } for (int i = 0; i < listView.getChildCount(); ++i) { View child = listView.getChildAt(i); if (child instanceof CheckBoxCell) { int pos = listView.getChildAdapterPosition(child); if (pos >= 0) { ItemInner item2 = itemInners.get(pos); if (item2.viewType == VIEW_TYPE_SECTION) { if (item2.index < 0) { ((CheckBoxCell) child).setChecked(!selected, true); } else { ((CheckBoxCell) child).setChecked(CacheControlActivity.this.selected[item2.index], true); } } } } } updateChart(); } private class ListAdapter extends AdapterWithDiffUtils { private Context mContext; public ListAdapter(Context context) { mContext = context; } @Override public boolean isEnabled(RecyclerView.ViewHolder holder) { int position = holder.getAdapterPosition(); return position == migrateOldFolderRow || (holder.getItemViewType() == VIEW_TYPE_STORAGE && (totalSize > 0) && !calculating) || holder.getItemViewType() == VIEW_TYPE_CHAT || holder.getItemViewType() == VIEW_TYPE_KEEP_MEDIA_CELL || holder.getItemViewType() == VIEW_TYPE_SECTION; } @Override public int getItemCount() { return itemInners.size(); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view; switch (viewType) { case VIEW_TYPE_TEXT_SETTINGS: view = new TextSettingsCell(mContext); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); break; case VIEW_TYPE_STORAGE: view = new StorageUsageView(mContext); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); break; case VIEW_TYPE_HEADER: view = new HeaderCell(mContext); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); break; case VIEW_TYPE_CHOOSER: SlideChooseView slideChooseView = new SlideChooseView(mContext); view = slideChooseView; view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); slideChooseView.setCallback(index -> { if (index == 0) { SharedConfig.setKeepMedia(3); } else if (index == 1) { SharedConfig.setKeepMedia(0); } else if (index == 2) { SharedConfig.setKeepMedia(1); } else if (index == 3) { SharedConfig.setKeepMedia(2); } }); int keepMedia = SharedConfig.keepMedia; int index; if (keepMedia == 3) { index = 0; } else { index = keepMedia + 1; } slideChooseView.setOptions(index, LocaleController.formatPluralString("Days", 3), LocaleController.formatPluralString("Weeks", 1), LocaleController.formatPluralString("Months", 1), LocaleController.getString("KeepMediaForever", R.string.KeepMediaForever)); break; case VIEW_TYPE_CHAT: UserCell userCell = new UserCell(getContext(), getResourceProvider()); userCell.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); view = userCell; break; case VIEW_FLICKER_LOADING_DIALOG: FlickerLoadingView flickerLoadingView = new FlickerLoadingView(getContext()); flickerLoadingView.setIsSingleCell(true); flickerLoadingView.setItemsCount(3); flickerLoadingView.setIgnoreHeightCheck(true); flickerLoadingView.setViewType(FlickerLoadingView.DIALOG_CACHE_CONTROL); flickerLoadingView.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); view = flickerLoadingView; break; case VIEW_TYPE_KEEP_MEDIA_CELL: view = new TextCell(mContext); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); break; case VIEW_TYPE_CHART: view = cacheChart = new CacheChart(mContext) { @Override protected void onSectionClick(int index) { // if (index == 8) { // index = -1; // } // for (int i = 0; i < itemInners.size(); ++i) { // ItemInner item = itemInners.get(i); // if (item != null && item.index == index) { // toggleSection(item, null); // return; // } // } } @Override protected void onSectionDown(int index, boolean down) { if (!down) { listView.removeHighlightRow(); return; } if (index == 8) { index = -1; } int position = -1; for (int i = 0; i < itemInners.size(); ++i) { ItemInner item2 = itemInners.get(i); if (item2 != null && item2.viewType == VIEW_TYPE_SECTION && item2.index == index) { position = i; break; } } if (position >= 0) { final int finalPosition = position; listView.highlightRow(() -> finalPosition, 0); } else { listView.removeHighlightRow(); } } }; break; case VIEW_TYPE_CHART_HEADER: view = cacheChartHeader = new CacheChartHeader(mContext); break; case VIEW_TYPE_SECTION_LOADING: FlickerLoadingView flickerLoadingView2 = new FlickerLoadingView(getContext()); flickerLoadingView2.setIsSingleCell(true); flickerLoadingView2.setItemsCount(1); flickerLoadingView2.setIgnoreHeightCheck(true); flickerLoadingView2.setViewType(FlickerLoadingView.CHECKBOX_TYPE); flickerLoadingView2.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); view = flickerLoadingView2; break; case VIEW_TYPE_SECTION: view = new CheckBoxCell(mContext, 4, 21, getResourceProvider()); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); break; case VIEW_TYPE_INFO: default: view = new TextInfoPrivacyCell(mContext); break; case VIEW_TYPE_CACHE_VIEW_PAGER: view = cachedMediaLayout = new CachedMediaLayout(mContext, CacheControlActivity.this) { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(heightMeasureSpec) - (ActionBar.getCurrentActionBarHeight() / 2), MeasureSpec.EXACTLY)); } @Override protected void showActionMode(boolean show) { if (show) { updateActionBar(true); actionBar.showActionMode(); } else { actionBar.hideActionMode(); } } @Override protected boolean actionModeIsVisible() { return actionBar.isActionModeShowed(); } }; cachedMediaLayout.setDelegate(new CachedMediaLayout.Delegate() { @Override public void onItemSelected(DialogFileEntities entities, CacheModel.FileInfo fileInfo, boolean longPress) { if (entities != null) { if ((cacheModel.getSelectedFiles() > 0 || longPress)) { cacheModel.toggleSelect(entities); cachedMediaLayout.updateVisibleRows(); updateActionMode(); } else { showClearCacheDialog(entities); } return; } if (fileInfo != null) { cacheModel.toggleSelect(fileInfo); cachedMediaLayout.updateVisibleRows(); updateActionMode(); } } @Override public void clear() { clearSelectedFiles(); } @Override public void clearSelection() { if (cacheModel != null && cacheModel.getSelectedFiles() > 0) { cacheModel.clearSelection(); if (cachedMediaLayout != null) { cachedMediaLayout.showActionMode(false); cachedMediaLayout.updateVisibleRows(); } return; } } }); cachedMediaLayout.setCacheModel(cacheModel); nestedSizeNotifierLayout.setChildLayout(cachedMediaLayout); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); view.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); break; case VIEW_TYPE_CLEAR_CACHE_BUTTON: view = clearCacheButton = new ClearCacheButtonInternal(mContext); break; case VIEW_TYPE_MAX_CACHE_SIZE: SlideChooseView slideChooseView2 = new SlideChooseView(mContext); view = slideChooseView2; view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); float totalSizeInGb = (int) (totalDeviceSize / 1024L / 1024L) / 1000.0f; ArrayList<Integer> options = new ArrayList<>(); // if (BuildVars.DEBUG_PRIVATE_VERSION) { // options.add(1); // } if (totalSizeInGb <= 17) { options.add(2); } if (totalSizeInGb > 5) { options.add(5); } if (totalSizeInGb > 16) { options.add(16); } if (totalSizeInGb > 32) { options.add(32); } options.add(Integer.MAX_VALUE); String[] values = new String[options.size()]; for (int i = 0; i < options.size(); i++) { if (options.get(i) == 1) { values[i] = String.format("300 MB"); } else if (options.get(i) == Integer.MAX_VALUE) { values[i] = LocaleController.getString("NoLimit", R.string.NoLimit); } else { values[i] = String.format("%d GB", options.get(i)); } } slideChooseView2.setCallback(i -> { SharedConfig.getPreferences().edit().putInt("cache_limit", options.get(i)).apply(); }); int currentLimit = SharedConfig.getPreferences().getInt("cache_limit", Integer.MAX_VALUE); int i = options.indexOf(currentLimit); if (i < 0) { i = options.size() - 1; } slideChooseView2.setOptions(i, values); break; } return new RecyclerListView.Holder(view); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { final ItemInner item = itemInners.get(position); switch (holder.getItemViewType()) { case VIEW_TYPE_CHART: // updateChart(); break; case VIEW_TYPE_CHART_HEADER: if (cacheChartHeader != null && !calculating) { cacheChartHeader.setData( totalSize > 0, totalDeviceSize <= 0 ? 0 : (float) totalSize / totalDeviceSize, totalDeviceFreeSize <= 0 || totalDeviceSize <= 0 ? 0 : (float) (totalDeviceSize - totalDeviceFreeSize) / totalDeviceSize ); } break; case VIEW_TYPE_SECTION: CheckBoxCell cell = (CheckBoxCell) holder.itemView; final boolean selected; if (item.index < 0) { selected = isOtherSelected(); } else { selected = CacheControlActivity.this.selected[item.index]; } cell.setText(getCheckBoxTitle(item.headerName, percents[item.index < 0 ? 8 : item.index], item.index < 0), AndroidUtilities.formatFileSize(item.size), selected, item.index < 0 ? !collapsed : !item.last); cell.setCheckBoxColor(item.colorKey, Theme.key_windowBackgroundWhiteGrayIcon, Theme.key_checkboxCheck); cell.setCollapsed(item.index < 0 ? collapsed : null); if (item.index == -1) { cell.setOnSectionsClickListener(e -> { collapsed = !collapsed; updateRows(); updateChart(); }, e -> toggleOtherSelected(cell)); } else { cell.setOnSectionsClickListener(null, null); } cell.setPad(item.pad ? 1 : 0); break; case VIEW_TYPE_KEEP_MEDIA_CELL: TextCell textCell2 = (TextCell) holder.itemView; CacheByChatsController cacheByChatsController = getMessagesController().getCacheByChatsController(); int keepMediaType = item.keepMediaType; int exceptionsCount = cacheByChatsController.getKeepMediaExceptions(itemInners.get(position).keepMediaType).size(); String subtitle = null; if (exceptionsCount > 0) { subtitle = LocaleController.formatPluralString("ExceptionShort", exceptionsCount, exceptionsCount); } String value = CacheByChatsController.getKeepMediaString(cacheByChatsController.getKeepMedia(keepMediaType)); if (itemInners.get(position).keepMediaType == KEEP_MEDIA_TYPE_USER) { textCell2.setTextAndValueAndColorfulIcon(LocaleController.getString("PrivateChats", R.string.PrivateChats), value, true, R.drawable.msg_filled_menu_users, getThemedColor(Theme.key_statisticChartLine_lightblue), true); } else if (itemInners.get(position).keepMediaType == KEEP_MEDIA_TYPE_GROUP) { textCell2.setTextAndValueAndColorfulIcon(LocaleController.getString("GroupChats", R.string.GroupChats), value, true, R.drawable.msg_filled_menu_groups, getThemedColor(Theme.key_statisticChartLine_green), true); } else if (itemInners.get(position).keepMediaType == KEEP_MEDIA_TYPE_CHANNEL) { textCell2.setTextAndValueAndColorfulIcon(LocaleController.getString("CacheChannels", R.string.CacheChannels), value, true, R.drawable.msg_filled_menu_channels, getThemedColor(Theme.key_statisticChartLine_golden), true); } textCell2.setSubtitle(subtitle); break; case VIEW_TYPE_TEXT_SETTINGS: TextSettingsCell textCell = (TextSettingsCell) holder.itemView; // if (position == databaseRow) { // textCell.setTextAndValue(LocaleController.getString("ClearLocalDatabase", R.string.ClearLocalDatabase), AndroidUtilities.formatFileSize(databaseSize), updateDatabaseSize, false); // updateDatabaseSize = false; // } else if (position == migrateOldFolderRow) { textCell.setTextAndValue(LocaleController.getString("MigrateOldFolder", R.string.MigrateOldFolder), null, false); } break; case VIEW_TYPE_INFO: TextInfoPrivacyCell privacyCell = (TextInfoPrivacyCell) holder.itemView; // if (position == databaseInfoRow) { // privacyCell.setText(LocaleController.getString("LocalDatabaseInfo", R.string.LocalDatabaseInfo)); // privacyCell.setBackgroundDrawable(Theme.getThemedDrawable(mContext, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow)); // } else if (position == keepMediaInfoRow) { // privacyCell.setText(AndroidUtilities.replaceTags(LocaleController.getString("KeepMediaInfo", R.string.KeepMediaInfo))); // privacyCell.setBackgroundDrawable(Theme.getThemedDrawable(mContext, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow)); // } else { privacyCell.setText(AndroidUtilities.replaceTags(item.text)); privacyCell.setBackgroundDrawable(Theme.getThemedDrawable(mContext, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow)); // } break; case VIEW_TYPE_STORAGE: StorageUsageView storageUsageView = (StorageUsageView) holder.itemView; storageUsageView.setStorageUsage(calculating, databaseSize, totalSize, totalDeviceFreeSize, totalDeviceSize); break; case VIEW_TYPE_HEADER: HeaderCell headerCell = (HeaderCell) holder.itemView; headerCell.setText(itemInners.get(position).headerName); headerCell.setTopMargin(itemInners.get(position).headerTopMargin); headerCell.setBottomMargin(itemInners.get(position).headerBottomMargin); break; } } @Override public int getItemViewType(int i) { return itemInners.get(i).viewType; } } private void updateActionMode() { if (cacheModel.getSelectedFiles() > 0) { if (cachedMediaLayout != null) { String filesString; if (!cacheModel.selectedDialogs.isEmpty()) { int filesInChats = 0; for (CacheControlActivity.DialogFileEntities entity : cacheModel.entities) { if (cacheModel.selectedDialogs.contains(entity.dialogId)) { filesInChats += entity.filesCount; } } int filesNotInChat = cacheModel.getSelectedFiles() - filesInChats; if (filesNotInChat > 0) { filesString = String.format("%s, %s", LocaleController.formatPluralString("Chats", cacheModel.selectedDialogs.size(), cacheModel.selectedDialogs.size()), LocaleController.formatPluralString("Files", filesNotInChat, filesNotInChat) ); } else { filesString = LocaleController.formatPluralString("Chats", cacheModel.selectedDialogs.size(), cacheModel.selectedDialogs.size()); } } else { filesString = LocaleController.formatPluralString("Files", cacheModel.getSelectedFiles(), cacheModel.getSelectedFiles()); } String sizeString = AndroidUtilities.formatFileSize(cacheModel.getSelectedFilesSize()); actionModeTitle.setText(sizeString); actionModeSubtitle.setText(filesString); cachedMediaLayout.showActionMode(true); } } else { cachedMediaLayout.showActionMode(false); return; } } @Override public ArrayList<ThemeDescription> getThemeDescriptions() { ThemeDescription.ThemeDescriptionDelegate deldegagte = () -> { if (bottomSheet != null) { bottomSheet.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground)); } if (actionTextView != null) { actionTextView.setBackground(Theme.AdaptiveRipple.filledRect(Theme.key_featuredStickers_addButton, 4)); } }; ArrayList<ThemeDescription> arrayList = new ArrayList<>(); arrayList.add(new ThemeDescription(listView, ThemeDescription.FLAG_CELLBACKGROUNDCOLOR, new Class[]{TextSettingsCell.class, SlideChooseView.class, StorageUsageView.class, HeaderCell.class}, null, null, null, Theme.key_windowBackgroundWhite)); arrayList.add(new ThemeDescription(fragmentView, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_windowBackgroundGray)); arrayList.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_actionBarDefault)); arrayList.add(new ThemeDescription(listView, ThemeDescription.FLAG_LISTGLOWCOLOR, null, null, null, null, Theme.key_actionBarDefault)); arrayList.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_ITEMSCOLOR, null, null, null, null, Theme.key_actionBarDefaultIcon)); arrayList.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_TITLECOLOR, null, null, null, null, Theme.key_actionBarDefaultTitle)); arrayList.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SELECTORCOLOR, null, null, null, null, Theme.key_actionBarDefaultSelector)); arrayList.add(new ThemeDescription(listView, ThemeDescription.FLAG_SELECTOR, null, null, null, null, Theme.key_listSelector)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{TextSettingsCell.class}, new String[]{"textView"}, null, null, null, Theme.key_windowBackgroundWhiteBlackText)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{TextSettingsCell.class}, new String[]{"valueTextView"}, null, null, null, Theme.key_windowBackgroundWhiteValueText)); arrayList.add(new ThemeDescription(listView, ThemeDescription.FLAG_BACKGROUNDFILTER, new Class[]{TextInfoPrivacyCell.class}, null, null, null, Theme.key_windowBackgroundGrayShadow)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{TextInfoPrivacyCell.class}, new String[]{"textView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText4)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{HeaderCell.class}, new String[]{"textView"}, null, null, null, Theme.key_windowBackgroundWhiteBlueHeader)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{StorageUsageView.class}, new String[]{"paintFill"}, null, null, null, Theme.key_player_progressBackground)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{StorageUsageView.class}, new String[]{"paintProgress"}, null, null, null, Theme.key_player_progress)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{StorageUsageView.class}, new String[]{"telegramCacheTextView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{StorageUsageView.class}, new String[]{"freeSizeTextView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{StorageUsageView.class}, new String[]{"calculationgTextView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{SlideChooseView.class}, null, null, null, Theme.key_switchTrack)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{SlideChooseView.class}, null, null, null, Theme.key_switchTrackChecked)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{SlideChooseView.class}, null, null, null, Theme.key_windowBackgroundWhiteGrayText)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_windowBackgroundWhiteGrayText)); arrayList.add(new ThemeDescription(bottomSheetView, 0, new Class[]{CheckBoxCell.class}, new String[]{"textView"}, null, null, null, Theme.key_windowBackgroundWhiteBlackText)); arrayList.add(new ThemeDescription(bottomSheetView, 0, new Class[]{CheckBoxCell.class}, new String[]{"valueTextView"}, null, null, null, Theme.key_windowBackgroundWhiteValueText)); arrayList.add(new ThemeDescription(bottomSheetView, 0, new Class[]{CheckBoxCell.class}, Theme.dividerPaint, null, null, Theme.key_divider)); arrayList.add(new ThemeDescription(bottomSheetView, 0, new Class[]{StorageDiagramView.class}, null, null, null, Theme.key_windowBackgroundWhiteBlackText)); arrayList.add(new ThemeDescription(null, 0, new Class[]{TextCheckBoxCell.class}, new String[]{"textView"}, null, null, null, Theme.key_windowBackgroundWhiteBlackText)); arrayList.add(new ThemeDescription(null, 0, null, null, null, deldegagte, Theme.key_dialogBackground)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_blue)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_green)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_red)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_golden)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_lightblue)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_lightgreen)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_orange)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_indigo)); return arrayList; } public static class UserCell extends FrameLayout implements NotificationCenter.NotificationCenterDelegate { public DialogFileEntities dialogFileEntities; private Theme.ResourcesProvider resourcesProvider; private TextView textView; private AnimatedTextView valueTextView; private BackupImageView imageView; private boolean needDivider; private boolean canDisable; protected CheckBox2 checkBox; public UserCell(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); this.resourcesProvider = resourcesProvider; textView = new TextView(context); textView.setSingleLine(); textView.setLines(1); textView.setMaxLines(1); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); textView.setEllipsize(TextUtils.TruncateAt.END); // textView.setEllipsizeByGradient(true); textView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL); textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText, resourcesProvider)); addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 21 : 72, 0, LocaleController.isRTL ? 72 : 21, 0)); valueTextView = new AnimatedTextView(context, true, true, !LocaleController.isRTL); valueTextView.setAnimationProperties(.55f, 0, 320, CubicBezierInterpolator.EASE_OUT_QUINT); valueTextView.setTextSize(AndroidUtilities.dp(16)); valueTextView.setGravity((LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.CENTER_VERTICAL); valueTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteValueText, resourcesProvider)); addView(valueTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.TOP, LocaleController.isRTL ? 21 : 72, 0, LocaleController.isRTL ? 72 : 21, 0)); imageView = new BackupImageView(context); imageView.getAvatarDrawable().setScaleSize(.8f); addView(imageView, LayoutHelper.createFrame(38, 38, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL, 17, 0, 17, 0)); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), AndroidUtilities.dp(50) + (needDivider ? 1 : 0)); int availableWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - AndroidUtilities.dp(34); int width = availableWidth / 2; if (imageView.getVisibility() == VISIBLE) { imageView.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(38), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(38), MeasureSpec.EXACTLY)); } if (valueTextView.getVisibility() == VISIBLE) { valueTextView.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY)); width = availableWidth - valueTextView.getMeasuredWidth() - AndroidUtilities.dp(8); } else { width = availableWidth; } int padding = valueTextView.getMeasuredWidth() + AndroidUtilities.dp(12); if (LocaleController.isRTL) { ((MarginLayoutParams) textView.getLayoutParams()).leftMargin = padding; } else { ((MarginLayoutParams) textView.getLayoutParams()).rightMargin = padding; } textView.measure(MeasureSpec.makeMeasureSpec(width - padding, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY)); if (checkBox != null) { checkBox.measure( MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(24), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(24), MeasureSpec.EXACTLY) ); } } public BackupImageView getImageView() { return imageView; } public TextView getTextView() { return textView; } public void setCanDisable(boolean value) { canDisable = value; } public AnimatedTextView getValueTextView() { return valueTextView; } public void setTextColor(int color) { textView.setTextColor(color); } public void setTextValueColor(int color) { valueTextView.setTextColor(color); } public void setText(CharSequence text, boolean divider) { text = Emoji.replaceEmoji(text, textView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(16), false); textView.setText(text); valueTextView.setVisibility(INVISIBLE); needDivider = divider; setWillNotDraw(!divider); } public void setTextAndValue(CharSequence text, CharSequence value, boolean divider) { setTextAndValue(text, value, false, divider); } public void setTextAndValue(CharSequence text, CharSequence value, boolean animated, boolean divider) { text = Emoji.replaceEmoji(text, textView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(16), false); textView.setText(text); if (value != null) { valueTextView.setText(value, animated); valueTextView.setVisibility(VISIBLE); } else { valueTextView.setVisibility(INVISIBLE); } needDivider = divider; setWillNotDraw(!divider); requestLayout(); } public void setEnabled(boolean value, ArrayList<Animator> animators) { setEnabled(value); if (animators != null) { animators.add(ObjectAnimator.ofFloat(textView, "alpha", value ? 1.0f : 0.5f)); if (valueTextView.getVisibility() == VISIBLE) { animators.add(ObjectAnimator.ofFloat(valueTextView, "alpha", value ? 1.0f : 0.5f)); } } else { textView.setAlpha(value ? 1.0f : 0.5f); if (valueTextView.getVisibility() == VISIBLE) { valueTextView.setAlpha(value ? 1.0f : 0.5f); } } } @Override public void setEnabled(boolean value) { super.setEnabled(value); textView.setAlpha(value || !canDisable ? 1.0f : 0.5f); if (valueTextView.getVisibility() == VISIBLE) { valueTextView.setAlpha(value || !canDisable ? 1.0f : 0.5f); } } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); if (needDivider) { canvas.drawLine(LocaleController.isRTL ? 0 : AndroidUtilities.dp(72), getMeasuredHeight() - 1, getMeasuredWidth() - (LocaleController.isRTL ? AndroidUtilities.dp(72) : 0), getMeasuredHeight() - 1, Theme.dividerPaint); } } @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setText(textView.getText() + (valueTextView != null && valueTextView.getVisibility() == View.VISIBLE ? "\n" + valueTextView.getText() : "")); info.setEnabled(isEnabled()); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.emojiLoaded); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.emojiLoaded); } @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.emojiLoaded) { if (textView != null) { textView.invalidate(); } } } public void setChecked(boolean checked, boolean animated) { if (checkBox == null && !checked) { return; } if (checkBox == null) { checkBox = new CheckBox2(getContext(), 21, resourcesProvider); checkBox.setColor(null, Theme.key_windowBackgroundWhite, Theme.key_checkboxCheck); checkBox.setDrawUnchecked(false); checkBox.setDrawBackgroundAsArc(3); addView(checkBox, LayoutHelper.createFrame(24, 24, 0, 38, 25, 0, 0)); } checkBox.setChecked(checked, animated); } } @Override public void onRequestPermissionsResultFragment(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == 4) { boolean allGranted = true; for (int a = 0; a < grantResults.length; a++) { if (grantResults[a] != PackageManager.PERMISSION_GRANTED) { allGranted = false; break; } } if (allGranted && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && FilesMigrationService.filesMigrationBottomSheet != null) { FilesMigrationService.filesMigrationBottomSheet.migrateOldFolder(); } } } public static class DialogFileEntities { public long dialogId; int filesCount; long totalSize; public final SparseArray<FileEntities> entitiesByType = new SparseArray<>(); public DialogFileEntities(long dialogId) { this.dialogId = dialogId; } public void addFile(CacheModel.FileInfo file, int type) { FileEntities entities = entitiesByType.get(type, null); if (entities == null) { entities = new FileEntities(); entitiesByType.put(type, entities); } entities.count++; long fileSize = file.size; entities.totalSize += fileSize; totalSize += fileSize; filesCount++; entities.files.add(file); } public void merge(DialogFileEntities dialogEntities) { for (int i = 0; i < dialogEntities.entitiesByType.size(); i++) { int type = dialogEntities.entitiesByType.keyAt(i); FileEntities entitesToMerge = dialogEntities.entitiesByType.valueAt(i); FileEntities entities = entitiesByType.get(type, null); if (entities == null) { entities = new FileEntities(); entitiesByType.put(type, entities); } entities.count += entitesToMerge.count; entities.totalSize += entitesToMerge.totalSize; totalSize += entitesToMerge.totalSize; entities.files.addAll(entitesToMerge.files); } filesCount += dialogEntities.filesCount; } public void removeFile(CacheModel.FileInfo fileInfo) { FileEntities entities = entitiesByType.get(fileInfo.type, null); if (entities == null) { return; } if (entities.files.remove(fileInfo)) { entities.count--; entities.totalSize -= fileInfo.size; totalSize -= fileInfo.size; filesCount--; } } public boolean isEmpty() { return totalSize <= 0; } public CacheModel createCacheModel() { CacheModel cacheModel = new CacheModel(true); if (entitiesByType.get(TYPE_PHOTOS) != null) { cacheModel.media.addAll(entitiesByType.get(TYPE_PHOTOS).files); } if (entitiesByType.get(TYPE_VIDEOS) != null) { cacheModel.media.addAll(entitiesByType.get(TYPE_VIDEOS).files); } if (entitiesByType.get(TYPE_DOCUMENTS) != null) { cacheModel.documents.addAll(entitiesByType.get(TYPE_DOCUMENTS).files); } if (entitiesByType.get(TYPE_MUSIC) != null) { cacheModel.music.addAll(entitiesByType.get(TYPE_MUSIC).files); } if (entitiesByType.get(TYPE_VOICE) != null) { cacheModel.voice.addAll(entitiesByType.get(TYPE_VOICE).files); } cacheModel.selectAllFiles(); cacheModel.sortBySize(); return cacheModel; } } public static class FileEntities { public long totalSize; public int count; public ArrayList<CacheModel.FileInfo> files = new ArrayList<>(); } public static class ItemInner extends AdapterWithDiffUtils.Item { int headerTopMargin = 15; int headerBottomMargin = 0; int keepMediaType = -1; CharSequence headerName; String text; DialogFileEntities entities; public int index; public long size; String colorKey; public boolean pad; boolean last; public ItemInner(int viewType, String headerName, DialogFileEntities dialogFileEntities) { super(viewType, true); this.headerName = headerName; this.entities = dialogFileEntities; } public ItemInner(int viewType, int keepMediaType) { super(viewType, true); this.keepMediaType = keepMediaType; } public ItemInner(int viewType, String headerName, int headerTopMargin, int headerBottomMargin, DialogFileEntities dialogFileEntities) { super(viewType, true); this.headerName = headerName; this.headerTopMargin = headerTopMargin; this.headerBottomMargin = headerBottomMargin; this.entities = dialogFileEntities; } private ItemInner(int viewType) { super(viewType, true); } public static ItemInner asCheckBox(CharSequence text, int index, long size, String colorKey) { return asCheckBox(text, index, size, colorKey, false); } public static ItemInner asCheckBox(CharSequence text, int index, long size, String colorKey, boolean last) { ItemInner item = new ItemInner(VIEW_TYPE_SECTION); item.index = index; item.headerName = text; item.size = size; item.colorKey = colorKey; item.last = last; return item; } public static ItemInner asInfo(String text) { ItemInner item = new ItemInner(VIEW_TYPE_INFO); item.text = text; return item; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ItemInner itemInner = (ItemInner) o; if (viewType == itemInner.viewType) { if (viewType == VIEW_TYPE_CHART || viewType == VIEW_TYPE_CHART_HEADER) { return true; } if (viewType == VIEW_TYPE_CHAT && entities != null && itemInner.entities != null) { return entities.dialogId == itemInner.entities.dialogId; } if (viewType == VIEW_TYPE_CACHE_VIEW_PAGER || viewType == VIEW_TYPE_CHOOSER || viewType == VIEW_TYPE_STORAGE || viewType == VIEW_TYPE_TEXT_SETTINGS || viewType == VIEW_TYPE_CLEAR_CACHE_BUTTON) { return true; } if (viewType == VIEW_TYPE_HEADER) { return Objects.equals(headerName, itemInner.headerName); } if (viewType == VIEW_TYPE_INFO) { return Objects.equals(text, itemInner.text); } if (viewType == VIEW_TYPE_SECTION) { return index == itemInner.index && size == itemInner.size; } if (viewType == VIEW_TYPE_KEEP_MEDIA_CELL) { return keepMediaType == itemInner.keepMediaType; } return false; } return false; } } AnimatedTextView selectedDialogsCountTextView; @Override public boolean isSwipeBackEnabled(MotionEvent event) { if (cachedMediaLayout != null) { cachedMediaLayout.getHitRect(AndroidUtilities.rectTmp2); if (!AndroidUtilities.rectTmp2.contains((int) event.getX(), (int) event.getY() - actionBar.getMeasuredHeight())) { return true; } else { return cachedMediaLayout.viewPagerFixed.isCurrentTabFirst(); } } return true; } @Override public boolean onBackPressed() { if (cacheModel != null && !cacheModel.selectedFiles.isEmpty()) { cacheModel.clearSelection(); if (cachedMediaLayout != null) { cachedMediaLayout.showActionMode(false); cachedMediaLayout.updateVisibleRows(); } return false; } return super.onBackPressed(); } }
flyun/chatAir
TMessagesProj/src/main/java/org/telegram/ui/CacheControlActivity.java
41,681
package us.shandian.giga.service; import android.content.Context; import android.os.Handler; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.DiffUtil; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import us.shandian.giga.get.DownloadMission; import us.shandian.giga.get.FinishedMission; import us.shandian.giga.get.Mission; import us.shandian.giga.get.sqlite.FinishedMissionStore; import org.schabi.newpipe.streams.io.StoredDirectoryHelper; import org.schabi.newpipe.streams.io.StoredFileHelper; import us.shandian.giga.util.Utility; import static org.schabi.newpipe.BuildConfig.DEBUG; public class DownloadManager { private static final String TAG = DownloadManager.class.getSimpleName(); enum NetworkState {Unavailable, Operating, MeteredOperating} public static final int SPECIAL_NOTHING = 0; public static final int SPECIAL_PENDING = 1; public static final int SPECIAL_FINISHED = 2; public static final String TAG_AUDIO = "audio"; public static final String TAG_VIDEO = "video"; private static final String DOWNLOADS_METADATA_FOLDER = "pending_downloads"; private final FinishedMissionStore mFinishedMissionStore; private final ArrayList<DownloadMission> mMissionsPending = new ArrayList<>(); private final ArrayList<FinishedMission> mMissionsFinished; private final Handler mHandler; private final File mPendingMissionsDir; private NetworkState mLastNetworkStatus = NetworkState.Unavailable; int mPrefMaxRetry; boolean mPrefMeteredDownloads; boolean mPrefQueueLimit; private boolean mSelfMissionsControl; StoredDirectoryHelper mMainStorageAudio; StoredDirectoryHelper mMainStorageVideo; /** * Create a new instance * * @param context Context for the data source for finished downloads * @param handler Thread required for Messaging */ DownloadManager(@NonNull Context context, Handler handler, StoredDirectoryHelper storageVideo, StoredDirectoryHelper storageAudio) { if (DEBUG) { Log.d(TAG, "new DownloadManager instance. 0x" + Integer.toHexString(this.hashCode())); } mFinishedMissionStore = new FinishedMissionStore(context); mHandler = handler; mMainStorageAudio = storageAudio; mMainStorageVideo = storageVideo; mMissionsFinished = loadFinishedMissions(); mPendingMissionsDir = getPendingDir(context); loadPendingMissions(context); } private static File getPendingDir(@NonNull Context context) { File dir = context.getExternalFilesDir(DOWNLOADS_METADATA_FOLDER); if (testDir(dir)) return dir; dir = new File(context.getFilesDir(), DOWNLOADS_METADATA_FOLDER); if (testDir(dir)) return dir; throw new RuntimeException("path to pending downloads are not accessible"); } private static boolean testDir(@Nullable File dir) { if (dir == null) return false; try { if (!Utility.mkdir(dir, false)) { Log.e(TAG, "testDir() cannot create the directory in path: " + dir.getAbsolutePath()); return false; } File tmp = new File(dir, ".tmp"); if (!tmp.createNewFile()) return false; return tmp.delete();// if the file was created, SHOULD BE deleted too } catch (Exception e) { Log.e(TAG, "testDir() failed: " + dir.getAbsolutePath(), e); return false; } } /** * Loads finished missions from the data source and forgets finished missions whose file does * not exist anymore. */ private ArrayList<FinishedMission> loadFinishedMissions() { ArrayList<FinishedMission> finishedMissions = mFinishedMissionStore.loadFinishedMissions(); // check if the files exists, otherwise, forget the download for (int i = finishedMissions.size() - 1; i >= 0; i--) { FinishedMission mission = finishedMissions.get(i); if (!mission.storage.existsAsFile()) { if (DEBUG) Log.d(TAG, "downloaded file removed: " + mission.storage.getName()); mFinishedMissionStore.deleteMission(mission); finishedMissions.remove(i); } } return finishedMissions; } private void loadPendingMissions(Context ctx) { File[] subs = mPendingMissionsDir.listFiles(); if (subs == null) { Log.e(TAG, "listFiles() returned null"); return; } if (subs.length < 1) { return; } if (DEBUG) { Log.d(TAG, "Loading pending downloads from directory: " + mPendingMissionsDir.getAbsolutePath()); } File tempDir = pickAvailableTemporalDir(ctx); Log.i(TAG, "using '" + tempDir + "' as temporal directory"); for (File sub : subs) { if (!sub.isFile()) continue; if (sub.getName().equals(".tmp")) continue; DownloadMission mis = Utility.readFromFile(sub); if (mis == null || mis.isFinished() || mis.hasInvalidStorage()) { //noinspection ResultOfMethodCallIgnored sub.delete(); continue; } mis.threads = new Thread[0]; boolean exists; try { mis.storage = StoredFileHelper.deserialize(mis.storage, ctx); exists = !mis.storage.isInvalid() && mis.storage.existsAsFile(); } catch (Exception ex) { Log.e(TAG, "Failed to load the file source of " + mis.storage.toString(), ex); mis.storage.invalidate(); exists = false; } if (mis.isPsRunning()) { if (mis.psAlgorithm.worksOnSameFile) { // Incomplete post-processing results in a corrupted download file // because the selected algorithm works on the same file to save space. // the file will be deleted if the storage API // is Java IO (avoid showing the "Save as..." dialog) if (exists && mis.storage.isDirect() && !mis.storage.delete()) Log.w(TAG, "Unable to delete incomplete download file: " + sub.getPath()); } mis.psState = 0; mis.errCode = DownloadMission.ERROR_POSTPROCESSING_STOPPED; } else if (!exists) { tryRecover(mis); // the progress is lost, reset mission state if (mis.isInitialized()) mis.resetState(true, true, DownloadMission.ERROR_PROGRESS_LOST); } if (mis.psAlgorithm != null) { mis.psAlgorithm.cleanupTemporalDir(); mis.psAlgorithm.setTemporalDir(tempDir); } mis.metadata = sub; mis.maxRetry = mPrefMaxRetry; mis.mHandler = mHandler; mMissionsPending.add(mis); } if (mMissionsPending.size() > 1) Collections.sort(mMissionsPending, Comparator.comparingLong(Mission::getTimestamp)); } /** * Start a new download mission * * @param mission the new download mission to add and run (if possible) */ void startMission(DownloadMission mission) { synchronized (this) { mission.timestamp = System.currentTimeMillis(); mission.mHandler = mHandler; mission.maxRetry = mPrefMaxRetry; // create metadata file while (true) { mission.metadata = new File(mPendingMissionsDir, String.valueOf(mission.timestamp)); if (!mission.metadata.isFile() && !mission.metadata.exists()) { try { if (!mission.metadata.createNewFile()) throw new RuntimeException("Cant create download metadata file"); } catch (IOException e) { throw new RuntimeException(e); } break; } mission.timestamp = System.currentTimeMillis(); } mSelfMissionsControl = true; mMissionsPending.add(mission); // Before continue, save the metadata in case the internet connection is not available Utility.writeToFile(mission.metadata, mission); if (mission.storage == null) { // noting to do here mission.errCode = DownloadMission.ERROR_FILE_CREATION; if (mission.errObject != null) mission.errObject = new IOException("DownloadMission.storage == NULL"); return; } boolean start = !mPrefQueueLimit || getRunningMissionsCount() < 1; if (canDownloadInCurrentNetwork() && start) { mission.start(); } } } public void resumeMission(DownloadMission mission) { if (!mission.running) { mission.start(); } } public void pauseMission(DownloadMission mission) { if (mission.running) { mission.setEnqueued(false); mission.pause(); } } public void deleteMission(Mission mission) { synchronized (this) { if (mission instanceof DownloadMission) { mMissionsPending.remove(mission); } else if (mission instanceof FinishedMission) { mMissionsFinished.remove(mission); mFinishedMissionStore.deleteMission(mission); } mission.delete(); } } public void forgetMission(StoredFileHelper storage) { synchronized (this) { Mission mission = getAnyMission(storage); if (mission == null) return; if (mission instanceof DownloadMission) { mMissionsPending.remove(mission); } else if (mission instanceof FinishedMission) { mMissionsFinished.remove(mission); mFinishedMissionStore.deleteMission(mission); } mission.storage = null; mission.delete(); } } public void tryRecover(DownloadMission mission) { StoredDirectoryHelper mainStorage = getMainStorage(mission.storage.getTag()); if (!mission.storage.isInvalid() && mission.storage.create()) return; // using javaIO cannot recreate the file // using SAF in older devices (no tree available) // // force the user to pick again the save path mission.storage.invalidate(); if (mainStorage == null) return; // if the user has changed the save path before this download, the original save path will be lost StoredFileHelper newStorage = mainStorage.createFile(mission.storage.getName(), mission.storage.getType()); if (newStorage != null) mission.storage = newStorage; } /** * Get a pending mission by its path * * @param storage where the file possible is stored * @return the mission or null if no such mission exists */ @Nullable private DownloadMission getPendingMission(StoredFileHelper storage) { for (DownloadMission mission : mMissionsPending) { if (mission.storage.equals(storage)) { return mission; } } return null; } /** * Get the index into {@link #mMissionsFinished} of a finished mission by its path, return * {@code -1} if there is no such mission. This function also checks if the matched mission's * file exists, and, if it does not, the related mission is forgotten about (like in {@link * #loadFinishedMissions()}) and {@code -1} is returned. * * @param storage where the file would be stored * @return the mission index or -1 if no such mission exists */ private int getFinishedMissionIndex(StoredFileHelper storage) { for (int i = 0; i < mMissionsFinished.size(); i++) { if (mMissionsFinished.get(i).storage.equals(storage)) { // If the file does not exist the mission is not valid anymore. Also checking if // length == 0 since the file picker may create an empty file before yielding it, // but that does not mean the file really belonged to a previous mission. if (!storage.existsAsFile() || storage.length() == 0) { if (DEBUG) { Log.d(TAG, "matched downloaded file removed: " + storage.getName()); } mFinishedMissionStore.deleteMission(mMissionsFinished.get(i)); mMissionsFinished.remove(i); return -1; // finished mission whose associated file was removed } return i; } } return -1; } private Mission getAnyMission(StoredFileHelper storage) { synchronized (this) { Mission mission = getPendingMission(storage); if (mission != null) return mission; int idx = getFinishedMissionIndex(storage); if (idx >= 0) return mMissionsFinished.get(idx); } return null; } int getRunningMissionsCount() { int count = 0; synchronized (this) { for (DownloadMission mission : mMissionsPending) { if (mission.running && !mission.isPsFailed() && !mission.isFinished()) count++; } } return count; } public void pauseAllMissions(boolean force) { synchronized (this) { for (DownloadMission mission : mMissionsPending) { if (!mission.running || mission.isPsRunning() || mission.isFinished()) continue; if (force) { // avoid waiting for threads mission.init = null; mission.threads = new Thread[0]; } mission.pause(); } } } public void startAllMissions() { synchronized (this) { for (DownloadMission mission : mMissionsPending) { if (mission.running || mission.isCorrupt()) continue; mission.start(); } } } /** * Set a pending download as finished * * @param mission the desired mission */ void setFinished(DownloadMission mission) { synchronized (this) { mMissionsPending.remove(mission); mMissionsFinished.add(0, new FinishedMission(mission)); mFinishedMissionStore.addFinishedMission(mission); } } /** * runs one or multiple missions in from queue if possible * * @return true if one or multiple missions are running, otherwise, false */ boolean runMissions() { synchronized (this) { if (mMissionsPending.size() < 1) return false; if (!canDownloadInCurrentNetwork()) return false; if (mPrefQueueLimit) { for (DownloadMission mission : mMissionsPending) if (!mission.isFinished() && mission.running) return true; } boolean flag = false; for (DownloadMission mission : mMissionsPending) { if (mission.running || !mission.enqueued || mission.isFinished()) continue; resumeMission(mission); if (mission.errCode != DownloadMission.ERROR_NOTHING) continue; if (mPrefQueueLimit) return true; flag = true; } return flag; } } public MissionIterator getIterator() { mSelfMissionsControl = true; return new MissionIterator(); } /** * Forget all finished downloads, but, doesn't delete any file */ public void forgetFinishedDownloads() { synchronized (this) { for (FinishedMission mission : mMissionsFinished) { mFinishedMissionStore.deleteMission(mission); } mMissionsFinished.clear(); } } private boolean canDownloadInCurrentNetwork() { if (mLastNetworkStatus == NetworkState.Unavailable) return false; return !(mPrefMeteredDownloads && mLastNetworkStatus == NetworkState.MeteredOperating); } void handleConnectivityState(NetworkState currentStatus, boolean updateOnly) { if (currentStatus == mLastNetworkStatus) return; mLastNetworkStatus = currentStatus; if (currentStatus == NetworkState.Unavailable) return; if (!mSelfMissionsControl || updateOnly) { return;// don't touch anything without the user interaction } boolean isMetered = mPrefMeteredDownloads && mLastNetworkStatus == NetworkState.MeteredOperating; synchronized (this) { for (DownloadMission mission : mMissionsPending) { if (mission.isCorrupt() || mission.isPsRunning()) continue; if (mission.running && isMetered) { mission.pause(); } else if (!mission.running && !isMetered && mission.enqueued) { mission.start(); if (mPrefQueueLimit) break; } } } } void updateMaximumAttempts() { synchronized (this) { for (DownloadMission mission : mMissionsPending) mission.maxRetry = mPrefMaxRetry; } } public MissionState checkForExistingMission(StoredFileHelper storage) { synchronized (this) { DownloadMission pending = getPendingMission(storage); if (pending == null) { if (getFinishedMissionIndex(storage) >= 0) return MissionState.Finished; } else { if (pending.isFinished()) { return MissionState.Finished;// this never should happen (race-condition) } else { return pending.running ? MissionState.PendingRunning : MissionState.Pending; } } } return MissionState.None; } private static boolean isDirectoryAvailable(File directory) { return directory != null && directory.canWrite() && directory.exists(); } static File pickAvailableTemporalDir(@NonNull Context ctx) { File dir = ctx.getExternalFilesDir(null); if (isDirectoryAvailable(dir)) return dir; dir = ctx.getFilesDir(); if (isDirectoryAvailable(dir)) return dir; // this never should happen dir = ctx.getDir("muxing_tmp", Context.MODE_PRIVATE); if (isDirectoryAvailable(dir)) return dir; // fallback to cache dir dir = ctx.getCacheDir(); if (isDirectoryAvailable(dir)) return dir; throw new RuntimeException("Not temporal directories are available"); } @Nullable private StoredDirectoryHelper getMainStorage(@NonNull String tag) { if (tag.equals(TAG_AUDIO)) return mMainStorageAudio; if (tag.equals(TAG_VIDEO)) return mMainStorageVideo; Log.w(TAG, "Unknown download category, not [audio video]: " + tag); return null;// this never should happen } public class MissionIterator extends DiffUtil.Callback { final Object FINISHED = new Object(); final Object PENDING = new Object(); ArrayList<Object> snapshot; ArrayList<Object> current; ArrayList<Mission> hidden; boolean hasFinished = false; private MissionIterator() { hidden = new ArrayList<>(2); current = null; snapshot = getSpecialItems(); } private ArrayList<Object> getSpecialItems() { synchronized (DownloadManager.this) { ArrayList<Mission> pending = new ArrayList<>(mMissionsPending); ArrayList<Mission> finished = new ArrayList<>(mMissionsFinished); List<Mission> remove = new ArrayList<>(hidden); // hide missions (if required) remove.removeIf(mission -> pending.remove(mission) || finished.remove(mission)); int fakeTotal = pending.size(); if (fakeTotal > 0) fakeTotal++; fakeTotal += finished.size(); if (finished.size() > 0) fakeTotal++; ArrayList<Object> list = new ArrayList<>(fakeTotal); if (pending.size() > 0) { list.add(PENDING); list.addAll(pending); } if (finished.size() > 0) { list.add(FINISHED); list.addAll(finished); } hasFinished = finished.size() > 0; return list; } } public MissionItem getItem(int position) { Object object = snapshot.get(position); if (object == PENDING) return new MissionItem(SPECIAL_PENDING); if (object == FINISHED) return new MissionItem(SPECIAL_FINISHED); return new MissionItem(SPECIAL_NOTHING, (Mission) object); } public int getSpecialAtItem(int position) { Object object = snapshot.get(position); if (object == PENDING) return SPECIAL_PENDING; if (object == FINISHED) return SPECIAL_FINISHED; return SPECIAL_NOTHING; } public void start() { current = getSpecialItems(); } public void end() { snapshot = current; current = null; } public void hide(Mission mission) { hidden.add(mission); } public void unHide(Mission mission) { hidden.remove(mission); } public boolean hasFinishedMissions() { return hasFinished; } /** * Check if exists missions running and paused. Corrupted and hidden missions are not counted * * @return two-dimensional array contains the current missions state. * 1° entry: true if has at least one mission running * 2° entry: true if has at least one mission paused */ public boolean[] hasValidPendingMissions() { boolean running = false; boolean paused = false; synchronized (DownloadManager.this) { for (DownloadMission mission : mMissionsPending) { if (hidden.contains(mission) || mission.isCorrupt()) continue; if (mission.running) running = true; else paused = true; } } return new boolean[]{running, paused}; } @Override public int getOldListSize() { return snapshot.size(); } @Override public int getNewListSize() { return current.size(); } @Override public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { return snapshot.get(oldItemPosition) == current.get(newItemPosition); } @Override public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { Object x = snapshot.get(oldItemPosition); Object y = current.get(newItemPosition); if (x instanceof Mission && y instanceof Mission) { return ((Mission) x).storage.equals(((Mission) y).storage); } return false; } } public static class MissionItem { public int special; public Mission mission; MissionItem(int s, Mission m) { special = s; mission = m; } MissionItem(int s) { this(s, null); } } }
jamestiotio/NewPipe
app/src/main/java/us/shandian/giga/service/DownloadManager.java
41,682
package org.telegram.ui.Cells; import static org.telegram.messenger.AndroidUtilities.dp; import static org.telegram.messenger.AndroidUtilities.dpf2; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.RectF; import android.graphics.Region; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.text.Layout; import android.text.StaticLayout; import android.text.TextPaint; import android.text.TextUtils; import android.util.Log; import android.util.SparseArray; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.core.graphics.ColorUtils; import androidx.core.math.MathUtils; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.DownloadController; import org.telegram.messenger.FileLoader; import org.telegram.messenger.ImageLocation; import org.telegram.messenger.ImageReceiver; import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessagesController; import org.telegram.messenger.R; import org.telegram.messenger.Utilities; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.Components.AnimatedFloat; import org.telegram.ui.Components.AnimatedTextView; import org.telegram.ui.Components.CanvasButton; import org.telegram.ui.Components.CheckBoxBase; import org.telegram.ui.Components.CombinedDrawable; import org.telegram.ui.Components.CubicBezierInterpolator; import org.telegram.ui.Components.FlickerLoadingView; import org.telegram.ui.Components.spoilers.SpoilerEffect; import org.telegram.ui.Components.spoilers.SpoilerEffect2; import org.telegram.ui.PhotoViewer; import org.telegram.ui.Stories.StoryWidgetsImageDecorator; import org.telegram.ui.Stories.recorder.DominantColors; import org.telegram.ui.Stories.recorder.StoryPrivacyBottomSheet; import java.util.HashMap; public class SharedPhotoVideoCell2 extends FrameLayout { public ImageReceiver imageReceiver = new ImageReceiver(); public ImageReceiver blurImageReceiver = new ImageReceiver(); public int storyId; int currentAccount; MessageObject currentMessageObject; int currentParentColumnsCount; FlickerLoadingView globalGradientView; SharedPhotoVideoCell2 crossfadeView; float imageAlpha = 1f; float imageScale = 1f; boolean showVideoLayout; StaticLayout videoInfoLayot; String videoText; boolean drawVideoIcon = true; private int privacyType; private Bitmap privacyBitmap; private Paint privacyPaint; boolean drawViews; AnimatedFloat viewsAlpha = new AnimatedFloat(this, 0, 350, CubicBezierInterpolator.EASE_OUT_QUINT); AnimatedTextView.AnimatedTextDrawable viewsText = new AnimatedTextView.AnimatedTextDrawable(false, true, true); CheckBoxBase checkBoxBase; SharedResources sharedResources; private boolean attached; float crossfadeProgress; float crossfadeToColumnsCount; float highlightProgress; public boolean isFirst, isLast; private Drawable gradientDrawable; private boolean gradientDrawableLoading; public boolean isStory; public boolean isStoryPinned; static long lastUpdateDownloadSettingsTime; static boolean lastAutoDownload; private Path path = new Path(); private SpoilerEffect mediaSpoilerEffect = new SpoilerEffect(); private float spoilerRevealProgress; private float spoilerRevealX; private float spoilerRevealY; private float spoilerMaxRadius; private SpoilerEffect2 mediaSpoilerEffect2; public final static int STYLE_SHARED_MEDIA = 0; public final static int STYLE_CACHE = 1; private int style = STYLE_SHARED_MEDIA; CanvasButton canvasButton; public SharedPhotoVideoCell2(Context context, SharedResources sharedResources, int currentAccount) { super(context); this.sharedResources = sharedResources; this.currentAccount = currentAccount; setChecked(false, false); imageReceiver.setParentView(this); blurImageReceiver.setParentView(this); imageReceiver.setDelegate((imageReceiver1, set, thumb, memCache) -> { if (set && !thumb && currentMessageObject != null && currentMessageObject.hasMediaSpoilers() && imageReceiver.getBitmap() != null) { if (blurImageReceiver.getBitmap() != null) { blurImageReceiver.getBitmap().recycle(); } blurImageReceiver.setImageBitmap(Utilities.stackBlurBitmapMax(imageReceiver.getBitmap())); } }); viewsText.setCallback(this); viewsText.setTextSize(dp(12)); viewsText.setTextColor(Color.WHITE); viewsText.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); viewsText.setOverrideFullWidth(AndroidUtilities.displaySize.x); setWillNotDraw(false); } public void setStyle(int style) { if (this.style == style) { return; } this.style = style; if (style == STYLE_CACHE) { checkBoxBase = new CheckBoxBase(this, 21, null); checkBoxBase.setColor(-1, Theme.key_sharedMedia_photoPlaceholder, Theme.key_checkboxCheck); checkBoxBase.setDrawUnchecked(true); checkBoxBase.setBackgroundType(0); checkBoxBase.setBounds(0, 0, dp(24), dp(24)); if (attached) { checkBoxBase.onAttachedToWindow(); } canvasButton = new CanvasButton(this); canvasButton.setDelegate(() -> { onCheckBoxPressed(); }); } } public void onCheckBoxPressed() { } public void setMessageObject(MessageObject messageObject, int parentColumnsCount) { int oldParentColumsCount = currentParentColumnsCount; currentParentColumnsCount = parentColumnsCount; if (currentMessageObject == null && messageObject == null) { return; } if (currentMessageObject != null && messageObject != null && currentMessageObject.getId() == messageObject.getId() && oldParentColumsCount == parentColumnsCount && (privacyType == 100) == isStoryPinned) { return; } currentMessageObject = messageObject; isStory = currentMessageObject != null && currentMessageObject.isStory(); updateSpoilers2(); if (messageObject == null) { imageReceiver.onDetachedFromWindow(); blurImageReceiver.onDetachedFromWindow(); videoText = null; drawViews = false; viewsAlpha.set(0f, true); viewsText.setText("", false); videoInfoLayot = null; showVideoLayout = false; gradientDrawableLoading = false; gradientDrawable = null; privacyType = -1; privacyBitmap = null; return; } else { if (attached) { imageReceiver.onAttachedToWindow(); blurImageReceiver.onAttachedToWindow(); } } String restrictionReason = MessagesController.getRestrictionReason(messageObject.messageOwner.restriction_reason); String imageFilter; int stride; int width = (int) (AndroidUtilities.displaySize.x / parentColumnsCount / AndroidUtilities.density); imageFilter = sharedResources.getFilterString(width); boolean showImageStub = false; if (parentColumnsCount <= 2) { stride = AndroidUtilities.getPhotoSize(); } else if (parentColumnsCount == 3) { stride = 320; } else if (parentColumnsCount == 5) { stride = 320; } else { stride = 320; } videoText = null; videoInfoLayot = null; showVideoLayout = false; imageReceiver.clearDecorators(); if (isStory && messageObject.storyItem.views != null) { drawViews = messageObject.storyItem.views.views_count > 0; viewsText.setText(AndroidUtilities.formatWholeNumber(messageObject.storyItem.views.views_count, 0), false); } else { drawViews = false; viewsAlpha.set(0f, true); viewsText.setText("", false); } viewsAlpha.set(drawViews ? 1f : 0f, true); if (!TextUtils.isEmpty(restrictionReason)) { showImageStub = true; } else if (messageObject.storyItem != null && messageObject.storyItem.media instanceof TLRPC.TL_messageMediaUnsupported) { messageObject.storyItem.dialogId = messageObject.getDialogId(); Drawable icon = getContext().getResources().getDrawable(R.drawable.msg_emoji_recent).mutate(); icon.setColorFilter(new PorterDuffColorFilter(0x40FFFFFF, PorterDuff.Mode.SRC_IN)); imageReceiver.setImageBitmap(new CombinedDrawable(new ColorDrawable(0xFF333333), icon)); } else if (messageObject.isVideo()) { showVideoLayout = true; if (parentColumnsCount != 9) { videoText = AndroidUtilities.formatShortDuration((int) messageObject.getDuration()); } if (messageObject.mediaThumb != null) { if (messageObject.strippedThumb != null) { imageReceiver.setImage(messageObject.mediaThumb, imageFilter, messageObject.strippedThumb, null, messageObject, 0); } else { imageReceiver.setImage(messageObject.mediaThumb, imageFilter, messageObject.mediaSmallThumb, imageFilter + "_b", null, 0, null, messageObject, 0); } } else { TLRPC.Document document = messageObject.getDocument(); TLRPC.PhotoSize thumb = FileLoader.getClosestPhotoSizeWithSize(document.thumbs, 50); TLRPC.PhotoSize qualityThumb = FileLoader.getClosestPhotoSizeWithSize(document.thumbs, stride, false, null, isStory); if (thumb == qualityThumb && !isStory) { qualityThumb = null; } if (thumb != null) { if (messageObject.strippedThumb != null) { imageReceiver.setImage(ImageLocation.getForDocument(qualityThumb, document), imageFilter, messageObject.strippedThumb, null, messageObject, 0); } else { imageReceiver.setImage(ImageLocation.getForDocument(qualityThumb, document), imageFilter, ImageLocation.getForDocument(thumb, document), imageFilter + "_b", null, 0, null, messageObject, 0); } } else { showImageStub = true; } } } else if (MessageObject.getMedia(messageObject.messageOwner) instanceof TLRPC.TL_messageMediaPhoto && MessageObject.getMedia(messageObject.messageOwner).photo != null && !messageObject.photoThumbs.isEmpty()) { if (messageObject.mediaExists || canAutoDownload(messageObject) || isStory) { if (messageObject.mediaThumb != null) { if (messageObject.strippedThumb != null) { imageReceiver.setImage(messageObject.mediaThumb, imageFilter, messageObject.strippedThumb, null, messageObject, 0); } else { imageReceiver.setImage(messageObject.mediaThumb, imageFilter, messageObject.mediaSmallThumb, imageFilter + "_b", null, 0, null, messageObject, 0); } } else { TLRPC.PhotoSize currentPhotoObjectThumb = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, 50); TLRPC.PhotoSize currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, stride, false, currentPhotoObjectThumb, isStory); if (currentPhotoObject == currentPhotoObjectThumb) { currentPhotoObjectThumb = null; } if (messageObject.strippedThumb != null) { imageReceiver.setImage(ImageLocation.getForObject(currentPhotoObject, messageObject.photoThumbsObject), imageFilter, null, null, messageObject.strippedThumb, currentPhotoObject != null ? currentPhotoObject.size : 0, null, messageObject, messageObject.shouldEncryptPhotoOrVideo() ? 2 : 1); } else { imageReceiver.setImage(ImageLocation.getForObject(currentPhotoObject, messageObject.photoThumbsObject), imageFilter, ImageLocation.getForObject(currentPhotoObjectThumb, messageObject.photoThumbsObject), imageFilter + "_b", currentPhotoObject != null ? currentPhotoObject.size : 0, null, messageObject, messageObject.shouldEncryptPhotoOrVideo() ? 2 : 1); } } } else { if (messageObject.strippedThumb != null) { imageReceiver.setImage(null, null, null, null, messageObject.strippedThumb, 0, null, messageObject, 0); } else { TLRPC.PhotoSize currentPhotoObjectThumb = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, 50); imageReceiver.setImage(null, null, ImageLocation.getForObject(currentPhotoObjectThumb, messageObject.photoThumbsObject), "b", null, 0, null, messageObject, 0); } } } else { showImageStub = true; } if (showImageStub) { imageReceiver.setImageBitmap(ContextCompat.getDrawable(getContext(), R.drawable.photo_placeholder_in)); } if (blurImageReceiver.getBitmap() != null) { blurImageReceiver.getBitmap().recycle(); blurImageReceiver.setImageBitmap((Bitmap) null); } if (imageReceiver.getBitmap() != null && currentMessageObject.hasMediaSpoilers() && !currentMessageObject.isMediaSpoilersRevealed) { blurImageReceiver.setImageBitmap(Utilities.stackBlurBitmapMax(imageReceiver.getBitmap())); } if (messageObject != null && messageObject.storyItem != null) { imageReceiver.addDecorator(new StoryWidgetsImageDecorator(messageObject.storyItem)); } if (isStoryPinned) { setPrivacyType(100, R.drawable.msg_pin_mini); } else if (isStory && messageObject.storyItem != null) { if (messageObject.storyItem.parsedPrivacy == null) { messageObject.storyItem.parsedPrivacy = new StoryPrivacyBottomSheet.StoryPrivacy(currentAccount, messageObject.storyItem.privacy); } if (messageObject.storyItem.parsedPrivacy.type == StoryPrivacyBottomSheet.TYPE_CONTACTS) { setPrivacyType(messageObject.storyItem.parsedPrivacy.type, R.drawable.msg_folders_private); } else if (messageObject.storyItem.parsedPrivacy.type == StoryPrivacyBottomSheet.TYPE_CLOSE_FRIENDS) { setPrivacyType(messageObject.storyItem.parsedPrivacy.type, R.drawable.msg_stories_closefriends); } else if (messageObject.storyItem.parsedPrivacy.type == StoryPrivacyBottomSheet.TYPE_SELECTED_CONTACTS) { setPrivacyType(messageObject.storyItem.parsedPrivacy.type, R.drawable.msg_folders_groups); } else { setPrivacyType(-1, 0); } } else { setPrivacyType(-1, 0); } invalidate(); } private void setPrivacyType(int type, int resId) { if (privacyType == type) return; privacyType = type; privacyBitmap = null; if (resId != 0) { privacyBitmap = sharedResources.getPrivacyBitmap(getContext(), resId); } invalidate(); } private boolean canAutoDownload(MessageObject messageObject) { if (System.currentTimeMillis() - lastUpdateDownloadSettingsTime > 5000) { lastUpdateDownloadSettingsTime = System.currentTimeMillis(); lastAutoDownload = DownloadController.getInstance(currentAccount).canDownloadMedia(messageObject); } return lastAutoDownload; } public void setVideoText(String videoText, boolean drawVideoIcon) { this.videoText = videoText; showVideoLayout = videoText != null; if (showVideoLayout && videoInfoLayot != null && !videoInfoLayot.getText().toString().equals(videoText)) { videoInfoLayot = null; } this.drawVideoIcon = drawVideoIcon; } private float getPadding() { if (crossfadeProgress != 0 && (crossfadeToColumnsCount == 9 || currentParentColumnsCount == 9)) { if (crossfadeToColumnsCount == 9) { return dpf2(0.5f) * crossfadeProgress + dpf2(1) * (1f - crossfadeProgress); } else { return dpf2(1f) * crossfadeProgress + dpf2(0.5f) * (1f - crossfadeProgress); } } else { return currentParentColumnsCount == 9 ? dpf2(0.5f) : dpf2(1); } } private final RectF bounds = new RectF(); @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); final float padding = getPadding(); final float leftpadding = isStory && isFirst ? 0 : padding; final float rightpadding = isStory && isLast ? 0 : padding; float imageWidth = (getMeasuredWidth() - leftpadding - rightpadding) * imageScale; float imageHeight = (getMeasuredHeight() - padding * 2) * imageScale; if (crossfadeProgress > 0.5f && crossfadeToColumnsCount != 9 && currentParentColumnsCount != 9) { imageWidth -= 2; imageHeight -= 2; } if ((currentMessageObject == null && style != STYLE_CACHE) || !imageReceiver.hasBitmapImage() || imageReceiver.getCurrentAlpha() != 1.0f || imageAlpha != 1f) { if (SharedPhotoVideoCell2.this.getParent() != null && globalGradientView != null) { globalGradientView.setParentSize(((View) SharedPhotoVideoCell2.this.getParent()).getMeasuredWidth(), SharedPhotoVideoCell2.this.getMeasuredHeight(), -getX()); globalGradientView.updateColors(); globalGradientView.updateGradient(); float padPlus = 0; if (crossfadeProgress > 0.5f && crossfadeToColumnsCount != 9 && currentParentColumnsCount != 9) { padPlus += 1; } canvas.drawRect(leftpadding + padPlus, padding + padPlus, leftpadding + padPlus + imageWidth, padding + padPlus + imageHeight, globalGradientView.getPaint()); } invalidate(); } if (imageAlpha != 1f) { canvas.saveLayerAlpha(0, 0, leftpadding + rightpadding + imageWidth, padding * 2 + imageHeight, (int) (255 * imageAlpha), Canvas.ALL_SAVE_FLAG); } else { canvas.save(); } if ((checkBoxBase != null && checkBoxBase.isChecked()) || PhotoViewer.isShowingImage(currentMessageObject)) { canvas.drawRect(leftpadding, padding, leftpadding + imageWidth - rightpadding, imageHeight, sharedResources.backgroundPaint); } if (isStory && currentParentColumnsCount == 1) { final float w = getHeight() * .72f; if (gradientDrawable == null) { if (!gradientDrawableLoading && imageReceiver.getBitmap() != null) { gradientDrawableLoading = true; DominantColors.getColors(false, imageReceiver.getBitmap(), Theme.isCurrentThemeDark(), colors -> { if (!gradientDrawableLoading) { return; } gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors); invalidate(); gradientDrawableLoading = false; }); } } else { gradientDrawable.setBounds(0, 0, getWidth(), getHeight()); gradientDrawable.draw(canvas); } imageReceiver.setImageCoords((imageWidth - w) / 2, 0, w, getHeight()); } else if (checkBoxProgress > 0) { float offset = dp(10) * checkBoxProgress; imageReceiver.setImageCoords(leftpadding + offset, padding + offset, imageWidth - offset * 2, imageHeight - offset * 2); blurImageReceiver.setImageCoords(leftpadding + offset, padding + offset, imageWidth - offset * 2, imageHeight - offset * 2); } else { float padPlus = 0; if (crossfadeProgress > 0.5f && crossfadeToColumnsCount != 9 && currentParentColumnsCount != 9) { padPlus = 1; } imageReceiver.setImageCoords(leftpadding + padPlus, padding + padPlus, imageWidth, imageHeight); blurImageReceiver.setImageCoords(leftpadding + padPlus, padding + padPlus, imageWidth, imageHeight); } if (!PhotoViewer.isShowingImage(currentMessageObject)) { imageReceiver.draw(canvas); if (currentMessageObject != null && currentMessageObject.hasMediaSpoilers() && !currentMessageObject.isMediaSpoilersRevealedInSharedMedia) { canvas.save(); canvas.clipRect(leftpadding, padding, leftpadding + imageWidth - rightpadding, padding + imageHeight); if (spoilerRevealProgress != 0f) { path.rewind(); path.addCircle(spoilerRevealX, spoilerRevealY, spoilerMaxRadius * spoilerRevealProgress, Path.Direction.CW); canvas.clipPath(path, Region.Op.DIFFERENCE); } blurImageReceiver.draw(canvas); if (mediaSpoilerEffect2 != null) { canvas.clipRect(imageReceiver.getImageX(), imageReceiver.getImageY(), imageReceiver.getImageX2(), imageReceiver.getImageY2()); mediaSpoilerEffect2.draw(canvas, this, (int) imageReceiver.getImageWidth(), (int) imageReceiver.getImageHeight()); } else { int sColor = Color.WHITE; mediaSpoilerEffect.setColor(ColorUtils.setAlphaComponent(sColor, (int) (Color.alpha(sColor) * 0.325f))); mediaSpoilerEffect.setBounds((int) imageReceiver.getImageX(), (int) imageReceiver.getImageY(), (int) imageReceiver.getImageX2(), (int) imageReceiver.getImageY2()); mediaSpoilerEffect.draw(canvas); } canvas.restore(); invalidate(); } if (highlightProgress > 0) { sharedResources.highlightPaint.setColor(ColorUtils.setAlphaComponent(Color.BLACK, (int) (0.5f * highlightProgress * 255))); canvas.drawRect(imageReceiver.getDrawRegion(), sharedResources.highlightPaint); } } bounds.set(imageReceiver.getImageX(), imageReceiver.getImageY(), imageReceiver.getImageX2(), imageReceiver.getImageY2()); drawDuration(canvas, bounds, 1f); drawViews(canvas, bounds, 1f); drawPrivacy(canvas, bounds, 1f); if (checkBoxBase != null && (style == STYLE_CACHE || checkBoxBase.getProgress() != 0)) { canvas.save(); float x, y; if (style == STYLE_CACHE) { x = imageWidth + dp(2) - dp(25) - dp(4); y = dp(4); } else { x = imageWidth + dp(2) - dp(25); y = 0; } canvas.translate(x, y); checkBoxBase.draw(canvas); if (canvasButton != null) { AndroidUtilities.rectTmp.set(x, y, x + checkBoxBase.bounds.width(), y + checkBoxBase.bounds.height()); canvasButton.setRect(AndroidUtilities.rectTmp); } canvas.restore(); } canvas.restore(); } public void drawDuration(Canvas canvas, RectF bounds, float alpha) { if (!showVideoLayout || imageReceiver != null && !imageReceiver.getVisible()) { return; } final float fwidth = bounds.width() + dp(20) * checkBoxProgress; final float scale = bounds.width() / fwidth; if (alpha < 1) { alpha = (float) Math.pow(alpha, 8); } canvas.save(); canvas.translate(bounds.left, bounds.top); canvas.scale(scale, scale, 0, bounds.height()); canvas.clipRect(0, 0, bounds.width(), bounds.height()); if (currentParentColumnsCount != 9 && videoInfoLayot == null && videoText != null) { int textWidth = (int) Math.ceil(sharedResources.textPaint.measureText(videoText)); videoInfoLayot = new StaticLayout(videoText, sharedResources.textPaint, textWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); } else if ((currentParentColumnsCount >= 9 || videoText == null) && videoInfoLayot != null) { videoInfoLayot = null; } final boolean up = viewsOnLeft(fwidth); int width = dp(8) + (videoInfoLayot != null ? videoInfoLayot.getWidth() : 0) + (drawVideoIcon ? dp(10) : 0); canvas.translate(dp(5), dp(1) + bounds.height() - dp(17) - dp(4) - (up ? dp(17 + 5) : 0)); AndroidUtilities.rectTmp.set(0, 0, width, dp(17)); int oldAlpha = Theme.chat_timeBackgroundPaint.getAlpha(); Theme.chat_timeBackgroundPaint.setAlpha((int) (oldAlpha * alpha)); canvas.drawRoundRect(AndroidUtilities.rectTmp, dp(4), dp(4), Theme.chat_timeBackgroundPaint); Theme.chat_timeBackgroundPaint.setAlpha(oldAlpha); if (drawVideoIcon) { canvas.save(); canvas.translate(videoInfoLayot == null ? dp(5) : dp(4), (dp(17) - sharedResources.playDrawable.getIntrinsicHeight()) / 2f); sharedResources.playDrawable.setAlpha((int) (255 * imageAlpha * alpha)); sharedResources.playDrawable.draw(canvas); canvas.restore(); } if (videoInfoLayot != null) { canvas.translate(dp(4 + (drawVideoIcon ? 10 : 0)), (dp(17) - videoInfoLayot.getHeight()) / 2f); oldAlpha = sharedResources.textPaint.getAlpha(); sharedResources.textPaint.setAlpha((int) (oldAlpha * alpha)); videoInfoLayot.draw(canvas); sharedResources.textPaint.setAlpha(oldAlpha); } canvas.restore(); } public void updateViews() { if (isStory && currentMessageObject != null && currentMessageObject.storyItem != null && currentMessageObject.storyItem.views != null) { drawViews = currentMessageObject.storyItem.views.views_count > 0; viewsText.setText(AndroidUtilities.formatWholeNumber(currentMessageObject.storyItem.views.views_count, 0), true); } else { drawViews = false; viewsText.setText("", false); } } public boolean viewsOnLeft(float width) { if (!isStory || currentParentColumnsCount >= 5) { return false; } final int viewsWidth = dp(18 + 8) + (int) viewsText.getCurrentWidth(); final int durationWidth = showVideoLayout ? dp(8) + (videoInfoLayot != null ? videoInfoLayot.getWidth() : 0) + (drawVideoIcon ? dp(10) : 0) : 0; final int padding = viewsWidth > 0 && durationWidth > 0 ? dp(8) : 0; final int totalWidth = viewsWidth + padding + durationWidth; return totalWidth > width; } public void drawPrivacy(Canvas canvas, RectF bounds, float alpha) { if (!isStory || privacyBitmap == null || privacyBitmap.isRecycled()) { return; } final float fwidth = bounds.width() + dp(20) * checkBoxProgress; final float scale = bounds.width() / fwidth; final int sz = dp(17.33f * scale); canvas.save(); canvas.translate(bounds.right - sz - dp(5.66f), bounds.top + dp(5.66f)); if (privacyPaint == null) { privacyPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); } privacyPaint.setAlpha((int) (0xFF * alpha)); AndroidUtilities.rectTmp.set(0, 0, sz, sz); canvas.drawBitmap(privacyBitmap, null, AndroidUtilities.rectTmp, privacyPaint); canvas.restore(); } public void drawViews(Canvas canvas, RectF bounds, float alpha) { if (!isStory || imageReceiver != null && !imageReceiver.getVisible() || currentParentColumnsCount >= 5) { return; } final float fwidth = bounds.width() + dp(20) * checkBoxProgress; final float scale = bounds.width() / fwidth; final boolean left = viewsOnLeft(fwidth); float a = viewsAlpha.set(drawViews); alpha *= a; if (alpha < 1) { alpha = (float) Math.pow(alpha, 8); } if (a <= 0) { return; } canvas.save(); canvas.translate(bounds.left, bounds.top); canvas.scale(scale, scale, left ? 0 : bounds.width(), bounds.height()); canvas.clipRect(0, 0, bounds.width(), bounds.height()); float width = dp(18 + 8) + viewsText.getCurrentWidth(); canvas.translate(left ? dp(5) : bounds.width() - dp(5) - width, dp(1) + bounds.height() - dp(17) - dp(4)); AndroidUtilities.rectTmp.set(0, 0, width, dp(17)); int oldAlpha = Theme.chat_timeBackgroundPaint.getAlpha(); Theme.chat_timeBackgroundPaint.setAlpha((int) (oldAlpha * alpha)); canvas.drawRoundRect(AndroidUtilities.rectTmp, dp(4), dp(4), Theme.chat_timeBackgroundPaint); Theme.chat_timeBackgroundPaint.setAlpha(oldAlpha); canvas.save(); canvas.translate(dp(3), (dp(17) - sharedResources.viewDrawable.getBounds().height()) / 2f); sharedResources.viewDrawable.setAlpha((int) (255 * imageAlpha * alpha)); sharedResources.viewDrawable.draw(canvas); canvas.restore(); canvas.translate(dp(4 + 18), 0); viewsText.setBounds(0, 0, (int) width, dp(17)); viewsText.setAlpha((int) (0xFF * alpha)); viewsText.draw(canvas); canvas.restore(); } public boolean canRevealSpoiler() { return currentMessageObject != null && currentMessageObject.hasMediaSpoilers() && spoilerRevealProgress == 0f && !currentMessageObject.isMediaSpoilersRevealedInSharedMedia; } public void startRevealMedia(float x, float y) { spoilerRevealX = x; spoilerRevealY = y; spoilerMaxRadius = (float) Math.sqrt(Math.pow(getWidth(), 2) + Math.pow(getHeight(), 2)); ValueAnimator animator = ValueAnimator.ofFloat(0, 1).setDuration((long) MathUtils.clamp(spoilerMaxRadius * 0.3f, 250, 550)); animator.setInterpolator(CubicBezierInterpolator.EASE_BOTH); animator.addUpdateListener(animation -> { spoilerRevealProgress = (float) animation.getAnimatedValue(); invalidate(); }); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { currentMessageObject.isMediaSpoilersRevealedInSharedMedia = true; invalidate(); } }); animator.start(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); attached = true; if (checkBoxBase != null) { checkBoxBase.onAttachedToWindow(); } if (currentMessageObject != null) { imageReceiver.onAttachedToWindow(); blurImageReceiver.onAttachedToWindow(); } if (mediaSpoilerEffect2 != null) { if (mediaSpoilerEffect2.destroyed) { mediaSpoilerEffect2 = SpoilerEffect2.getInstance(this); } else { mediaSpoilerEffect2.attach(this); } } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); attached = false; if (checkBoxBase != null) { checkBoxBase.onDetachedFromWindow(); } if (currentMessageObject != null) { imageReceiver.onDetachedFromWindow(); blurImageReceiver.onDetachedFromWindow(); } if (mediaSpoilerEffect2 != null) { mediaSpoilerEffect2.detach(this); } } public void setGradientView(FlickerLoadingView globalGradientView) { this.globalGradientView = globalGradientView; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = MeasureSpec.getSize(widthMeasureSpec); int height = isStory ? (int) (1.25f * width) : width; if (isStory && currentParentColumnsCount == 1) { height /= 2; } setMeasuredDimension(width, height); updateSpoilers2(); } private void updateSpoilers2() { if (getMeasuredHeight() <= 0 || getMeasuredWidth() <= 0) { return; } if (currentMessageObject != null && currentMessageObject.hasMediaSpoilers() && SpoilerEffect2.supports()) { if (mediaSpoilerEffect2 == null) { mediaSpoilerEffect2 = SpoilerEffect2.getInstance(this); } } else { if (mediaSpoilerEffect2 != null) { mediaSpoilerEffect2.detach(this); mediaSpoilerEffect2 = null; } } } public int getMessageId() { return currentMessageObject != null ? currentMessageObject.getId() : 0; } public MessageObject getMessageObject() { return currentMessageObject; } public void setImageAlpha(float alpha, boolean invalidate) { if (this.imageAlpha != alpha) { this.imageAlpha = alpha; if (invalidate) { invalidate(); } } } public void setImageScale(float scale, boolean invalidate) { if (this.imageScale != scale) { this.imageScale = scale; if (invalidate) { invalidate(); } } } public void setCrossfadeView(SharedPhotoVideoCell2 cell, float crossfadeProgress, int crossfadeToColumnsCount) { crossfadeView = cell; this.crossfadeProgress = crossfadeProgress; this.crossfadeToColumnsCount = crossfadeToColumnsCount; } public void drawCrossafadeImage(Canvas canvas) { if (crossfadeView != null) { canvas.save(); canvas.translate(getX(), getY()); float scale = ((getMeasuredWidth() - dp(2)) * imageScale) / (float) (crossfadeView.getMeasuredWidth() - dp(2)); crossfadeView.setImageScale(scale, false); crossfadeView.draw(canvas); canvas.restore(); } } public View getCrossfadeView() { return crossfadeView; } ValueAnimator animator; float checkBoxProgress; public void setChecked(final boolean checked, boolean animated) { boolean currentIsChecked = checkBoxBase != null && checkBoxBase.isChecked(); if (currentIsChecked == checked) { return; } if (checkBoxBase == null) { checkBoxBase = new CheckBoxBase(this, 21, null); checkBoxBase.setColor(-1, Theme.key_sharedMedia_photoPlaceholder, Theme.key_checkboxCheck); checkBoxBase.setDrawUnchecked(false); checkBoxBase.setBackgroundType(1); checkBoxBase.setBounds(0, 0, dp(24), dp(24)); if (attached) { checkBoxBase.onAttachedToWindow(); } } checkBoxBase.setChecked(checked, animated); if (animator != null) { ValueAnimator animatorFinal = animator; animator = null; animatorFinal.cancel(); } if (animated) { animator = ValueAnimator.ofFloat(checkBoxProgress, checked ? 1f : 0); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { checkBoxProgress = (float) valueAnimator.getAnimatedValue(); invalidate(); } }); animator.setDuration(200); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (animator != null && animator.equals(animation)) { checkBoxProgress = checked ? 1f : 0; animator = null; } } }); animator.start(); } else { checkBoxProgress = checked ? 1f : 0; } invalidate(); } public void startHighlight() { } public void setHighlightProgress(float p) { if (highlightProgress != p) { highlightProgress = p; invalidate(); } } public void moveImageToFront() { imageReceiver.moveImageToFront(); } public int getStyle() { return style; } public static class SharedResources { TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); private Paint backgroundPaint = new Paint(); Drawable playDrawable; Drawable viewDrawable; Paint highlightPaint = new Paint(); SparseArray<String> imageFilters = new SparseArray<>(); private final HashMap<Integer, Bitmap> privacyBitmaps = new HashMap<>(); public SharedResources(Context context, Theme.ResourcesProvider resourcesProvider) { textPaint.setTextSize(dp(12)); textPaint.setColor(Color.WHITE); textPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); playDrawable = ContextCompat.getDrawable(context, R.drawable.play_mini_video); playDrawable.setBounds(0, 0, playDrawable.getIntrinsicWidth(), playDrawable.getIntrinsicHeight()); viewDrawable = ContextCompat.getDrawable(context, R.drawable.filled_views); viewDrawable.setBounds(0, 0, (int) (viewDrawable.getIntrinsicWidth() * .7f), (int) (viewDrawable.getIntrinsicHeight() * .7f)); backgroundPaint.setColor(Theme.getColor(Theme.key_sharedMedia_photoPlaceholder, resourcesProvider)); } public String getFilterString(int width) { String str = imageFilters.get(width); if (str == null) { str = width + "_" + width + "_isc"; imageFilters.put(width, str); } return str; } public void recycleAll() { for (Bitmap bitmap : privacyBitmaps.values()) { AndroidUtilities.recycleBitmap(bitmap); } privacyBitmaps.clear(); } public Bitmap getPrivacyBitmap(Context context, int resId) { Bitmap bitmap = privacyBitmaps.get(resId); if (bitmap != null) { return bitmap; } bitmap = BitmapFactory.decodeResource(context.getResources(), resId); Bitmap shadowBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(shadowBitmap); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); paint.setColorFilter(new PorterDuffColorFilter(0xFF606060, PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, 0, 0, paint); Utilities.stackBlurBitmap(shadowBitmap, dp(1)); Bitmap resultBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); canvas = new Canvas(resultBitmap); canvas.drawBitmap(shadowBitmap, 0, 0, paint); canvas.drawBitmap(shadowBitmap, 0, 0, paint); canvas.drawBitmap(shadowBitmap, 0, 0, paint); paint.setColorFilter(new PorterDuffColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, 0, 0, paint); shadowBitmap.recycle(); bitmap.recycle(); bitmap = resultBitmap; privacyBitmaps.put(resId, bitmap); return bitmap; } } @Override public boolean onTouchEvent(MotionEvent event) { if (canvasButton != null) { if (canvasButton.checkTouchEvent(event)) { return true; } } return super.onTouchEvent(event); } @Override protected boolean verifyDrawable(@NonNull Drawable who) { return viewsText == who || super.verifyDrawable(who); } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedPhotoVideoCell2.java
41,683
package org.telegram.ui; import android.Manifest; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import androidx.annotation.RawRes; import androidx.fragment.app.FragmentActivity; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.ContactsController; import org.telegram.messenger.FileLog; import org.telegram.messenger.ImageLoader; import org.telegram.messenger.LocaleController; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.SharedConfig; import org.telegram.messenger.camera.CameraController; import org.telegram.ui.ActionBar.AlertDialog; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.Components.AlertsCreator; public class BasePermissionsActivity extends FragmentActivity { public final static int REQUEST_CODE_GEOLOCATION = 2, REQUEST_CODE_EXTERNAL_STORAGE = 4, REQUEST_CODE_ATTACH_CONTACT = 5, REQUEST_CODE_CALLS = 7, REQUEST_CODE_OPEN_CAMERA = 20, REQUEST_CODE_VIDEO_MESSAGE = 150, REQUEST_CODE_EXTERNAL_STORAGE_FOR_AVATAR = 151, REQUEST_CODE_SIGN_IN_WITH_GOOGLE = 200, REQUEST_CODE_PAYMENT_FORM = 210, REQUEST_CODE_MEDIA_GEO = 211; protected int currentAccount = -1; protected boolean checkPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (grantResults == null) { grantResults = new int[0]; } if (permissions == null) { permissions = new String[0]; } boolean granted = grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED; if (requestCode == 104) { if (granted) { if (GroupCallActivity.groupCallInstance != null) { GroupCallActivity.groupCallInstance.enableCamera(); } } else { showPermissionErrorAlert(R.raw.permission_request_camera, LocaleController.getString("VoipNeedCameraPermission", R.string.VoipNeedCameraPermission)); } } else if (requestCode == REQUEST_CODE_EXTERNAL_STORAGE || requestCode == REQUEST_CODE_EXTERNAL_STORAGE_FOR_AVATAR) { if (!granted) { showPermissionErrorAlert(R.raw.permission_request_folder, requestCode == REQUEST_CODE_EXTERNAL_STORAGE_FOR_AVATAR ? LocaleController.getString("PermissionNoStorageAvatar", R.string.PermissionNoStorageAvatar) : LocaleController.getString("PermissionStorageWithHint", R.string.PermissionStorageWithHint)); } else { ImageLoader.getInstance().checkMediaPaths(); } } else if (requestCode == REQUEST_CODE_ATTACH_CONTACT) { if (!granted) { showPermissionErrorAlert(R.raw.permission_request_contacts, LocaleController.getString("PermissionNoContactsSharing", R.string.PermissionNoContactsSharing)); return false; } else { ContactsController.getInstance(currentAccount).forceImportContacts(); } } else if (requestCode == 3 || requestCode == REQUEST_CODE_VIDEO_MESSAGE) { boolean audioGranted = true; boolean cameraGranted = true; for (int i = 0, size = Math.min(permissions.length, grantResults.length); i < size; i++) { if (Manifest.permission.RECORD_AUDIO.equals(permissions[i])) { audioGranted = grantResults[i] == PackageManager.PERMISSION_GRANTED; } else if (Manifest.permission.CAMERA.equals(permissions[i])) { cameraGranted = grantResults[i] == PackageManager.PERMISSION_GRANTED; } } if (requestCode == REQUEST_CODE_VIDEO_MESSAGE && (!audioGranted || !cameraGranted)) { showPermissionErrorAlert(R.raw.permission_request_camera, LocaleController.getString("PermissionNoCameraMicVideo", R.string.PermissionNoCameraMicVideo)); } else if (!audioGranted) { showPermissionErrorAlert(R.raw.permission_request_microphone, LocaleController.getString("PermissionNoAudioWithHint", R.string.PermissionNoAudioWithHint)); } else if (!cameraGranted) { showPermissionErrorAlert(R.raw.permission_request_camera, LocaleController.getString("PermissionNoCameraWithHint", R.string.PermissionNoCameraWithHint)); } else { if (SharedConfig.inappCamera) { CameraController.getInstance().initCamera(null); } return false; } } else if (requestCode == 18 || requestCode == 19 || requestCode == REQUEST_CODE_OPEN_CAMERA || requestCode == 22) { if (!granted) { showPermissionErrorAlert(R.raw.permission_request_camera, LocaleController.getString("PermissionNoCameraWithHint", R.string.PermissionNoCameraWithHint)); } } else if (requestCode == REQUEST_CODE_GEOLOCATION) { NotificationCenter.getGlobalInstance().postNotificationName(granted ? NotificationCenter.locationPermissionGranted : NotificationCenter.locationPermissionDenied); } else if (requestCode == REQUEST_CODE_MEDIA_GEO) { NotificationCenter.getGlobalInstance().postNotificationName(granted ? NotificationCenter.locationPermissionGranted : NotificationCenter.locationPermissionDenied, 1); } return true; } protected AlertDialog createPermissionErrorAlert(@RawRes int animationId, String message) { return new AlertDialog.Builder(this) .setTopAnimation(animationId, AlertsCreator.PERMISSIONS_REQUEST_TOP_ICON_SIZE, false, Theme.getColor(Theme.key_dialogTopBackground)) .setMessage(AndroidUtilities.replaceTags(message)) .setPositiveButton(LocaleController.getString("PermissionOpenSettings", R.string.PermissionOpenSettings), (dialogInterface, i) -> { try { Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS); intent.setData(Uri.parse("package:" + ApplicationLoader.applicationContext.getPackageName())); startActivity(intent); } catch (Exception e) { FileLog.e(e); } }) .setNegativeButton(LocaleController.getString("ContactsPermissionAlertNotNow", R.string.ContactsPermissionAlertNotNow), null) .create(); } private void showPermissionErrorAlert(@RawRes int animationId, String message) { createPermissionErrorAlert(animationId, message).show(); } }
Telegram-FOSS-Team/Telegram-FOSS
TMessagesProj/src/main/java/org/telegram/ui/BasePermissionsActivity.java
41,684
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.ui.Cells; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.ContentUris; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Region; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.SystemClock; import android.text.TextUtils; import android.util.Size; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; import android.view.SoundEffectConstants; import android.view.View; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.view.animation.DecelerateInterpolator; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import androidx.core.graphics.ColorUtils; import androidx.core.math.MathUtils; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.ImageLocation; import org.telegram.messenger.ImageReceiver; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MediaController; import org.telegram.messenger.MessageObject; import org.telegram.messenger.R; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.Components.BackupImageView; import org.telegram.ui.Components.CheckBox2; import org.telegram.ui.Components.CubicBezierInterpolator; import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.spoilers.SpoilerEffect; import org.telegram.ui.Components.spoilers.SpoilerEffect2; import org.telegram.ui.PhotoViewer; import java.io.IOException; public class PhotoAttachPhotoCell extends FrameLayout { private BackupImageView imageView; private FrameLayout container; private FrameLayout checkFrame; private CheckBox2 checkBox; private TextView videoTextView; private FrameLayout videoInfoContainer; private AnimatorSet animatorSet; private boolean isLast; private boolean pressed; private static Rect rect = new Rect(); private PhotoAttachPhotoCellDelegate delegate; private boolean itemSizeChanged; private boolean needCheckShow; private int itemSize; private boolean isVertical; private boolean zoomOnSelect = true; private MediaController.PhotoEntry photoEntry; private MediaController.SearchImage searchEntry; private Paint backgroundPaint = new Paint(); private AnimatorSet animator; private final Theme.ResourcesProvider resourcesProvider; private SpoilerEffect spoilerEffect = new SpoilerEffect(); private SpoilerEffect2 spoilerEffect2; private boolean hasSpoiler; private Path path = new Path(); private float spoilerRevealX; private float spoilerRevealY; private float spoilerMaxRadius; private float spoilerRevealProgress; private Bitmap imageViewCrossfadeSnapshot; private Float crossfadeDuration; private float imageViewCrossfadeProgress = 1f; public interface PhotoAttachPhotoCellDelegate { void onCheckClick(PhotoAttachPhotoCell v); } public PhotoAttachPhotoCell(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); this.resourcesProvider = resourcesProvider; setWillNotDraw(false); container = new FrameLayout(context) { @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { if (spoilerEffect2 != null && child == imageView) { boolean r = super.drawChild(canvas, child, drawingTime); if (hasSpoiler && spoilerRevealProgress != 1f && (photoEntry == null || !photoEntry.isAttachSpoilerRevealed)) { if (spoilerRevealProgress != 0f) { canvas.save(); path.rewind(); path.addCircle(spoilerRevealX, spoilerRevealY, spoilerMaxRadius * spoilerRevealProgress, Path.Direction.CW); canvas.clipPath(path, Region.Op.DIFFERENCE); } float alphaProgress = CubicBezierInterpolator.DEFAULT.getInterpolation(1f - imageViewCrossfadeProgress); float alpha = hasSpoiler ? alphaProgress : 1f - alphaProgress; spoilerEffect2.draw(canvas, container, imageView.getMeasuredWidth(), imageView.getMeasuredHeight()); if (spoilerRevealProgress != 0f) { canvas.restore(); } } return r; } return super.drawChild(canvas, child, drawingTime); } }; addView(container, LayoutHelper.createFrame(80, 80)); int sColor = Color.WHITE; spoilerEffect.setColor(ColorUtils.setAlphaComponent(sColor, (int) (Color.alpha(sColor) * 0.325f))); imageView = new BackupImageView(context) { private Paint crossfadePaint = new Paint(Paint.ANTI_ALIAS_FLAG); private long lastUpdate; @Override protected void onDraw(Canvas canvas) { ImageReceiver imageReceiver = animatedEmojiDrawable != null ? animatedEmojiDrawable.getImageReceiver() : this.imageReceiver; if (imageReceiver == null) { return; } if (width != -1 && height != -1) { imageReceiver.setImageCoords((getWidth() - width) / 2, (getHeight() - height) / 2, width, height); blurImageReceiver.setImageCoords((getWidth() - width) / 2, (getHeight() - height) / 2, width, height); } else { imageReceiver.setImageCoords(0, 0, getWidth(), getHeight()); blurImageReceiver.setImageCoords(0, 0, getWidth(), getHeight()); } imageReceiver.draw(canvas); if (hasSpoiler && spoilerRevealProgress != 1f && (photoEntry == null || !photoEntry.isAttachSpoilerRevealed)) { if (spoilerRevealProgress != 0f) { canvas.save(); path.rewind(); path.addCircle(spoilerRevealX, spoilerRevealY, spoilerMaxRadius * spoilerRevealProgress, Path.Direction.CW); canvas.clipPath(path, Region.Op.DIFFERENCE); } blurImageReceiver.draw(canvas); if (spoilerEffect2 == null) { spoilerEffect.setBounds(0, 0, getWidth(), getHeight()); spoilerEffect.draw(canvas); } invalidate(); if (spoilerRevealProgress != 0f) { canvas.restore(); } } if (imageViewCrossfadeProgress != 1f && imageViewCrossfadeSnapshot != null) { crossfadePaint.setAlpha((int) (CubicBezierInterpolator.DEFAULT.getInterpolation(1f - imageViewCrossfadeProgress) * 0xFF)); canvas.drawBitmap(imageViewCrossfadeSnapshot, 0, 0, crossfadePaint); long dt = Math.min(16, System.currentTimeMillis() - lastUpdate); float duration = crossfadeDuration == null ? 250f : crossfadeDuration; imageViewCrossfadeProgress = Math.min(1f, imageViewCrossfadeProgress + dt / duration); lastUpdate = System.currentTimeMillis(); invalidate(); if (spoilerEffect2 != null) { container.invalidate(); } } else if (imageViewCrossfadeProgress == 1f && imageViewCrossfadeSnapshot != null) { imageViewCrossfadeSnapshot.recycle(); imageViewCrossfadeSnapshot = null; crossfadeDuration = null; invalidate(); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); updateSpoilers2(photoEntry != null && photoEntry.hasSpoiler); } }; imageView.setBlurAllowed(true); container.addView(imageView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); videoInfoContainer = new FrameLayout(context) { private RectF rect = new RectF(); @Override protected void onDraw(Canvas canvas) { rect.set(0, 0, getMeasuredWidth(), getMeasuredHeight()); canvas.drawRoundRect(rect, AndroidUtilities.dp(4), AndroidUtilities.dp(4), Theme.chat_timeBackgroundPaint); } }; videoInfoContainer.setWillNotDraw(false); videoInfoContainer.setPadding(AndroidUtilities.dp(5), 0, AndroidUtilities.dp(5), 0); container.addView(videoInfoContainer, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 17, Gravity.BOTTOM | Gravity.LEFT, 4, 0, 0, 4)); ImageView imageView1 = new ImageView(context); imageView1.setImageResource(R.drawable.play_mini_video); videoInfoContainer.addView(imageView1, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL)); videoTextView = new TextView(context); videoTextView.setTextColor(0xffffffff); videoTextView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); videoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12); videoTextView.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO); videoInfoContainer.addView(videoTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 13, -0.7f, 0, 0)); checkBox = new CheckBox2(context, 24, resourcesProvider); checkBox.setDrawBackgroundAsArc(7); checkBox.setColor(Theme.key_chat_attachCheckBoxBackground, Theme.key_chat_attachPhotoBackground, Theme.key_chat_attachCheckBoxCheck); addView(checkBox, LayoutHelper.createFrame(26, 26, Gravity.LEFT | Gravity.TOP, 52, 4, 0, 0)); checkBox.setVisibility(VISIBLE); setFocusable(true); checkFrame = new FrameLayout(context); addView(checkFrame, LayoutHelper.createFrame(42, 42, Gravity.LEFT | Gravity.TOP, 38, 0, 0, 0)); itemSize = AndroidUtilities.dp(80); } public boolean canRevealSpoiler() { return hasSpoiler && spoilerRevealProgress == 0f && (photoEntry == null || !photoEntry.isAttachSpoilerRevealed); } public void startRevealMedia(float x, float y) { spoilerRevealX = x; spoilerRevealY = y; spoilerMaxRadius = (float) Math.sqrt(Math.pow(getWidth(), 2) + Math.pow(getHeight(), 2)); ValueAnimator animator = ValueAnimator.ofFloat(0, 1).setDuration((long) MathUtils.clamp(spoilerMaxRadius * 0.3f, 250, 550)); animator.setInterpolator(CubicBezierInterpolator.EASE_BOTH); animator.addUpdateListener(animation -> { spoilerRevealProgress = (float) animation.getAnimatedValue(); invalidate(); }); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { photoEntry.isAttachSpoilerRevealed = true; invalidate(); } }); animator.start(); } public void setHasSpoiler(boolean hasSpoiler) { setHasSpoiler(hasSpoiler, null); } public void setHasSpoiler(boolean hasSpoiler, Float crossfadeDuration) { if (this.hasSpoiler != hasSpoiler) { spoilerRevealProgress = 0f; if (isLaidOut()) { Bitmap prevSnapshot = imageViewCrossfadeSnapshot; imageViewCrossfadeSnapshot = AndroidUtilities.snapshotView(imageView); if (prevSnapshot != null) { prevSnapshot.recycle(); } imageViewCrossfadeProgress = 0f; } else { if (imageViewCrossfadeSnapshot != null) { imageViewCrossfadeSnapshot.recycle(); imageViewCrossfadeSnapshot = null; } imageViewCrossfadeProgress = 1f; } this.hasSpoiler = hasSpoiler; this.crossfadeDuration = crossfadeDuration; imageView.setHasBlur(hasSpoiler); imageView.invalidate(); if (hasSpoiler) { updateSpoilers2(hasSpoiler); } } } private void updateSpoilers2(boolean hasSpoiler) { if (container == null || imageView == null || imageView.getMeasuredHeight() <= 0 || imageView.getMeasuredWidth() <= 0) { return; } if (hasSpoiler && SpoilerEffect2.supports()) { if (spoilerEffect2 == null) { spoilerEffect2 = SpoilerEffect2.getInstance(container); } } else { if (spoilerEffect2 != null) { spoilerEffect2.detach(this); spoilerEffect2 = null; } } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (spoilerEffect2 != null) { spoilerEffect2.detach(this); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (spoilerEffect2 != null) { if (spoilerEffect2.destroyed) { spoilerEffect2 = SpoilerEffect2.getInstance(this); } else { spoilerEffect2.attach(this); } } } public void setIsVertical(boolean value) { isVertical = value; } public void setItemSize(int size) { itemSize = size; LayoutParams layoutParams = (LayoutParams) container.getLayoutParams(); layoutParams.width = layoutParams.height = itemSize; layoutParams = (LayoutParams) checkFrame.getLayoutParams(); layoutParams.gravity = Gravity.RIGHT | Gravity.TOP; layoutParams.leftMargin = 0; layoutParams = (LayoutParams) checkBox.getLayoutParams(); layoutParams.gravity = Gravity.RIGHT | Gravity.TOP; layoutParams.leftMargin = 0; layoutParams.rightMargin = layoutParams.topMargin = AndroidUtilities.dp(5); checkBox.setDrawBackgroundAsArc(6); itemSizeChanged = true; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (itemSizeChanged) { super.onMeasure(MeasureSpec.makeMeasureSpec(itemSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(itemSize + AndroidUtilities.dp(5), MeasureSpec.EXACTLY)); } else { if (isVertical) { super.onMeasure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(80), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(80 + (isLast ? 0 : 6)), MeasureSpec.EXACTLY)); } else { super.onMeasure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(80 + (isLast ? 0 : 6)), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(80), MeasureSpec.EXACTLY)); } } } public MediaController.PhotoEntry getPhotoEntry() { return photoEntry; } public BackupImageView getImageView() { return imageView; } public float getScale() { return container.getScaleX(); } public CheckBox2 getCheckBox() { return checkBox; } public FrameLayout getCheckFrame() { return checkFrame; } public View getVideoInfoContainer() { return videoInfoContainer; } public void setPhotoEntry(MediaController.PhotoEntry entry, boolean needCheckShow, boolean last) { pressed = false; photoEntry = entry; isLast = last; if (photoEntry.isVideo) { imageView.setOrientation(0, true); videoInfoContainer.setVisibility(VISIBLE); videoTextView.setText(AndroidUtilities.formatShortDuration(photoEntry.duration)); } else { videoInfoContainer.setVisibility(INVISIBLE); } if (photoEntry.thumbPath != null) { imageView.setImage(photoEntry.thumbPath, null, Theme.chat_attachEmptyDrawable); } else if (photoEntry.path != null) { if (photoEntry.isVideo) { imageView.setImage("vthumb://" + photoEntry.imageId + ":" + photoEntry.path, null, Theme.chat_attachEmptyDrawable); } else { imageView.setOrientation(photoEntry.orientation, photoEntry.invert, true); imageView.setImage("thumb://" + photoEntry.imageId + ":" + photoEntry.path, null, Theme.chat_attachEmptyDrawable); } } else { imageView.setImageDrawable(Theme.chat_attachEmptyDrawable); } boolean showing = needCheckShow && PhotoViewer.isShowingImage(photoEntry.path); imageView.getImageReceiver().setVisible(!showing, true); checkBox.setAlpha(showing ? 0.0f : 1.0f); videoInfoContainer.setAlpha(showing ? 0.0f : 1.0f); requestLayout(); setHasSpoiler(entry.hasSpoiler); } public void setPhotoEntry(MediaController.SearchImage searchImage, boolean needCheckShow, boolean last) { pressed = false; searchEntry = searchImage; isLast = last; Drawable thumb = zoomOnSelect ? Theme.chat_attachEmptyDrawable : getResources().getDrawable(R.drawable.nophotos); if (searchImage.thumbPhotoSize != null) { imageView.setImage(ImageLocation.getForPhoto(searchImage.thumbPhotoSize, searchImage.photo), null, thumb, searchImage); } else if (searchImage.photoSize != null) { imageView.setImage(ImageLocation.getForPhoto(searchImage.photoSize, searchImage.photo), "80_80", thumb, searchImage); } else if (searchImage.thumbPath != null) { imageView.setImage(searchImage.thumbPath, null, thumb); } else if (!TextUtils.isEmpty(searchImage.thumbUrl)) { ImageLocation location = ImageLocation.getForPath(searchImage.thumbUrl); if (searchImage.type == 1 && searchImage.thumbUrl.endsWith("mp4")) { location.imageType = FileLoader.IMAGE_TYPE_ANIMATION; } imageView.setImage(location, null, thumb, searchImage); } else if (searchImage.document != null) { MessageObject.getDocumentVideoThumb(searchImage.document); TLRPC.VideoSize videoSize = MessageObject.getDocumentVideoThumb(searchImage.document); if (videoSize != null) { TLRPC.PhotoSize currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(searchImage.document.thumbs, 90); imageView.setImage(ImageLocation.getForDocument(videoSize, searchImage.document), null, ImageLocation.getForDocument(currentPhotoObject, searchImage.document), "52_52", null, -1, 1, searchImage); } else { TLRPC.PhotoSize photoSize = FileLoader.getClosestPhotoSizeWithSize(searchImage.document.thumbs, 320); imageView.setImage(ImageLocation.getForDocument(photoSize, searchImage.document), null, thumb, searchImage); } } else { imageView.setImageDrawable(thumb); } boolean showing = needCheckShow && PhotoViewer.isShowingImage(searchImage.getPathToAttach()); imageView.getImageReceiver().setVisible(!showing, true); checkBox.setAlpha(showing ? 0.0f : 1.0f); videoInfoContainer.setAlpha(showing ? 0.0f : 1.0f); requestLayout(); setHasSpoiler(false); } public boolean isChecked() { return checkBox.isChecked(); } public void setChecked(int num, boolean checked, boolean animated) { checkBox.setChecked(num, checked, animated); if (itemSizeChanged) { if (animator != null) { animator.cancel(); animator = null; } if (animated) { animator = new AnimatorSet(); animator.playTogether( ObjectAnimator.ofFloat(container, View.SCALE_X, checked ? 0.787f : 1.0f), ObjectAnimator.ofFloat(container, View.SCALE_Y, checked ? 0.787f : 1.0f)); animator.setDuration(200); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (animator != null && animator.equals(animation)) { animator = null; if (!checked) { setBackgroundColor(0); } } } @Override public void onAnimationCancel(Animator animation) { if (animator != null && animator.equals(animation)) { animator = null; } } }); animator.start(); } else { container.setScaleX(checked ? 0.787f : 1.0f); container.setScaleY(checked ? 0.787f : 1.0f); } } } public void setNum(int num) { checkBox.setNum(num); } public void setOnCheckClickLisnener(OnClickListener onCheckClickLisnener) { checkFrame.setOnClickListener(onCheckClickLisnener); } public void setDelegate(PhotoAttachPhotoCellDelegate delegate) { this.delegate = delegate; } public void callDelegate() { delegate.onCheckClick(this); } public void showImage() { imageView.getImageReceiver().setVisible(true, true); } public void showCheck(boolean show) { if (show && checkBox.getAlpha() == 1 || !show && checkBox.getAlpha() == 0) { return; } if (animatorSet != null) { animatorSet.cancel(); animatorSet = null; } animatorSet = new AnimatorSet(); animatorSet.setInterpolator(new DecelerateInterpolator()); animatorSet.setDuration(180); animatorSet.playTogether( ObjectAnimator.ofFloat(videoInfoContainer, View.ALPHA, show ? 1.0f : 0.0f), ObjectAnimator.ofFloat(checkBox, View.ALPHA, show ? 1.0f : 0.0f)); animatorSet.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (animation.equals(animatorSet)) { animatorSet = null; } } }); animatorSet.start(); } @Override public void clearAnimation() { super.clearAnimation(); if (animator != null) { animator.cancel(); animator = null; container.setScaleX(checkBox.isChecked() ? 0.787f : 1.0f); container.setScaleY(checkBox.isChecked() ? 0.787f : 1.0f); } } @Override public boolean onTouchEvent(MotionEvent event) { boolean result = false; checkFrame.getHitRect(rect); if (event.getAction() == MotionEvent.ACTION_DOWN) { if (rect.contains((int) event.getX(), (int) event.getY())) { pressed = true; invalidate(); result = true; } } else if (pressed) { if (event.getAction() == MotionEvent.ACTION_UP) { getParent().requestDisallowInterceptTouchEvent(true); pressed = false; playSoundEffect(SoundEffectConstants.CLICK); sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); delegate.onCheckClick(this); invalidate(); } else if (event.getAction() == MotionEvent.ACTION_CANCEL) { pressed = false; invalidate(); } else if (event.getAction() == MotionEvent.ACTION_MOVE) { if (!(rect.contains((int) event.getX(), (int) event.getY()))) { pressed = false; invalidate(); } } } if (!result) { result = super.onTouchEvent(event); } return result; } @Override protected void onDraw(Canvas canvas) { if (checkBox.isChecked() || container.getScaleX() != 1.0f || !imageView.getImageReceiver().hasNotThumb() || imageView.getImageReceiver().getCurrentAlpha() != 1.0f || photoEntry != null && PhotoViewer.isShowingImage(photoEntry.path) || searchEntry != null && PhotoViewer.isShowingImage(searchEntry.getPathToAttach())) { backgroundPaint.setColor(getThemedColor(Theme.key_chat_attachPhotoBackground)); canvas.drawRect(0, 0, imageView.getMeasuredWidth(), imageView.getMeasuredHeight(), backgroundPaint); } } @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setEnabled(true); StringBuilder sb = new StringBuilder(); if (photoEntry != null && photoEntry.isVideo) { sb.append(LocaleController.getString("AttachVideo", R.string.AttachVideo) + ", " + LocaleController.formatDuration(photoEntry.duration)); } else { sb.append(LocaleController.getString("AttachPhoto", R.string.AttachPhoto)); } if (photoEntry != null) { sb.append(". "); sb.append(LocaleController.getInstance().formatterStats.format(photoEntry.dateTaken * 1000L)); } info.setText(sb); if (checkBox.isChecked()) { info.setSelected(true); } if (Build.VERSION.SDK_INT >= 21) { info.addAction(new AccessibilityNodeInfo.AccessibilityAction(R.id.acc_action_open_photo, LocaleController.getString("Open", R.string.Open))); } } @Override public boolean performAccessibilityAction(int action, Bundle arguments) { if (action == R.id.acc_action_open_photo) { View parent = (View) getParent(); parent.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, getLeft(), getTop() + getHeight() - 1, 0)); parent.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, getLeft(), getTop() + getHeight() - 1, 0)); } return super.performAccessibilityAction(action, arguments); } protected int getThemedColor(int key) { return Theme.getColor(key, resourcesProvider); } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoAttachPhotoCell.java
41,685
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.ui; import android.Manifest; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.annotation.TargetApi; import android.app.DatePickerDialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Canvas; import android.graphics.Outline; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextPaint; import android.text.TextUtils; import android.text.style.CharacterStyle; import android.text.style.ClickableSpan; import android.text.style.DynamicDrawableSpan; import android.text.style.ImageSpan; import android.text.style.URLSpan; import android.util.TypedValue; import android.view.Gravity; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.TextureView; import android.view.View; import android.view.ViewGroup; import android.view.ViewOutlineProvider; import android.view.ViewTreeObserver; import android.view.WindowManager; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.collection.LongSparseArray; import androidx.core.content.FileProvider; import androidx.recyclerview.widget.ChatListItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.LinearSmoothScrollerCustom; import androidx.recyclerview.widget.RecyclerView; import com.google.android.exoplayer2.ui.AspectRatioFrameLayout; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.BuildVars; import org.telegram.messenger.ChatObject; import org.telegram.messenger.ContactsController; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.ImageLocation; import org.telegram.messenger.ImageReceiver; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MediaController; import org.telegram.messenger.MediaDataController; import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessagesController; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.UserConfig; import org.telegram.messenger.UserObject; import org.telegram.messenger.Utilities; import org.telegram.messenger.browser.Browser; import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.ActionBar; import org.telegram.ui.ActionBar.ActionBarMenu; import org.telegram.ui.ActionBar.ActionBarMenuItem; import org.telegram.ui.ActionBar.ActionBarMenuSubItem; import org.telegram.ui.ActionBar.ActionBarPopupWindow; import org.telegram.ui.ActionBar.AlertDialog; import org.telegram.ui.ActionBar.BackDrawable; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.BottomSheet; import org.telegram.ui.ActionBar.SimpleTextView; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.ThemeDescription; import org.telegram.ui.Cells.ChatActionCell; import org.telegram.ui.Cells.ChatLoadingCell; import org.telegram.ui.Cells.ChatMessageCell; import org.telegram.ui.Cells.ChatUnreadCell; import org.telegram.ui.Components.AdminLogFilterAlert; import org.telegram.ui.Components.AlertsCreator; import org.telegram.ui.Components.Bulletin; import org.telegram.ui.Components.BulletinFactory; import org.telegram.ui.Components.ChatAvatarContainer; import org.telegram.ui.Components.ChatScrimPopupContainerLayout; import org.telegram.ui.Components.ClearHistoryAlert; import org.telegram.ui.Components.EmbedBottomSheet; import org.telegram.ui.Components.InviteLinkBottomSheet; import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.PhonebookShareAlert; import org.telegram.ui.Components.PipRoundVideoView; import org.telegram.ui.Components.RadialProgressView; import org.telegram.ui.Components.RecyclerListView; import org.telegram.ui.Components.ShareAlert; import org.telegram.ui.Components.SizeNotifierFrameLayout; import org.telegram.ui.Components.StickersAlert; import org.telegram.ui.Components.URLSpanMono; import org.telegram.ui.Components.URLSpanNoUnderline; import org.telegram.ui.Components.URLSpanReplacement; import org.telegram.ui.Components.URLSpanUserMention; import org.telegram.ui.Components.UndoView; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashMap; public class ChannelAdminLogActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate { protected TLRPC.Chat currentChat; private ArrayList<ChatMessageCell> chatMessageCellsCache = new ArrayList<>(); private FrameLayout progressView; private View progressView2; private RadialProgressView progressBar; private RecyclerListView chatListView; private UndoView undoView; private LinearLayoutManager chatLayoutManager; private ChatActivityAdapter chatAdapter; private TextView bottomOverlayChatText; private ImageView bottomOverlayImage; private FrameLayout bottomOverlayChat; private FrameLayout emptyViewContainer; private ChatAvatarContainer avatarContainer; private TextView emptyView; private ChatActionCell floatingDateView; private ActionBarMenuItem searchItem; private long minEventId; private boolean currentFloatingDateOnScreen; private boolean currentFloatingTopIsNotMessage; private AnimatorSet floatingDateAnimation; private boolean scrollingFloatingDate; private int[] mid = new int[]{2}; private boolean searchWas; private boolean checkTextureViewPosition; private SizeNotifierFrameLayout contentView; private MessageObject selectedObject; private FrameLayout searchContainer; private ImageView searchCalendarButton; private ImageView searchUpButton; private ImageView searchDownButton; private SimpleTextView searchCountText; private FrameLayout roundVideoContainer; private AspectRatioFrameLayout aspectRatioFrameLayout; private TextureView videoTextureView; private Path aspectPath; private Paint aspectPaint; private int scrollToPositionOnRecreate = -1; private int scrollToOffsetOnRecreate = 0; private boolean paused = true; private boolean wasPaused = false; private boolean openAnimationEnded; private LongSparseArray<MessageObject> messagesDict = new LongSparseArray<>(); private HashMap<String, ArrayList<MessageObject>> messagesByDays = new HashMap<>(); protected ArrayList<MessageObject> messages = new ArrayList<>(); private int minDate; private boolean endReached; private boolean loading; private int loadsCount; private ArrayList<TLRPC.ChannelParticipant> admins; private TLRPC.TL_channelAdminLogEventsFilter currentFilter = null; private String searchQuery = ""; private LongSparseArray<TLRPC.User> selectedAdmins; private MessageObject scrollToMessage; private int allowAnimationIndex; private HashMap<String, Object> invitesCache = new HashMap<>(); private HashMap<Long, TLRPC.User> usersMap; private boolean linviteLoading; private PhotoViewer.PhotoViewerProvider provider = new PhotoViewer.EmptyPhotoViewerProvider() { @Override public PhotoViewer.PlaceProviderObject getPlaceForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index, boolean needPreview) { int count = chatListView.getChildCount(); for (int a = 0; a < count; a++) { ImageReceiver imageReceiver = null; View view = chatListView.getChildAt(a); if (view instanceof ChatMessageCell) { if (messageObject != null) { ChatMessageCell cell = (ChatMessageCell) view; MessageObject message = cell.getMessageObject(); if (message != null && message.getId() == messageObject.getId()) { imageReceiver = cell.getPhotoImage(); } } } else if (view instanceof ChatActionCell) { ChatActionCell cell = (ChatActionCell) view; MessageObject message = cell.getMessageObject(); if (message != null) { if (messageObject != null) { if (message.getId() == messageObject.getId()) { imageReceiver = cell.getPhotoImage(); } } else if (fileLocation != null && message.photoThumbs != null) { for (int b = 0; b < message.photoThumbs.size(); b++) { TLRPC.PhotoSize photoSize = message.photoThumbs.get(b); if (photoSize.location.volume_id == fileLocation.volume_id && photoSize.location.local_id == fileLocation.local_id) { imageReceiver = cell.getPhotoImage(); break; } } } } } if (imageReceiver != null) { int[] coords = new int[2]; view.getLocationInWindow(coords); PhotoViewer.PlaceProviderObject object = new PhotoViewer.PlaceProviderObject(); object.viewX = coords[0]; object.viewY = coords[1] - (Build.VERSION.SDK_INT >= 21 ? 0 : AndroidUtilities.statusBarHeight); object.parentView = chatListView; object.imageReceiver = imageReceiver; object.thumb = imageReceiver.getBitmapSafe(); object.radius = imageReceiver.getRoundRadius(); object.isEvent = true; return object; } } return null; } }; private ChatListItemAnimator chatListItemAnimator; public ChannelAdminLogActivity(TLRPC.Chat chat) { currentChat = chat; } @Override public boolean onFragmentCreate() { super.onFragmentCreate(); NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.emojiLoaded); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingDidStart); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingPlayStateChanged); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingDidReset); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingProgressDidChanged); NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.didSetNewWallpapper); loadMessages(true); loadAdmins(); Bulletin.addDelegate(this, new Bulletin.Delegate() { @Override public int getBottomOffset(int tag) { return AndroidUtilities.dp(51); } }); return true; } @Override public void onFragmentDestroy() { super.onFragmentDestroy(); NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.emojiLoaded); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.messagePlayingDidStart); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.messagePlayingPlayStateChanged); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.messagePlayingDidReset); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.messagePlayingProgressDidChanged); NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.didSetNewWallpapper); getNotificationCenter().onAnimationFinish(allowAnimationIndex); } private void updateEmptyPlaceholder() { if (emptyView == null) { return; } if (!TextUtils.isEmpty(searchQuery)) { emptyView.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(5), AndroidUtilities.dp(8), AndroidUtilities.dp(5)); emptyView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("EventLogEmptyTextSearch", R.string.EventLogEmptyTextSearch, searchQuery))); } else if (selectedAdmins != null || currentFilter != null) { emptyView.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(5), AndroidUtilities.dp(8), AndroidUtilities.dp(5)); emptyView.setText(AndroidUtilities.replaceTags(LocaleController.getString("EventLogEmptySearch", R.string.EventLogEmptySearch))); } else { emptyView.setPadding(AndroidUtilities.dp(16), AndroidUtilities.dp(16), AndroidUtilities.dp(16), AndroidUtilities.dp(16)); if (currentChat.megagroup) { emptyView.setText(AndroidUtilities.replaceTags(LocaleController.getString("EventLogEmpty", R.string.EventLogEmpty))); } else { emptyView.setText(AndroidUtilities.replaceTags(LocaleController.getString("EventLogEmptyChannel", R.string.EventLogEmptyChannel))); } } } private void loadMessages(boolean reset) { if (loading) { return; } if (reset) { minEventId = Long.MAX_VALUE; if (progressView != null) { AndroidUtilities.updateViewVisibilityAnimated(progressView, true, 0.3f, true); emptyViewContainer.setVisibility(View.INVISIBLE); chatListView.setEmptyView(null); } messagesDict.clear(); messages.clear(); messagesByDays.clear(); } loading = true; TLRPC.TL_channels_getAdminLog req = new TLRPC.TL_channels_getAdminLog(); req.channel = MessagesController.getInputChannel(currentChat); req.q = searchQuery; req.limit = 50; if (!reset && !messages.isEmpty()) { req.max_id = minEventId; } else { req.max_id = 0; } req.min_id = 0; if (currentFilter != null) { req.flags |= 1; req.events_filter = currentFilter; } if (selectedAdmins != null) { req.flags |= 2; for (int a = 0; a < selectedAdmins.size(); a++) { req.admins.add(MessagesController.getInstance(currentAccount).getInputUser(selectedAdmins.valueAt(a))); } } updateEmptyPlaceholder(); ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> { if (response != null) { final TLRPC.TL_channels_adminLogResults res = (TLRPC.TL_channels_adminLogResults) response; AndroidUtilities.runOnUIThread(() -> { chatListItemAnimator.setShouldAnimateEnterFromBottom(false); MessagesController.getInstance(currentAccount).putUsers(res.users, false); MessagesController.getInstance(currentAccount).putChats(res.chats, false); boolean added = false; int oldRowsCount = messages.size(); for (int a = 0; a < res.events.size(); a++) { TLRPC.TL_channelAdminLogEvent event = res.events.get(a); if (messagesDict.indexOfKey(event.id) >= 0) { continue; } if (event.action instanceof TLRPC.TL_channelAdminLogEventActionParticipantToggleAdmin) { TLRPC.TL_channelAdminLogEventActionParticipantToggleAdmin action = (TLRPC.TL_channelAdminLogEventActionParticipantToggleAdmin) event.action; if (action.prev_participant instanceof TLRPC.TL_channelParticipantCreator && !(action.new_participant instanceof TLRPC.TL_channelParticipantCreator)) { continue; } } minEventId = Math.min(minEventId, event.id); added = true; MessageObject messageObject = new MessageObject(currentAccount, event, messages, messagesByDays, currentChat, mid, false); if (messageObject.contentType < 0) { continue; } messagesDict.put(event.id, messageObject); } int newRowsCount = messages.size() - oldRowsCount; loading = false; if (!added) { endReached = true; } AndroidUtilities.updateViewVisibilityAnimated(progressView, false, 0.3f, true); chatListView.setEmptyView(emptyViewContainer); if (newRowsCount != 0) { boolean end = false; if (endReached) { end = true; chatAdapter.notifyItemRangeChanged(0, 2); } int firstVisPos = chatLayoutManager.findLastVisibleItemPosition(); View firstVisView = chatLayoutManager.findViewByPosition(firstVisPos); int top = ((firstVisView == null) ? 0 : firstVisView.getTop()) - chatListView.getPaddingTop(); if (newRowsCount - (end ? 1 : 0) > 0) { int insertStart = 1 + (end ? 0 : 1); chatAdapter.notifyItemChanged(insertStart); chatAdapter.notifyItemRangeInserted(insertStart, newRowsCount - (end ? 1 : 0)); } if (firstVisPos != -1) { chatLayoutManager.scrollToPositionWithOffset(firstVisPos + newRowsCount - (end ? 1 : 0), top); } } else if (endReached) { chatAdapter.notifyItemRemoved(0); } }); } }); if (reset && chatAdapter != null) { chatAdapter.notifyDataSetChanged(); } } @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.emojiLoaded) { if (chatListView != null) { chatListView.invalidateViews(); } } else if (id == NotificationCenter.messagePlayingDidStart) { MessageObject messageObject = (MessageObject) args[0]; if (messageObject.isRoundVideo()) { MediaController.getInstance().setTextureView(createTextureView(true), aspectRatioFrameLayout, roundVideoContainer, true); updateTextureViewPosition(); } if (chatListView != null) { int count = chatListView.getChildCount(); for (int a = 0; a < count; a++) { View view = chatListView.getChildAt(a); if (view instanceof ChatMessageCell) { ChatMessageCell cell = (ChatMessageCell) view; MessageObject messageObject1 = cell.getMessageObject(); if (messageObject1 != null) { if (messageObject1.isVoice() || messageObject1.isMusic()) { cell.updateButtonState(false, true, false); } else if (messageObject1.isRoundVideo()) { cell.checkVideoPlayback(false, null); if (!MediaController.getInstance().isPlayingMessage(messageObject1)) { if (messageObject1.audioProgress != 0) { messageObject1.resetPlayingProgress(); cell.invalidate(); } } } } } } } } else if (id == NotificationCenter.messagePlayingDidReset || id == NotificationCenter.messagePlayingPlayStateChanged) { if (chatListView != null) { int count = chatListView.getChildCount(); for (int a = 0; a < count; a++) { View view = chatListView.getChildAt(a); if (view instanceof ChatMessageCell) { ChatMessageCell cell = (ChatMessageCell) view; MessageObject messageObject = cell.getMessageObject(); if (messageObject != null) { if (messageObject.isVoice() || messageObject.isMusic()) { cell.updateButtonState(false, true, false); } else if (messageObject.isRoundVideo()) { if (!MediaController.getInstance().isPlayingMessage(messageObject)) { cell.checkVideoPlayback(true, null); } } } } } } } else if (id == NotificationCenter.messagePlayingProgressDidChanged) { Integer mid = (Integer) args[0]; if (chatListView != null) { int count = chatListView.getChildCount(); for (int a = 0; a < count; a++) { View view = chatListView.getChildAt(a); if (view instanceof ChatMessageCell) { ChatMessageCell cell = (ChatMessageCell) view; MessageObject playing = cell.getMessageObject(); if (playing != null && playing.getId() == mid) { MessageObject player = MediaController.getInstance().getPlayingMessageObject(); if (player != null) { playing.audioProgress = player.audioProgress; playing.audioProgressSec = player.audioProgressSec; playing.audioPlayerDuration = player.audioPlayerDuration; cell.updatePlayingMessageProgress(); } break; } } } } } else if (id == NotificationCenter.didSetNewWallpapper) { if (fragmentView != null) { contentView.setBackgroundImage(Theme.getCachedWallpaper(), Theme.isWallpaperMotion()); progressView2.invalidate(); if (emptyView != null) { emptyView.invalidate(); } chatListView.invalidateViews(); } } } private void updateBottomOverlay() { /*if (searchItem != null && searchItem.getVisibility() == View.VISIBLE) { searchContainer.setVisibility(View.VISIBLE); bottomOverlayChat.setVisibility(View.INVISIBLE); } else { searchContainer.setVisibility(View.INVISIBLE); bottomOverlayChat.setVisibility(View.VISIBLE); }*/ } @Override public View createView(Context context) { if (chatMessageCellsCache.isEmpty()) { for (int a = 0; a < 8; a++) { chatMessageCellsCache.add(new ChatMessageCell(context)); } } searchWas = false; hasOwnBackground = true; Theme.createChatResources(context, false); actionBar.setAddToContainer(false); actionBar.setOccupyStatusBar(Build.VERSION.SDK_INT >= 21 && !AndroidUtilities.isTablet()); actionBar.setBackButtonDrawable(new BackDrawable(false)); actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override public void onItemClick(final int id) { if (id == -1) { finishFragment(); } } }); avatarContainer = new ChatAvatarContainer(context, null, false); avatarContainer.setOccupyStatusBar(!AndroidUtilities.isTablet()); actionBar.addView(avatarContainer, 0, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 56, 0, 40, 0)); ActionBarMenu menu = actionBar.createMenu(); searchItem = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() { @Override public void onSearchCollapse() { searchQuery = ""; avatarContainer.setVisibility(View.VISIBLE); if (searchWas) { searchWas = false; loadMessages(true); } /*highlightMessageId = Integer.MAX_VALUE; updateVisibleRows(); scrollToLastMessage(false); */ updateBottomOverlay(); } @Override public void onSearchExpand() { avatarContainer.setVisibility(View.GONE); updateBottomOverlay(); } @Override public void onSearchPressed(EditText editText) { searchWas = true; searchQuery = editText.getText().toString(); loadMessages(true); //updateSearchButtons(0, 0, 0); } }); searchItem.setSearchFieldHint(LocaleController.getString("Search", R.string.Search)); avatarContainer.setEnabled(false); avatarContainer.setTitle(currentChat.title); avatarContainer.setSubtitle(LocaleController.getString("EventLogAllEvents", R.string.EventLogAllEvents)); avatarContainer.setChatAvatar(currentChat); fragmentView = new SizeNotifierFrameLayout(context) { @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject(); if (messageObject != null && messageObject.isRoundVideo() && messageObject.eventId != 0 && messageObject.getDialogId() == -currentChat.id) { MediaController.getInstance().setTextureView(createTextureView(false), aspectRatioFrameLayout, roundVideoContainer, true); } } @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { boolean result = super.drawChild(canvas, child, drawingTime); if (child == actionBar && parentLayout != null) { parentLayout.drawHeaderShadow(canvas, actionBar.getVisibility() == VISIBLE ? actionBar.getMeasuredHeight() : 0); } return result; } @Override protected boolean isActionBarVisible() { return actionBar.getVisibility() == VISIBLE; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int allHeight; int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); setMeasuredDimension(widthSize, heightSize); heightSize -= getPaddingTop(); measureChildWithMargins(actionBar, widthMeasureSpec, 0, heightMeasureSpec, 0); int actionBarHeight = actionBar.getMeasuredHeight(); if (actionBar.getVisibility() == VISIBLE) { heightSize -= actionBarHeight; } int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); if (child == null || child.getVisibility() == GONE || child == actionBar) { continue; } if (child == chatListView || child == progressView) { int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY); int contentHeightSpec = MeasureSpec.makeMeasureSpec(Math.max(AndroidUtilities.dp(10), heightSize - AndroidUtilities.dp(48 + 2)), MeasureSpec.EXACTLY); child.measure(contentWidthSpec, contentHeightSpec); } else if (child == emptyViewContainer) { int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY); int contentHeightSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY); child.measure(contentWidthSpec, contentHeightSpec); } else { measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0); } } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int width = child.getMeasuredWidth(); final int height = child.getMeasuredHeight(); int childLeft; int childTop; int gravity = lp.gravity; if (gravity == -1) { gravity = Gravity.TOP | Gravity.LEFT; } final int absoluteGravity = gravity & Gravity.HORIZONTAL_GRAVITY_MASK; final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK; switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { case Gravity.CENTER_HORIZONTAL: childLeft = (r - l - width) / 2 + lp.leftMargin - lp.rightMargin; break; case Gravity.RIGHT: childLeft = r - width - lp.rightMargin; break; case Gravity.LEFT: default: childLeft = lp.leftMargin; } switch (verticalGravity) { case Gravity.TOP: childTop = lp.topMargin + getPaddingTop(); if (child != actionBar && actionBar.getVisibility() == VISIBLE) { childTop += actionBar.getMeasuredHeight(); } break; case Gravity.CENTER_VERTICAL: childTop = (b - t - height) / 2 + lp.topMargin - lp.bottomMargin; break; case Gravity.BOTTOM: childTop = (b - t) - height - lp.bottomMargin; break; default: childTop = lp.topMargin; } if (child == emptyViewContainer) { childTop -= AndroidUtilities.dp(24) - (actionBar.getVisibility() == VISIBLE ? actionBar.getMeasuredHeight() / 2 : 0); } else if (child == actionBar) { childTop -= getPaddingTop(); } else if (child == backgroundView) { childTop = 0; } child.layout(childLeft, childTop, childLeft + width, childTop + height); } updateMessagesVisiblePart(); notifyHeightChanged(); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (AvatarPreviewer.hasVisibleInstance()) { AvatarPreviewer.getInstance().onTouchEvent(ev); return true; } return super.dispatchTouchEvent(ev); } }; contentView = (SizeNotifierFrameLayout) fragmentView; contentView.setOccupyStatusBar(!AndroidUtilities.isTablet()); contentView.setBackgroundImage(Theme.getCachedWallpaper(), Theme.isWallpaperMotion()); emptyViewContainer = new FrameLayout(context); emptyViewContainer.setVisibility(View.INVISIBLE); contentView.addView(emptyViewContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER)); emptyViewContainer.setOnTouchListener((v, event) -> true); emptyView = new TextView(context); emptyView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); emptyView.setGravity(Gravity.CENTER); emptyView.setTextColor(Theme.getColor(Theme.key_chat_serviceText)); emptyView.setBackground(Theme.createServiceDrawable(AndroidUtilities.dp(6), emptyView, contentView)); emptyView.setPadding(AndroidUtilities.dp(16), AndroidUtilities.dp(16), AndroidUtilities.dp(16), AndroidUtilities.dp(16)); emptyViewContainer.addView(emptyView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 16, 0, 16, 0)); chatListView = new RecyclerListView(context) { @Override public boolean drawChild(Canvas canvas, View child, long drawingTime) { boolean result = super.drawChild(canvas, child, drawingTime); if (child instanceof ChatMessageCell) { ChatMessageCell chatMessageCell = (ChatMessageCell) child; ImageReceiver imageReceiver = chatMessageCell.getAvatarImage(); if (imageReceiver != null) { if (chatMessageCell.getMessageObject().deleted) { imageReceiver.setVisible(false, false); return result; } int top = (int) child.getY(); if (chatMessageCell.drawPinnedBottom()) { int p; ViewHolder holder = chatListView.getChildViewHolder(child); p = holder.getAdapterPosition(); if (p >= 0) { int nextPosition; nextPosition = p + 1; holder = chatListView.findViewHolderForAdapterPosition(nextPosition); if (holder != null) { imageReceiver.setVisible(false, false); return result; } } } float tx = chatMessageCell.getSlidingOffsetX() + chatMessageCell.getCheckBoxTranslation(); int y = (int) child.getY() + chatMessageCell.getLayoutHeight(); int maxY = chatListView.getMeasuredHeight() - chatListView.getPaddingBottom(); if (y > maxY) { y = maxY; } if (chatMessageCell.drawPinnedTop()) { int p; ViewHolder holder = chatListView.getChildViewHolder(child); p = holder.getAdapterPosition(); if (p >= 0) { int tries = 0; while (true) { if (tries >= 20) { break; } tries++; int prevPosition; prevPosition = p - 1; holder = chatListView.findViewHolderForAdapterPosition(prevPosition); if (holder != null) { top = holder.itemView.getTop(); if (holder.itemView instanceof ChatMessageCell) { chatMessageCell = (ChatMessageCell) holder.itemView; if (!chatMessageCell.drawPinnedTop()) { break; } else { p = prevPosition; } } else { break; } } else { break; } } } } if (y - AndroidUtilities.dp(48) < top) { y = top + AndroidUtilities.dp(48); } if (!chatMessageCell.drawPinnedBottom()) { int cellBottom = (int) (chatMessageCell.getY() + chatMessageCell.getMeasuredHeight()); if (y > cellBottom) { y = cellBottom; } } canvas.save(); if (tx != 0) { canvas.translate(tx, 0); } if (chatMessageCell.getCurrentMessagesGroup() != null) { if (chatMessageCell.getCurrentMessagesGroup().transitionParams.backgroundChangeBounds) { y -= chatMessageCell.getTranslationY(); } } imageReceiver.setImageY(y - AndroidUtilities.dp(44)); if (chatMessageCell.shouldDrawAlphaLayer()) { imageReceiver.setAlpha(chatMessageCell.getAlpha()); canvas.scale( chatMessageCell.getScaleX(), chatMessageCell.getScaleY(), chatMessageCell.getX() + chatMessageCell.getPivotX(), chatMessageCell.getY() + (chatMessageCell.getHeight() >> 1) ); } else { imageReceiver.setAlpha(1f); } imageReceiver.setVisible(true, false); imageReceiver.draw(canvas); canvas.restore(); } } return result; } }; chatListView.setOnItemClickListener(new RecyclerListView.OnItemClickListenerExtended() { @Override public void onItemClick(View view, int position, float x, float y) { createMenu(view, x, y); } }); chatListView.setTag(1); chatListView.setVerticalScrollBarEnabled(true); chatListView.setAdapter(chatAdapter = new ChatActivityAdapter(context)); chatListView.setClipToPadding(false); chatListView.setPadding(0, AndroidUtilities.dp(4), 0, AndroidUtilities.dp(3)); chatListView.setItemAnimator(chatListItemAnimator = new ChatListItemAnimator(null, chatListView, null) { int scrollAnimationIndex = -1; Runnable finishRunnable; public void onAnimationStart() { if (scrollAnimationIndex == -1) { scrollAnimationIndex = getNotificationCenter().setAnimationInProgress(scrollAnimationIndex, null, false); } if (finishRunnable != null) { AndroidUtilities.cancelRunOnUIThread(finishRunnable); finishRunnable = null; } if (BuildVars.LOGS_ENABLED) { FileLog.d("admin logs chatItemAnimator disable notifications"); } } @Override protected void onAllAnimationsDone() { super.onAllAnimationsDone(); if (finishRunnable != null) { AndroidUtilities.cancelRunOnUIThread(finishRunnable); } AndroidUtilities.runOnUIThread(finishRunnable = () -> { if (scrollAnimationIndex != -1) { getNotificationCenter().onAnimationFinish(scrollAnimationIndex); scrollAnimationIndex = -1; } if (BuildVars.LOGS_ENABLED) { FileLog.d("admin logs chatItemAnimator enable notifications"); } }); } }); chatListItemAnimator.setReversePositions(true); chatListView.setLayoutAnimation(null); chatLayoutManager = new LinearLayoutManager(context) { @Override public boolean supportsPredictiveItemAnimations() { return true; } @Override public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) { LinearSmoothScrollerCustom linearSmoothScroller = new LinearSmoothScrollerCustom(recyclerView.getContext(), LinearSmoothScrollerCustom.POSITION_MIDDLE); linearSmoothScroller.setTargetPosition(position); startSmoothScroll(linearSmoothScroller); } }; chatLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); chatLayoutManager.setStackFromEnd(true); chatListView.setLayoutManager(chatLayoutManager); contentView.addView(chatListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); chatListView.setOnScrollListener(new RecyclerView.OnScrollListener() { private float totalDy = 0; private final int scrollValue = AndroidUtilities.dp(100); @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { if (newState == RecyclerView.SCROLL_STATE_DRAGGING) { scrollingFloatingDate = true; checkTextureViewPosition = true; } else if (newState == RecyclerView.SCROLL_STATE_IDLE) { scrollingFloatingDate = false; checkTextureViewPosition = false; hideFloatingDateView(true); } } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { chatListView.invalidate(); if (dy != 0 && scrollingFloatingDate && !currentFloatingTopIsNotMessage) { if (floatingDateView.getTag() == null) { if (floatingDateAnimation != null) { floatingDateAnimation.cancel(); } floatingDateView.setTag(1); floatingDateAnimation = new AnimatorSet(); floatingDateAnimation.setDuration(150); floatingDateAnimation.playTogether(ObjectAnimator.ofFloat(floatingDateView, "alpha", 1.0f)); floatingDateAnimation.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (animation.equals(floatingDateAnimation)) { floatingDateAnimation = null; } } }); floatingDateAnimation.start(); } } checkScrollForLoad(true); updateMessagesVisiblePart(); } }); if (scrollToPositionOnRecreate != -1) { chatLayoutManager.scrollToPositionWithOffset(scrollToPositionOnRecreate, scrollToOffsetOnRecreate); scrollToPositionOnRecreate = -1; } progressView = new FrameLayout(context); progressView.setVisibility(View.INVISIBLE); contentView.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT)); progressView2 = new View(context); progressView2.setBackground(Theme.createServiceDrawable(AndroidUtilities.dp(18), progressView2, contentView)); progressView.addView(progressView2, LayoutHelper.createFrame(36, 36, Gravity.CENTER)); progressBar = new RadialProgressView(context); progressBar.setSize(AndroidUtilities.dp(28)); progressBar.setProgressColor(Theme.getColor(Theme.key_chat_serviceText)); progressView.addView(progressBar, LayoutHelper.createFrame(32, 32, Gravity.CENTER)); floatingDateView = new ChatActionCell(context); floatingDateView.setAlpha(0.0f); floatingDateView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); contentView.addView(floatingDateView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 4, 0, 0)); contentView.addView(actionBar); bottomOverlayChat = new FrameLayout(context) { @Override public void onDraw(Canvas canvas) { int bottom = Theme.chat_composeShadowDrawable.getIntrinsicHeight(); Theme.chat_composeShadowDrawable.setBounds(0, 0, getMeasuredWidth(), bottom); Theme.chat_composeShadowDrawable.draw(canvas); canvas.drawRect(0, bottom, getMeasuredWidth(), getMeasuredHeight(), Theme.chat_composeBackgroundPaint); } }; bottomOverlayChat.setWillNotDraw(false); bottomOverlayChat.setPadding(0, AndroidUtilities.dp(3), 0, 0); contentView.addView(bottomOverlayChat, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM)); bottomOverlayChat.setOnClickListener(view -> { if (getParentActivity() == null) { return; } AdminLogFilterAlert adminLogFilterAlert = new AdminLogFilterAlert(getParentActivity(), currentFilter, selectedAdmins, currentChat.megagroup); adminLogFilterAlert.setCurrentAdmins(admins); adminLogFilterAlert.setAdminLogFilterAlertDelegate((filter, admins) -> { currentFilter = filter; selectedAdmins = admins; if (currentFilter != null || selectedAdmins != null) { avatarContainer.setSubtitle(LocaleController.getString("EventLogSelectedEvents", R.string.EventLogSelectedEvents)); } else { avatarContainer.setSubtitle(LocaleController.getString("EventLogAllEvents", R.string.EventLogAllEvents)); } loadMessages(true); }); showDialog(adminLogFilterAlert); }); bottomOverlayChatText = new TextView(context); bottomOverlayChatText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); bottomOverlayChatText.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); bottomOverlayChatText.setTextColor(Theme.getColor(Theme.key_chat_fieldOverlayText)); bottomOverlayChatText.setText(LocaleController.getString("SETTINGS", R.string.SETTINGS).toUpperCase()); bottomOverlayChat.addView(bottomOverlayChatText, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER)); bottomOverlayImage = new ImageView(context); bottomOverlayImage.setImageResource(R.drawable.msg_help); bottomOverlayImage.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_fieldOverlayText), PorterDuff.Mode.MULTIPLY)); bottomOverlayImage.setScaleType(ImageView.ScaleType.CENTER); bottomOverlayChat.addView(bottomOverlayImage, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP, 3, 0, 0, 0)); bottomOverlayImage.setContentDescription(LocaleController.getString("BotHelp", R.string.BotHelp)); bottomOverlayImage.setOnClickListener(v -> { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); if (currentChat.megagroup) { builder.setMessage(AndroidUtilities.replaceTags(LocaleController.getString("EventLogInfoDetail", R.string.EventLogInfoDetail))); } else { builder.setMessage(AndroidUtilities.replaceTags(LocaleController.getString("EventLogInfoDetailChannel", R.string.EventLogInfoDetailChannel))); } builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); builder.setTitle(LocaleController.getString("EventLogInfoTitle", R.string.EventLogInfoTitle)); showDialog(builder.create()); }); searchContainer = new FrameLayout(context) { @Override public void onDraw(Canvas canvas) { int bottom = Theme.chat_composeShadowDrawable.getIntrinsicHeight(); Theme.chat_composeShadowDrawable.setBounds(0, 0, getMeasuredWidth(), bottom); Theme.chat_composeShadowDrawable.draw(canvas); canvas.drawRect(0, bottom, getMeasuredWidth(), getMeasuredHeight(), Theme.chat_composeBackgroundPaint); } }; searchContainer.setWillNotDraw(false); searchContainer.setVisibility(View.INVISIBLE); searchContainer.setFocusable(true); searchContainer.setFocusableInTouchMode(true); searchContainer.setClickable(true); searchContainer.setPadding(0, AndroidUtilities.dp(3), 0, 0); contentView.addView(searchContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM)); /*searchUpButton = new ImageView(context); searchUpButton.setScaleType(ImageView.ScaleType.CENTER); searchUpButton.setImageResource(R.drawable.msg_go_up); searchUpButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_searchPanelIcons), PorterDuff.Mode.MULTIPLY)); searchContainer.addView(searchUpButton, LayoutHelper.createFrame(48, 48)); searchUpButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MessagesSearchQuery.searchMessagesInChat(null, dialog_id, mergeDialogId, classGuid, 1); } }); searchDownButton = new ImageView(context); searchDownButton.setScaleType(ImageView.ScaleType.CENTER); searchDownButton.setImageResource(R.drawable.msg_go_down); searchDownButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_searchPanelIcons), PorterDuff.Mode.MULTIPLY)); searchContainer.addView(searchDownButton, LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP, 48, 0, 0, 0)); searchDownButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MessagesSearchQuery.searchMessagesInChat(null, dialog_id, mergeDialogId, classGuid, 2); } });*/ searchCalendarButton = new ImageView(context); searchCalendarButton.setScaleType(ImageView.ScaleType.CENTER); searchCalendarButton.setImageResource(R.drawable.msg_calendar); searchCalendarButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_searchPanelIcons), PorterDuff.Mode.MULTIPLY)); searchContainer.addView(searchCalendarButton, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP)); searchCalendarButton.setOnClickListener(view -> { if (getParentActivity() == null) { return; } AndroidUtilities.hideKeyboard(searchItem.getSearchField()); showDialog(AlertsCreator.createCalendarPickerDialog(getParentActivity(), 1375315200000L, param -> loadMessages(true), null).create()); }); searchCountText = new SimpleTextView(context); searchCountText.setTextColor(Theme.getColor(Theme.key_chat_searchPanelText)); searchCountText.setTextSize(15); searchCountText.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); searchContainer.addView(searchCountText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 108, 0, 0, 0)); chatAdapter.updateRows(); if (loading && messages.isEmpty()) { AndroidUtilities.updateViewVisibilityAnimated(progressView, true, 0.3f, true); chatListView.setEmptyView(null); } else { AndroidUtilities.updateViewVisibilityAnimated(progressView, false, 0.3f, true); chatListView.setEmptyView(emptyViewContainer); } chatListView.setAnimateEmptyView(true, RecyclerListView.EMPTY_VIEW_ANIMATION_TYPE_ALPHA_SCALE); undoView = new UndoView(context); undoView.setAdditionalTranslationY(AndroidUtilities.dp(51)); contentView.addView(undoView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 8, 0, 8, 8)); updateEmptyPlaceholder(); return fragmentView; } private ActionBarPopupWindow scrimPopupWindow; private int scrimPopupX, scrimPopupY; private void closeMenu() { if (scrimPopupWindow != null) { scrimPopupWindow.dismiss(); } } private final static int OPTION_COPY = 3; private final static int OPTION_SAVE_TO_GALLERY = 4; private final static int OPTION_APPLY_FILE = 5; private final static int OPTION_SHARE = 6; private final static int OPTION_SAVE_TO_GALLERY2 = 7; private final static int OPTION_SAVE_STICKER = 9; private final static int OPTION_SAVE_TO_DOWNLOADS_OR_MUSIC = 10; private final static int OPTION_SAVE_TO_GIFS = 11; private final static int OPTION_ADD_CONTACT = 15; private final static int OPTION_COPY_PHONE = 16; private final static int OPTION_CALL = 17; private final static int OPTION_RESTRICT = 33; private final static int OPTION_REPORT_FALSE_POSITIVE = 34; private boolean createMenu(View v) { return createMenu(v, 0, 0); } private boolean createMenu(View v, float x, float y) { MessageObject message = null; if (v instanceof ChatMessageCell) { message = ((ChatMessageCell) v).getMessageObject(); } else if (v instanceof ChatActionCell) { message = ((ChatActionCell) v).getMessageObject(); } if (message == null) { return false; } final int type = getMessageType(message); selectedObject = message; if (getParentActivity() == null) { return false; } ArrayList<CharSequence> items = new ArrayList<>(); final ArrayList<Integer> options = new ArrayList<>(); final ArrayList<Integer> icons = new ArrayList<>(); if (message.currentEvent != null && (message.currentEvent.action instanceof TLRPC.TL_channelAdminLogEventActionDeleteMessage && message.currentEvent.user_id == getMessagesController().telegramAntispamUserId || message.currentEvent.action instanceof TLRPC.TL_channelAdminLogEventActionToggleAntiSpam)) { if (v instanceof ChatActionCell) { SpannableString arrow = new SpannableString(">"); Drawable arrowDrawable = getContext().getResources().getDrawable(R.drawable.attach_arrow_right).mutate(); arrowDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_undo_cancelColor), PorterDuff.Mode.MULTIPLY)); arrowDrawable.setBounds(0, 0, AndroidUtilities.dp(10), AndroidUtilities.dp(10)); arrow.setSpan(new ImageSpan(arrowDrawable, DynamicDrawableSpan.ALIGN_CENTER), 0, arrow.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); SpannableStringBuilder link = new SpannableStringBuilder(); link .append(LocaleController.getString("EventLogFilterGroupInfo", R.string.EventLogFilterGroupInfo)) .append(" ") .append(arrow) .append(" ") .append(LocaleController.getString("ChannelAdministrators", R.string.ChannelAdministrators)); link.setSpan(new ClickableSpan() { @Override public void onClick(@NonNull View view) { finishFragment(); } @Override public void updateDrawState(@NonNull TextPaint ds) { super.updateDrawState(ds); ds.setUnderlineText(false); } }, 0, link.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); CharSequence text = LocaleController.getString("ChannelAntiSpamInfo2", R.string.ChannelAntiSpamInfo2); text = AndroidUtilities.replaceCharSequence("%s", text, link); Bulletin bulletin = BulletinFactory.of(this).createSimpleBulletin(R.raw.msg_antispam, LocaleController.getString("ChannelAntiSpamUser", R.string.ChannelAntiSpamUser), text); bulletin.setDuration(Bulletin.DURATION_PROLONG); bulletin.show(); return true; } items.add(LocaleController.getString("ReportFalsePositive", R.string.ReportFalsePositive)); icons.add(R.drawable.msg_notspam); options.add(OPTION_REPORT_FALSE_POSITIVE); items.add(null); icons.add(null); options.add(null); } if (selectedObject.type == MessageObject.TYPE_TEXT || selectedObject.caption != null) { items.add(LocaleController.getString("Copy", R.string.Copy)); icons.add(R.drawable.msg_copy); options.add(OPTION_COPY); } if (type == 1) { if (selectedObject.currentEvent != null && selectedObject.currentEvent.action instanceof TLRPC.TL_channelAdminLogEventActionChangeStickerSet) { TLRPC.TL_channelAdminLogEventActionChangeStickerSet action = (TLRPC.TL_channelAdminLogEventActionChangeStickerSet) selectedObject.currentEvent.action; TLRPC.InputStickerSet stickerSet = action.new_stickerset; if (stickerSet == null || stickerSet instanceof TLRPC.TL_inputStickerSetEmpty) { stickerSet = action.prev_stickerset; } if (stickerSet != null) { showDialog(new StickersAlert(getParentActivity(), ChannelAdminLogActivity.this, stickerSet, null, null)); return true; } } else if (selectedObject.currentEvent != null && selectedObject.currentEvent.action instanceof TLRPC.TL_channelAdminLogEventActionChangeHistoryTTL) { if (ChatObject.canUserDoAdminAction(currentChat, ChatObject.ACTION_DELETE_MESSAGES)) { ClearHistoryAlert alert = new ClearHistoryAlert(getParentActivity(), null, currentChat, false, null); alert.setDelegate(new ClearHistoryAlert.ClearHistoryAlertDelegate() { @Override public void onAutoDeleteHistory(int ttl, int action) { getMessagesController().setDialogHistoryTTL(-currentChat.id, ttl); TLRPC.ChatFull chatInfo = getMessagesController().getChatFull(currentChat.id); if (chatInfo != null) { undoView.showWithAction(-currentChat.id, action, null, chatInfo.ttl_period, null, null); } } }); showDialog(alert); } } } else if (type == 3) { if (selectedObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage && MessageObject.isNewGifDocument(selectedObject.messageOwner.media.webpage.document)) { items.add(LocaleController.getString("SaveToGIFs", R.string.SaveToGIFs)); icons.add(R.drawable.msg_gif); options.add(OPTION_SAVE_TO_GIFS); } } else if (type == 4) { if (selectedObject.isVideo()) { items.add(LocaleController.getString("SaveToGallery", R.string.SaveToGallery)); icons.add(R.drawable.msg_gallery); options.add(OPTION_SAVE_TO_GALLERY); items.add(LocaleController.getString("ShareFile", R.string.ShareFile)); icons.add(R.drawable.msg_share); options.add(OPTION_SHARE); } else if (selectedObject.isMusic()) { items.add(LocaleController.getString("SaveToMusic", R.string.SaveToMusic)); icons.add(R.drawable.msg_download); options.add(OPTION_SAVE_TO_DOWNLOADS_OR_MUSIC); items.add(LocaleController.getString("ShareFile", R.string.ShareFile)); icons.add(R.drawable.msg_share); options.add(OPTION_SHARE); } else if (selectedObject.getDocument() != null) { if (MessageObject.isNewGifDocument(selectedObject.getDocument())) { items.add(LocaleController.getString("SaveToGIFs", R.string.SaveToGIFs)); icons.add(R.drawable.msg_gif); options.add(OPTION_SAVE_TO_GIFS); } items.add(LocaleController.getString("SaveToDownloads", R.string.SaveToDownloads)); icons.add(R.drawable.msg_download); options.add(OPTION_SAVE_TO_DOWNLOADS_OR_MUSIC); items.add(LocaleController.getString("ShareFile", R.string.ShareFile)); icons.add(R.drawable.msg_share); options.add(OPTION_SHARE); } else { items.add(LocaleController.getString("SaveToGallery", R.string.SaveToGallery)); icons.add(R.drawable.msg_gallery); options.add(OPTION_SAVE_TO_GALLERY); } } else if (type == 5) { items.add(LocaleController.getString("ApplyLocalizationFile", R.string.ApplyLocalizationFile)); icons.add(R.drawable.msg_language); options.add(OPTION_APPLY_FILE); items.add(LocaleController.getString("SaveToDownloads", R.string.SaveToDownloads)); icons.add(R.drawable.msg_download); options.add(OPTION_SAVE_TO_DOWNLOADS_OR_MUSIC); items.add(LocaleController.getString("ShareFile", R.string.ShareFile)); icons.add(R.drawable.msg_share); options.add(OPTION_SHARE); } else if (type == 10) { items.add(LocaleController.getString("ApplyThemeFile", R.string.ApplyThemeFile)); icons.add(R.drawable.msg_theme); options.add(OPTION_APPLY_FILE); items.add(LocaleController.getString("SaveToDownloads", R.string.SaveToDownloads)); icons.add(R.drawable.msg_download); options.add(OPTION_SAVE_TO_DOWNLOADS_OR_MUSIC); items.add(LocaleController.getString("ShareFile", R.string.ShareFile)); icons.add(R.drawable.msg_share); options.add(OPTION_SHARE); } else if (type == 6) { items.add(LocaleController.getString("SaveToGallery", R.string.SaveToGallery)); icons.add(R.drawable.msg_gallery); options.add(OPTION_SAVE_TO_GALLERY2); items.add(LocaleController.getString("SaveToDownloads", R.string.SaveToDownloads)); icons.add(R.drawable.msg_download); options.add(OPTION_SAVE_TO_DOWNLOADS_OR_MUSIC); items.add(LocaleController.getString("ShareFile", R.string.ShareFile)); icons.add(R.drawable.msg_share); options.add(OPTION_SHARE); } else if (type == 7) { if (selectedObject.isMask()) { items.add(LocaleController.getString("AddToMasks", R.string.AddToMasks)); } else { items.add(LocaleController.getString("AddToStickers", R.string.AddToStickers)); } icons.add(R.drawable.msg_sticker); options.add(OPTION_SAVE_STICKER); } else if (type == 8) { long uid = selectedObject.messageOwner.media.user_id; TLRPC.User user = null; if (uid != 0) { user = MessagesController.getInstance(currentAccount).getUser(uid); } if (user != null && user.id != UserConfig.getInstance(currentAccount).getClientUserId() && ContactsController.getInstance(currentAccount).contactsDict.get(user.id) == null) { items.add(LocaleController.getString("AddContactTitle", R.string.AddContactTitle)); icons.add(R.drawable.msg_addcontact); options.add(OPTION_ADD_CONTACT); } if (!TextUtils.isEmpty(selectedObject.messageOwner.media.phone_number)) { items.add(LocaleController.getString("Copy", R.string.Copy)); icons.add(R.drawable.msg_copy); options.add(OPTION_COPY_PHONE); items.add(LocaleController.getString("Call", R.string.Call)); icons.add(R.drawable.msg_calls); options.add(OPTION_CALL); } } boolean callbackSent = false; Runnable proceed = () -> { if (options.isEmpty()) { return; } ActionBarPopupWindow.ActionBarPopupWindowLayout popupLayout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(getParentActivity(), R.drawable.popup_fixed_alert, getResourceProvider(), 0); popupLayout.setMinimumWidth(AndroidUtilities.dp(200)); Rect backgroundPaddings = new Rect(); Drawable shadowDrawable = getParentActivity().getResources().getDrawable(R.drawable.popup_fixed_alert).mutate(); shadowDrawable.getPadding(backgroundPaddings); popupLayout.setBackgroundColor(getThemedColor(Theme.key_actionBarDefaultSubmenuBackground)); for (int a = 0, N = items.size(); a < N; ++a) { if (options.get(a) == null) { popupLayout.addView(new ActionBarPopupWindow.GapView(getContext(), getResourceProvider()), LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 8)); } else { ActionBarMenuSubItem cell = new ActionBarMenuSubItem(getParentActivity(), a == 0, a == N - 1, getResourceProvider()); cell.setMinimumWidth(AndroidUtilities.dp(200)); cell.setTextAndIcon(items.get(a), icons.get(a)); final Integer option = options.get(a); popupLayout.addView(cell); final int i = a; cell.setOnClickListener(v1 -> { if (selectedObject == null || i >= options.size()) { return; } processSelectedOption(option); }); } } ChatScrimPopupContainerLayout scrimPopupContainerLayout = new ChatScrimPopupContainerLayout(contentView.getContext()) { @Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { closeMenu(); } return super.dispatchKeyEvent(event); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { boolean b = super.dispatchTouchEvent(ev); if (ev.getAction() == MotionEvent.ACTION_DOWN && !b) { closeMenu(); } return b; } }; scrimPopupContainerLayout.addView(popupLayout, LayoutHelper.createLinearRelatively(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT, 0, 0, 0, 0)); scrimPopupContainerLayout.setPopupWindowLayout(popupLayout); scrimPopupWindow = new ActionBarPopupWindow(scrimPopupContainerLayout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT) { @Override public void dismiss() { super.dismiss(); if (scrimPopupWindow != this) { return; } Bulletin.hideVisible(); scrimPopupWindow = null; } }; scrimPopupWindow.setPauseNotifications(true); scrimPopupWindow.setDismissAnimationDuration(220); scrimPopupWindow.setOutsideTouchable(true); scrimPopupWindow.setClippingEnabled(true); scrimPopupWindow.setAnimationStyle(R.style.PopupContextAnimation); scrimPopupWindow.setFocusable(true); scrimPopupContainerLayout.measure(View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST)); scrimPopupWindow.setInputMethodMode(ActionBarPopupWindow.INPUT_METHOD_NOT_NEEDED); scrimPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING); scrimPopupWindow.getContentView().setFocusableInTouchMode(true); popupLayout.setFitItems(true); int popupX = v.getLeft() + (int) x - scrimPopupContainerLayout.getMeasuredWidth() + backgroundPaddings.left - AndroidUtilities.dp(28); if (popupX < AndroidUtilities.dp(6)) { popupX = AndroidUtilities.dp(6); } else if (popupX > chatListView.getMeasuredWidth() - AndroidUtilities.dp(6) - scrimPopupContainerLayout.getMeasuredWidth()) { popupX = chatListView.getMeasuredWidth() - AndroidUtilities.dp(6) - scrimPopupContainerLayout.getMeasuredWidth(); } if (AndroidUtilities.isTablet()) { int[] location = new int[2]; fragmentView.getLocationInWindow(location); popupX += location[0]; } int totalHeight = contentView.getHeight(); int height = scrimPopupContainerLayout.getMeasuredHeight() + AndroidUtilities.dp(48); int keyboardHeight = contentView.measureKeyboardHeight(); if (keyboardHeight > AndroidUtilities.dp(20)) { totalHeight += keyboardHeight; } int popupY; if (height < totalHeight) { popupY = (int) (chatListView.getY() + v.getTop() + y); if (height - backgroundPaddings.top - backgroundPaddings.bottom > AndroidUtilities.dp(240)) { popupY += AndroidUtilities.dp(240) - height; } if (popupY < chatListView.getY() + AndroidUtilities.dp(24)) { popupY = (int) (chatListView.getY() + AndroidUtilities.dp(24)); } else if (popupY > totalHeight - height - AndroidUtilities.dp(8)) { popupY = totalHeight - height - AndroidUtilities.dp(8); } } else { popupY = inBubbleMode ? 0 : AndroidUtilities.statusBarHeight; } final int finalPopupX = scrimPopupX = popupX; final int finalPopupY = scrimPopupY = popupY; scrimPopupContainerLayout.setMaxHeight(totalHeight - popupY); scrimPopupWindow.showAtLocation(chatListView, Gravity.LEFT | Gravity.TOP, finalPopupX, finalPopupY); scrimPopupWindow.dimBehind(); }; if ( ChatObject.canBlockUsers(currentChat) && message.currentEvent != null && message.currentEvent.action instanceof TLRPC.TL_channelAdminLogEventActionDeleteMessage && message.currentEvent.user_id == getMessagesController().telegramAntispamUserId && message.messageOwner != null && message.messageOwner.from_id != null && !UserObject.isUserSelf(getMessagesController().getUser(message.messageOwner.from_id.user_id)) ) { TLRPC.User user = getMessagesController().getUser(selectedObject.messageOwner.from_id.user_id); if (user != null) { callbackSent = true; getMessagesController().checkIsInChat(true, currentChat, user, (isInChat, rights, rank) -> { if (isInChat) { items.add(LocaleController.getString("BanUser", R.string.BanUser)); icons.add(R.drawable.msg_block2); options.add(OPTION_RESTRICT); } AndroidUtilities.runOnUIThread(proceed); }); } } if (!callbackSent) { proceed.run(); } return true; } private CharSequence getMessageContent(MessageObject messageObject, int previousUid, boolean name) { SpannableStringBuilder str = new SpannableStringBuilder(); if (name) { long fromId = messageObject.getFromChatId(); if (previousUid != fromId) { if (fromId > 0) { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(fromId); if (user != null) { str.append(ContactsController.formatName(user.first_name, user.last_name)).append(":\n"); } } else if (fromId < 0) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-fromId); if (chat != null) { str.append(chat.title).append(":\n"); } } } } if (TextUtils.isEmpty(messageObject.messageText)) { str.append(messageObject.messageOwner.message); } else { str.append(messageObject.messageText); } return str; } private TextureView createTextureView(boolean add) { if (parentLayout == null) { return null; } if (roundVideoContainer == null) { if (Build.VERSION.SDK_INT >= 21) { roundVideoContainer = new FrameLayout(getParentActivity()) { @Override public void setTranslationY(float translationY) { super.setTranslationY(translationY); contentView.invalidate(); } }; roundVideoContainer.setOutlineProvider(new ViewOutlineProvider() { @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void getOutline(View view, Outline outline) { outline.setOval(0, 0, AndroidUtilities.roundMessageSize, AndroidUtilities.roundMessageSize); } }); roundVideoContainer.setClipToOutline(true); } else { roundVideoContainer = new FrameLayout(getParentActivity()) { @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); aspectPath.reset(); aspectPath.addCircle(w / 2, h / 2, w / 2, Path.Direction.CW); aspectPath.toggleInverseFillType(); } @Override public void setTranslationY(float translationY) { super.setTranslationY(translationY); contentView.invalidate(); } @Override public void setVisibility(int visibility) { super.setVisibility(visibility); if (visibility == VISIBLE) { setLayerType(View.LAYER_TYPE_HARDWARE, null); } } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); canvas.drawPath(aspectPath, aspectPaint); } }; aspectPath = new Path(); aspectPaint = new Paint(Paint.ANTI_ALIAS_FLAG); aspectPaint.setColor(0xff000000); aspectPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); } roundVideoContainer.setWillNotDraw(false); roundVideoContainer.setVisibility(View.INVISIBLE); aspectRatioFrameLayout = new AspectRatioFrameLayout(getParentActivity()); aspectRatioFrameLayout.setBackgroundColor(0); if (add) { roundVideoContainer.addView(aspectRatioFrameLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); } videoTextureView = new TextureView(getParentActivity()); videoTextureView.setOpaque(false); aspectRatioFrameLayout.addView(videoTextureView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); } if (roundVideoContainer.getParent() == null) { contentView.addView(roundVideoContainer, 1, new FrameLayout.LayoutParams(AndroidUtilities.roundMessageSize, AndroidUtilities.roundMessageSize)); } roundVideoContainer.setVisibility(View.INVISIBLE); aspectRatioFrameLayout.setDrawingReady(false); return videoTextureView; } private void destroyTextureView() { if (roundVideoContainer == null || roundVideoContainer.getParent() == null) { return; } contentView.removeView(roundVideoContainer); aspectRatioFrameLayout.setDrawingReady(false); roundVideoContainer.setVisibility(View.INVISIBLE); if (Build.VERSION.SDK_INT < 21) { roundVideoContainer.setLayerType(View.LAYER_TYPE_NONE, null); } } private void processSelectedOption(int option) { closeMenu(); if (selectedObject == null) { return; } switch (option) { case OPTION_COPY: { AndroidUtilities.addToClipboard(getMessageContent(selectedObject, 0, true)); BulletinFactory.of(ChannelAdminLogActivity.this).createCopyBulletin(LocaleController.getString("MessageCopied", R.string.MessageCopied)).show(); break; } case OPTION_SAVE_TO_GALLERY: { String path = selectedObject.messageOwner.attachPath; if (path != null && path.length() > 0) { File temp = new File(path); if (!temp.exists()) { path = null; } } if (path == null || path.length() == 0) { path = getFileLoader().getPathToMessage(selectedObject.messageOwner).toString(); } if (selectedObject.type == MessageObject.TYPE_VIDEO || selectedObject.type == MessageObject.TYPE_PHOTO) { if (Build.VERSION.SDK_INT >= 23 && (Build.VERSION.SDK_INT <= 28 || BuildVars.NO_SCOPED_STORAGE) && getParentActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { getParentActivity().requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 4); selectedObject = null; return; } MediaController.saveFile(path, getParentActivity(), selectedObject.type == MessageObject.TYPE_VIDEO ? 1 : 0, null, null); } break; } case OPTION_APPLY_FILE: { File locFile = null; if (selectedObject.messageOwner.attachPath != null && selectedObject.messageOwner.attachPath.length() != 0) { File f = new File(selectedObject.messageOwner.attachPath); if (f.exists()) { locFile = f; } } if (locFile == null) { File f = getFileLoader().getPathToMessage(selectedObject.messageOwner); if (f.exists()) { locFile = f; } } if (locFile != null) { if (locFile.getName().toLowerCase().endsWith("attheme")) { if (chatLayoutManager != null) { int lastPosition = chatLayoutManager.findLastVisibleItemPosition(); if (lastPosition < chatLayoutManager.getItemCount() - 1) { scrollToPositionOnRecreate = chatLayoutManager.findFirstVisibleItemPosition(); RecyclerListView.Holder holder = (RecyclerListView.Holder) chatListView.findViewHolderForAdapterPosition(scrollToPositionOnRecreate); if (holder != null) { scrollToOffsetOnRecreate = holder.itemView.getTop(); } else { scrollToPositionOnRecreate = -1; } } else { scrollToPositionOnRecreate = -1; } } Theme.ThemeInfo themeInfo = Theme.applyThemeFile(locFile, selectedObject.getDocumentName(), null, true); if (themeInfo != null) { presentFragment(new ThemePreviewActivity(themeInfo)); } else { scrollToPositionOnRecreate = -1; if (getParentActivity() == null) { selectedObject = null; return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setMessage(LocaleController.getString("IncorrectTheme", R.string.IncorrectTheme)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); showDialog(builder.create()); } } else { if (LocaleController.getInstance().applyLanguageFile(locFile, currentAccount)) { presentFragment(new LanguageSelectActivity()); } else { if (getParentActivity() == null) { selectedObject = null; return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setMessage(LocaleController.getString("IncorrectLocalization", R.string.IncorrectLocalization)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); showDialog(builder.create()); } } } break; } case OPTION_SHARE: { String path = selectedObject.messageOwner.attachPath; if (path != null && path.length() > 0) { File temp = new File(path); if (!temp.exists()) { path = null; } } if (path == null || path.length() == 0) { path = getFileLoader().getPathToMessage(selectedObject.messageOwner).toString(); } Intent intent = new Intent(Intent.ACTION_SEND); intent.setType(selectedObject.getDocument().mime_type); if (Build.VERSION.SDK_INT >= 24) { try { intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(getParentActivity(), ApplicationLoader.getApplicationId() + ".provider", new File(path))); intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } catch (Exception ignore) { intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(path))); } } else { intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(path))); } try { getParentActivity().startActivityForResult(Intent.createChooser(intent, LocaleController.getString("ShareFile", R.string.ShareFile)), 500); } catch (Exception e) { } break; } case OPTION_SAVE_TO_GALLERY2: { String path = selectedObject.messageOwner.attachPath; if (path != null && path.length() > 0) { File temp = new File(path); if (!temp.exists()) { path = null; } } if (path == null || path.length() == 0) { path = getFileLoader().getPathToMessage(selectedObject.messageOwner).toString(); } if (Build.VERSION.SDK_INT >= 23 && (Build.VERSION.SDK_INT <= 28 || BuildVars.NO_SCOPED_STORAGE) && getParentActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { getParentActivity().requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 4); selectedObject = null; return; } MediaController.saveFile(path, getParentActivity(), 0, null, null); break; } case OPTION_SAVE_STICKER: { showDialog(new StickersAlert(getParentActivity(), this, selectedObject.getInputStickerSet(), null, null)); break; } case OPTION_SAVE_TO_DOWNLOADS_OR_MUSIC: { if (Build.VERSION.SDK_INT >= 23 && (Build.VERSION.SDK_INT <= 28 || BuildVars.NO_SCOPED_STORAGE) && getParentActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { getParentActivity().requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 4); selectedObject = null; return; } String fileName = FileLoader.getDocumentFileName(selectedObject.getDocument()); if (TextUtils.isEmpty(fileName)) { fileName = selectedObject.getFileName(); } String path = selectedObject.messageOwner.attachPath; if (path != null && path.length() > 0) { File temp = new File(path); if (!temp.exists()) { path = null; } } if (path == null || path.length() == 0) { path = getFileLoader().getPathToMessage(selectedObject.messageOwner).toString(); } MediaController.saveFile(path, getParentActivity(), selectedObject.isMusic() ? 3 : 2, fileName, selectedObject.getDocument() != null ? selectedObject.getDocument().mime_type : ""); break; } case OPTION_SAVE_TO_GIFS: { TLRPC.Document document = selectedObject.getDocument(); MessagesController.getInstance(currentAccount).saveGif(selectedObject, document); break; } case OPTION_ADD_CONTACT: { Bundle args = new Bundle(); args.putLong("user_id", selectedObject.messageOwner.media.user_id); args.putString("phone", selectedObject.messageOwner.media.phone_number); args.putBoolean("addContact", true); presentFragment(new ContactAddActivity(args)); break; } case OPTION_COPY_PHONE: { AndroidUtilities.addToClipboard(selectedObject.messageOwner.media.phone_number); BulletinFactory.of(ChannelAdminLogActivity.this).createCopyBulletin(LocaleController.getString("PhoneCopied", R.string.PhoneCopied)).show(); break; } case OPTION_CALL: { try { Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + selectedObject.messageOwner.media.phone_number)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getParentActivity().startActivityForResult(intent, 500); } catch (Exception e) { FileLog.e(e); } break; } case OPTION_REPORT_FALSE_POSITIVE: { TLRPC.TL_channels_reportAntiSpamFalsePositive req = new TLRPC.TL_channels_reportAntiSpamFalsePositive(); req.channel = getMessagesController().getInputChannel(currentChat.id); req.msg_id = selectedObject.getRealId(); getConnectionsManager().sendRequest(req, (res, err) -> { AndroidUtilities.runOnUIThread(() -> { if (res instanceof TLRPC.TL_boolTrue) { BulletinFactory.of(this).createSimpleBulletin(R.raw.msg_antispam, LocaleController.getString("ChannelAntiSpamFalsePositiveReported", R.string.ChannelAntiSpamFalsePositiveReported)).show(); } else if (res instanceof TLRPC.TL_boolFalse) { BulletinFactory.of(this).createSimpleBulletin(R.raw.error, LocaleController.getString("UnknownError", R.string.UnknownError)).show(); } else { BulletinFactory.of(this).createSimpleBulletin(R.raw.error, LocaleController.getString("UnknownError", R.string.UnknownError)).show(); } }); }); break; } case OPTION_RESTRICT: { getMessagesController().deleteParticipantFromChat(currentChat.id, getMessagesController().getInputPeer(selectedObject.messageOwner.from_id)); if (currentChat != null && selectedObject.messageOwner.from_id instanceof TLRPC.TL_peerUser && BulletinFactory.canShowBulletin(this)) { TLRPC.User user = getMessagesController().getUser(selectedObject.messageOwner.from_id.user_id); if (user != null) { BulletinFactory.createRemoveFromChatBulletin(this, user, currentChat.title).show(); } } break; } } selectedObject = null; } private int getMessageType(MessageObject messageObject) { if (messageObject == null) { return -1; } if (messageObject.type == 6) { return -1; } else if (messageObject.type == 10 || messageObject.type == MessageObject.TYPE_ACTION_PHOTO || messageObject.type == MessageObject.TYPE_PHONE_CALL) { if (messageObject.getId() == 0) { return -1; } return 1; } else { if (messageObject.isVoice()) { return 2; } else if (messageObject.isSticker() || messageObject.isAnimatedSticker()) { TLRPC.InputStickerSet inputStickerSet = messageObject.getInputStickerSet(); if (inputStickerSet instanceof TLRPC.TL_inputStickerSetID) { if (!MediaDataController.getInstance(currentAccount).isStickerPackInstalled(inputStickerSet.id)) { return 7; } } else if (inputStickerSet instanceof TLRPC.TL_inputStickerSetShortName) { if (!MediaDataController.getInstance(currentAccount).isStickerPackInstalled(inputStickerSet.short_name)) { return 7; } } } else if ((!messageObject.isRoundVideo() || messageObject.isRoundVideo() && BuildVars.DEBUG_VERSION) && (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto || messageObject.getDocument() != null || messageObject.isMusic() || messageObject.isVideo())) { boolean canSave = false; if (messageObject.messageOwner.attachPath != null && messageObject.messageOwner.attachPath.length() != 0) { File f = new File(messageObject.messageOwner.attachPath); if (f.exists()) { canSave = true; } } if (!canSave) { File f = getFileLoader().getPathToMessage(messageObject.messageOwner); if (f.exists()) { canSave = true; } } if (canSave) { if (messageObject.getDocument() != null) { String mime = messageObject.getDocument().mime_type; if (mime != null) { if (messageObject.getDocumentName().toLowerCase().endsWith("attheme")) { return 10; } else if (mime.endsWith("/xml")) { return 5; } else if (mime.endsWith("/png") || mime.endsWith("/jpg") || mime.endsWith("/jpeg")) { return 6; } } } return 4; } } else if (messageObject.type == MessageObject.TYPE_CONTACT) { return 8; } else if (messageObject.isMediaEmpty()) { return 3; } return 2; } } private void loadAdmins() { TLRPC.TL_channels_getParticipants req = new TLRPC.TL_channels_getParticipants(); req.channel = MessagesController.getInputChannel(currentChat); req.filter = new TLRPC.TL_channelParticipantsAdmins(); req.offset = 0; req.limit = 200; int reqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { if (error == null) { TLRPC.TL_channels_channelParticipants res = (TLRPC.TL_channels_channelParticipants) response; getMessagesController().putUsers(res.users, false); getMessagesController().putChats(res.chats, false); admins = res.participants; if (currentChat != null) { TLRPC.ChatFull chatFull = getMessagesController().getChatFull(currentChat.id); if (chatFull != null && chatFull.antispam) { TLRPC.ChannelParticipant antispamParticipant = new TLRPC.ChannelParticipant() {}; antispamParticipant.user_id = getMessagesController().telegramAntispamUserId; antispamParticipant.peer = getMessagesController().getPeer(antispamParticipant.user_id); loadAntispamUser(getMessagesController().telegramAntispamUserId); admins.add(0, antispamParticipant); } } if (visibleDialog instanceof AdminLogFilterAlert) { ((AdminLogFilterAlert) visibleDialog).setCurrentAdmins(admins); } } })); ConnectionsManager.getInstance(currentAccount).bindRequestToGuid(reqId, classGuid); } private void loadAntispamUser(long userId) { if (getMessagesController().getUser(userId) != null) { return; } TLRPC.TL_users_getUsers req = new TLRPC.TL_users_getUsers(); TLRPC.TL_inputUser inputUser = new TLRPC.TL_inputUser(); inputUser.user_id = userId; req.id.add(inputUser); ConnectionsManager.getInstance(currentAccount).sendRequest(req, (res, err) -> { if (res instanceof TLRPC.Vector) { ArrayList<Object> objects = ((TLRPC.Vector) res).objects; ArrayList<TLRPC.User> users = new ArrayList<>(); for (int i = 0; i < objects.size(); ++i) { if (objects.get(i) instanceof TLRPC.User) { users.add((TLRPC.User) objects.get(i)); } } getMessagesController().putUsers(users, false); } }); } @Override public void onRemoveFromParent() { MediaController.getInstance().setTextureView(videoTextureView, null, null, false); } private void hideFloatingDateView(boolean animated) { if (floatingDateView.getTag() != null && !currentFloatingDateOnScreen && (!scrollingFloatingDate || currentFloatingTopIsNotMessage)) { floatingDateView.setTag(null); if (animated) { floatingDateAnimation = new AnimatorSet(); floatingDateAnimation.setDuration(150); floatingDateAnimation.playTogether(ObjectAnimator.ofFloat(floatingDateView, "alpha", 0.0f)); floatingDateAnimation.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (animation.equals(floatingDateAnimation)) { floatingDateAnimation = null; } } }); floatingDateAnimation.setStartDelay(500); floatingDateAnimation.start(); } else { if (floatingDateAnimation != null) { floatingDateAnimation.cancel(); floatingDateAnimation = null; } floatingDateView.setAlpha(0.0f); } } } private void checkScrollForLoad(boolean scroll) { if (chatLayoutManager == null || paused) { return; } int firstVisibleItem = chatLayoutManager.findFirstVisibleItemPosition(); int visibleItemCount = firstVisibleItem == RecyclerView.NO_POSITION ? 0 : Math.abs(chatLayoutManager.findLastVisibleItemPosition() - firstVisibleItem) + 1; if (visibleItemCount > 0) { int totalItemCount = chatAdapter.getItemCount(); int checkLoadCount; if (scroll) { checkLoadCount = 25; } else { checkLoadCount = 5; } if (firstVisibleItem <= checkLoadCount && !loading && !endReached) { loadMessages(false); } } } private void moveScrollToLastMessage() { if (chatListView != null && !messages.isEmpty()) { chatLayoutManager.scrollToPositionWithOffset(messages.size() - 1, -100000 - chatListView.getPaddingTop()); } } private void updateTextureViewPosition() { boolean foundTextureViewMessage = false; int count = chatListView.getChildCount(); for (int a = 0; a < count; a++) { View view = chatListView.getChildAt(a); if (view instanceof ChatMessageCell) { ChatMessageCell messageCell = (ChatMessageCell) view; MessageObject messageObject = messageCell.getMessageObject(); if (roundVideoContainer != null && messageObject.isRoundVideo() && MediaController.getInstance().isPlayingMessage(messageObject)) { ImageReceiver imageReceiver = messageCell.getPhotoImage(); roundVideoContainer.setTranslationX(imageReceiver.getImageX()); roundVideoContainer.setTranslationY(fragmentView.getPaddingTop() + messageCell.getTop() + imageReceiver.getImageY()); fragmentView.invalidate(); roundVideoContainer.invalidate(); foundTextureViewMessage = true; break; } } } if (roundVideoContainer != null) { MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject(); if (!foundTextureViewMessage) { roundVideoContainer.setTranslationY(-AndroidUtilities.roundMessageSize - 100); fragmentView.invalidate(); if (messageObject != null && messageObject.isRoundVideo()) { if (checkTextureViewPosition || PipRoundVideoView.getInstance() != null) { MediaController.getInstance().setCurrentVideoVisible(false); } } } else { MediaController.getInstance().setCurrentVideoVisible(true); } } } private void updateMessagesVisiblePart() { if (chatListView == null) { return; } int count = chatListView.getChildCount(); int height = chatListView.getMeasuredHeight(); int minPositionHolder = Integer.MAX_VALUE; int minPositionDateHolder = Integer.MAX_VALUE; View minDateChild = null; View minChild = null; View minMessageChild = null; boolean foundTextureViewMessage = false; for (int a = 0; a < count; a++) { View view = chatListView.getChildAt(a); if (view instanceof ChatMessageCell) { ChatMessageCell messageCell = (ChatMessageCell) view; int top = messageCell.getTop(); int bottom = messageCell.getBottom(); int viewTop = top >= 0 ? 0 : -top; int viewBottom = messageCell.getMeasuredHeight(); if (viewBottom > height) { viewBottom = viewTop + height; } messageCell.setVisiblePart(viewTop, viewBottom - viewTop, contentView.getHeightWithKeyboard() - AndroidUtilities.dp(48) - chatListView.getTop(), 0, view.getY() + actionBar.getMeasuredHeight() - contentView.getBackgroundTranslationY(), contentView.getMeasuredWidth(), contentView.getBackgroundSizeY(), 0, 0); MessageObject messageObject = messageCell.getMessageObject(); if (roundVideoContainer != null && messageObject.isRoundVideo() && MediaController.getInstance().isPlayingMessage(messageObject)) { ImageReceiver imageReceiver = messageCell.getPhotoImage(); roundVideoContainer.setTranslationX(imageReceiver.getImageX()); roundVideoContainer.setTranslationY(fragmentView.getPaddingTop() + top + imageReceiver.getImageY()); fragmentView.invalidate(); roundVideoContainer.invalidate(); foundTextureViewMessage = true; } } else if (view instanceof ChatActionCell) { ChatActionCell cell = (ChatActionCell) view; cell.setVisiblePart(view.getY() + actionBar.getMeasuredHeight() - contentView.getBackgroundTranslationY(), contentView.getBackgroundSizeY()); } if (view.getBottom() <= chatListView.getPaddingTop()) { continue; } int position = view.getBottom(); if (position < minPositionHolder) { minPositionHolder = position; if (view instanceof ChatMessageCell || view instanceof ChatActionCell) { minMessageChild = view; } minChild = view; } if (chatListItemAnimator == null || (!chatListItemAnimator.willRemoved(view) && !chatListItemAnimator.willAddedFromAlpha(view))) { if (view instanceof ChatActionCell && ((ChatActionCell) view).getMessageObject().isDateObject) { if (view.getAlpha() != 1.0f) { view.setAlpha(1.0f); } if (position < minPositionDateHolder) { minPositionDateHolder = position; minDateChild = view; } } } } if (roundVideoContainer != null) { if (!foundTextureViewMessage) { roundVideoContainer.setTranslationY(-AndroidUtilities.roundMessageSize - 100); fragmentView.invalidate(); MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject(); if (messageObject != null && messageObject.isRoundVideo() && checkTextureViewPosition) { MediaController.getInstance().setCurrentVideoVisible(false); } } else { MediaController.getInstance().setCurrentVideoVisible(true); } } if (minMessageChild != null) { MessageObject messageObject; if (minMessageChild instanceof ChatMessageCell) { messageObject = ((ChatMessageCell) minMessageChild).getMessageObject(); } else { messageObject = ((ChatActionCell) minMessageChild).getMessageObject(); } floatingDateView.setCustomDate(messageObject.messageOwner.date, false, true); } currentFloatingDateOnScreen = false; currentFloatingTopIsNotMessage = !(minChild instanceof ChatMessageCell || minChild instanceof ChatActionCell); if (minDateChild != null) { if (minDateChild.getTop() > chatListView.getPaddingTop() || currentFloatingTopIsNotMessage) { if (minDateChild.getAlpha() != 1.0f) { minDateChild.setAlpha(1.0f); } hideFloatingDateView(!currentFloatingTopIsNotMessage); } else { if (minDateChild.getAlpha() != 0.0f) { minDateChild.setAlpha(0.0f); } if (floatingDateAnimation != null) { floatingDateAnimation.cancel(); floatingDateAnimation = null; } if (floatingDateView.getTag() == null) { floatingDateView.setTag(1); } if (floatingDateView.getAlpha() != 1.0f) { floatingDateView.setAlpha(1.0f); } currentFloatingDateOnScreen = true; } int offset = minDateChild.getBottom() - chatListView.getPaddingTop(); if (offset > floatingDateView.getMeasuredHeight() && offset < floatingDateView.getMeasuredHeight() * 2) { floatingDateView.setTranslationY(-floatingDateView.getMeasuredHeight() * 2 + offset); } else { floatingDateView.setTranslationY(0); } } else { hideFloatingDateView(true); floatingDateView.setTranslationY(0); } } @Override public void onTransitionAnimationStart(boolean isOpen, boolean backward) { if (isOpen) { allowAnimationIndex = getNotificationCenter().setAnimationInProgress(allowAnimationIndex, new int[]{NotificationCenter.chatInfoDidLoad, NotificationCenter.dialogsNeedReload, NotificationCenter.closeChats, NotificationCenter.messagesDidLoad, NotificationCenter.botKeyboardDidLoad/*, NotificationCenter.botInfoDidLoad*/}); openAnimationEnded = false; } } @Override public void onTransitionAnimationEnd(boolean isOpen, boolean backward) { if (isOpen) { getNotificationCenter().onAnimationFinish(allowAnimationIndex); openAnimationEnded = true; } } @Override public void onResume() { super.onResume(); if (contentView != null) { contentView.onResume(); } paused = false; checkScrollForLoad(false); if (wasPaused) { wasPaused = false; if (chatAdapter != null) { chatAdapter.notifyDataSetChanged(); } } } @Override public void onPause() { super.onPause(); if (contentView != null) { contentView.onPause(); } if (undoView != null) { undoView.hide(true, 0); } paused = true; wasPaused = true; if (AvatarPreviewer.hasVisibleInstance()) { AvatarPreviewer.getInstance().close(); } } @Override public void onBecomeFullyHidden() { if (undoView != null) { undoView.hide(true, 0); } } public void openVCard(TLRPC.User user, String vcard, String first_name, String last_name) { try { File f = AndroidUtilities.getSharingDirectory(); f.mkdirs(); f = new File(f, "vcard.vcf"); BufferedWriter writer = new BufferedWriter(new FileWriter(f)); writer.write(vcard); writer.close(); showDialog(new PhonebookShareAlert(this, null, user, null, f, first_name, last_name)); } catch (Exception e) { FileLog.e(e); } } @Override public void onConfigurationChanged(android.content.res.Configuration newConfig) { if (visibleDialog instanceof DatePickerDialog) { visibleDialog.dismiss(); } } private void alertUserOpenError(MessageObject message) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); if (message.type == MessageObject.TYPE_VIDEO) { builder.setMessage(LocaleController.getString("NoPlayerInstalled", R.string.NoPlayerInstalled)); } else { builder.setMessage(LocaleController.formatString("NoHandleAppInstalled", R.string.NoHandleAppInstalled, message.getDocument().mime_type)); } showDialog(builder.create()); } public TLRPC.Chat getCurrentChat() { return currentChat; } private void addCanBanUser(Bundle bundle, long uid) { if (!currentChat.megagroup || admins == null || !ChatObject.canBlockUsers(currentChat)) { return; } for (int a = 0; a < admins.size(); a++) { TLRPC.ChannelParticipant channelParticipant = admins.get(a); if (MessageObject.getPeerId(channelParticipant.peer) == uid) { if (!channelParticipant.can_edit) { return; } break; } } bundle.putLong("ban_chat_id", currentChat.id); } public void showOpenUrlAlert(final String url, boolean ask) { if (Browser.isInternalUrl(url, null) || !ask) { Browser.openUrl(getParentActivity(), url, true); } else { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("OpenUrlTitle", R.string.OpenUrlTitle)); builder.setMessage(LocaleController.formatString("OpenUrlAlert2", R.string.OpenUrlAlert2, url)); builder.setPositiveButton(LocaleController.getString("Open", R.string.Open), (dialogInterface, i) -> Browser.openUrl(getParentActivity(), url, true)); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); } } private void removeMessageObject(MessageObject messageObject) { int index = messages.indexOf(messageObject); if (index == -1) { return; } messages.remove(index); if (chatAdapter != null) { chatAdapter.notifyItemRemoved(chatAdapter.messagesStartRow + messages.size() - index - 1); } } public class ChatActivityAdapter extends RecyclerView.Adapter { private Context mContext; private int rowCount; private int loadingUpRow; private int messagesStartRow; private int messagesEndRow; public ChatActivityAdapter(Context context) { mContext = context; } public void updateRows() { rowCount = 0; if (!messages.isEmpty()) { if (!endReached) { loadingUpRow = rowCount++; } else { loadingUpRow = -1; } messagesStartRow = rowCount; rowCount += messages.size(); messagesEndRow = rowCount; } else { loadingUpRow = -1; messagesStartRow = -1; messagesEndRow = -1; } } @Override public int getItemCount() { return rowCount; } @Override public long getItemId(int i) { return RecyclerListView.NO_ID; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view; if (viewType == 0) { if (!chatMessageCellsCache.isEmpty()) { view = chatMessageCellsCache.get(0); chatMessageCellsCache.remove(0); } else { view = new ChatMessageCell(mContext); } ChatMessageCell chatMessageCell = (ChatMessageCell) view; chatMessageCell.setDelegate(new ChatMessageCell.ChatMessageCellDelegate() { @Override public boolean canDrawOutboundsContent() { return true; } @Override public void didPressSideButton(ChatMessageCell cell) { if (getParentActivity() == null) { return; } showDialog(ShareAlert.createShareAlert(mContext, cell.getMessageObject(), null, ChatObject.isChannel(currentChat) && !currentChat.megagroup, null, false)); } @Override public boolean needPlayMessage(MessageObject messageObject, boolean muted) { if (messageObject.isVoice() || messageObject.isRoundVideo()) { boolean result = MediaController.getInstance().playMessage(messageObject, muted); MediaController.getInstance().setVoiceMessagesPlaylist(null, false); return result; } else if (messageObject.isMusic()) { return MediaController.getInstance().setPlaylist(messages, messageObject, 0); } return false; } @Override public void didPressChannelAvatar(ChatMessageCell cell, TLRPC.Chat chat, int postId, float touchX, float touchY) { if (chat != null && chat != currentChat) { Bundle args = new Bundle(); args.putLong("chat_id", chat.id); if (postId != 0) { args.putInt("message_id", postId); } if (MessagesController.getInstance(currentAccount).checkCanOpenChat(args, ChannelAdminLogActivity.this)) { presentFragment(new ChatActivity(args), true); } } } @Override public void didPressOther(ChatMessageCell cell, float x, float y) { createMenu(cell); } @Override public void didPressUserAvatar(ChatMessageCell cell, TLRPC.User user, float touchX, float touchY) { if (user != null && user.id != UserConfig.getInstance(currentAccount).getClientUserId()) { openProfile(user); } } @Override public boolean didLongPressUserAvatar(ChatMessageCell cell, TLRPC.User user, float touchX, float touchY) { if (user != null && user.id != UserConfig.getInstance(currentAccount).getClientUserId()) { final AvatarPreviewer.MenuItem[] menuItems = {AvatarPreviewer.MenuItem.OPEN_PROFILE, AvatarPreviewer.MenuItem.SEND_MESSAGE}; final TLRPC.UserFull userFull = getMessagesController().getUserFull(user.id); final AvatarPreviewer.Data data; if (userFull != null) { data = AvatarPreviewer.Data.of(userFull, menuItems); } else { data = AvatarPreviewer.Data.of(user, classGuid, menuItems); } if (AvatarPreviewer.canPreview(data)) { AvatarPreviewer.getInstance().show((ViewGroup) fragmentView, data, item -> { switch (item) { case SEND_MESSAGE: openDialog(cell, user); break; case OPEN_PROFILE: openProfile(user); break; } }); return true; } } return false; } private void openProfile(TLRPC.User user) { Bundle args = new Bundle(); args.putLong("user_id", user.id); addCanBanUser(args, user.id); ProfileActivity fragment = new ProfileActivity(args); fragment.setPlayProfileAnimation(0); presentFragment(fragment); } private void openDialog(ChatMessageCell cell, TLRPC.User user) { if (user != null) { Bundle args = new Bundle(); args.putLong("user_id", user.id); if (getMessagesController().checkCanOpenChat(args, ChannelAdminLogActivity.this)) { presentFragment(new ChatActivity(args)); } } } @Override public void didPressCancelSendButton(ChatMessageCell cell) { } @Override public void didLongPress(ChatMessageCell cell, float x, float y) { createMenu(cell); } @Override public boolean canPerformActions() { return true; } @Override public void didPressUrl(ChatMessageCell cell, final CharacterStyle url, boolean longPress) { if (url == null) { return; } MessageObject messageObject = cell.getMessageObject(); if (url instanceof URLSpanMono) { ((URLSpanMono) url).copyToClipboard(); if (AndroidUtilities.shouldShowClipboardToast()) { Toast.makeText(getParentActivity(), LocaleController.getString("TextCopied", R.string.TextCopied), Toast.LENGTH_SHORT).show(); } } else if (url instanceof URLSpanUserMention) { long peerId = Utilities.parseLong(((URLSpanUserMention) url).getURL()); if (peerId > 0) { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(peerId); if (user != null) { MessagesController.openChatOrProfileWith(user, null, ChannelAdminLogActivity.this, 0, false); } } else { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-peerId); if (chat != null) { MessagesController.openChatOrProfileWith(null, chat, ChannelAdminLogActivity.this, 0, false); } } } else if (url instanceof URLSpanNoUnderline) { String str = ((URLSpanNoUnderline) url).getURL(); if (str.startsWith("@")) { MessagesController.getInstance(currentAccount).openByUserName(str.substring(1), ChannelAdminLogActivity.this, 0); } else if (str.startsWith("#")) { DialogsActivity fragment = new DialogsActivity(null); fragment.setSearchString(str); presentFragment(fragment); } } else { final String urlFinal = ((URLSpan) url).getURL(); if (longPress) { BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity()); builder.setTitle(urlFinal); builder.setItems(new CharSequence[]{LocaleController.getString("Open", R.string.Open), LocaleController.getString("Copy", R.string.Copy)}, (dialog, which) -> { if (which == 0) { Browser.openUrl(getParentActivity(), urlFinal, true); } else if (which == 1) { String url1 = urlFinal; if (url1.startsWith("mailto:")) { url1 = url1.substring(7); } else if (url1.startsWith("tel:")) { url1 = url1.substring(4); } AndroidUtilities.addToClipboard(url1); } }); showDialog(builder.create()); } else { if (url instanceof URLSpanReplacement) { showOpenUrlAlert(((URLSpanReplacement) url).getURL(), true); } else { if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage && messageObject.messageOwner.media.webpage != null && messageObject.messageOwner.media.webpage.cached_page != null) { String lowerUrl = urlFinal.toLowerCase(); String lowerUrl2 = messageObject.messageOwner.media.webpage.url.toLowerCase(); if ((Browser.isTelegraphUrl(lowerUrl, false) || lowerUrl.contains("t.me/iv")) && (lowerUrl.contains(lowerUrl2) || lowerUrl2.contains(lowerUrl))) { ArticleViewer.getInstance().setParentActivity(getParentActivity(), ChannelAdminLogActivity.this); ArticleViewer.getInstance().open(messageObject); return; } } Browser.openUrl(getParentActivity(), urlFinal, true); } } } } @Override public void needOpenWebView(MessageObject message, String url, String title, String description, String originalUrl, int w, int h) { EmbedBottomSheet.show(ChannelAdminLogActivity.this, message, provider, title, description, originalUrl, url, w, h, false); } @Override public void didPressReplyMessage(ChatMessageCell cell, int id) { } @Override public void didPressViaBot(ChatMessageCell cell, String username) { } @Override public void didPressImage(ChatMessageCell cell, float x, float y) { MessageObject message = cell.getMessageObject(); if (message.getInputStickerSet() != null) { showDialog(new StickersAlert(getParentActivity(), ChannelAdminLogActivity.this, message.getInputStickerSet(), null, null)); } else if (message.isVideo() || message.type == MessageObject.TYPE_PHOTO || message.type == MessageObject.TYPE_TEXT && !message.isWebpageDocument() || message.isGif()) { PhotoViewer.getInstance().setParentActivity(ChannelAdminLogActivity.this); PhotoViewer.getInstance().openPhoto(message, null, 0, 0, 0, provider); } else if (message.type == MessageObject.TYPE_VIDEO) { try { File f = null; if (message.messageOwner.attachPath != null && message.messageOwner.attachPath.length() != 0) { f = new File(message.messageOwner.attachPath); } if (f == null || !f.exists()) { f = getFileLoader().getPathToMessage(message.messageOwner); } Intent intent = new Intent(Intent.ACTION_VIEW); if (Build.VERSION.SDK_INT >= 24) { intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setDataAndType(FileProvider.getUriForFile(getParentActivity(), ApplicationLoader.getApplicationId() + ".provider", f), "video/mp4"); } else { intent.setDataAndType(Uri.fromFile(f), "video/mp4"); } getParentActivity().startActivityForResult(intent, 500); } catch (Exception e) { alertUserOpenError(message); } } else if (message.type == MessageObject.TYPE_GEO) { if (!AndroidUtilities.isMapsInstalled(ChannelAdminLogActivity.this)) { return; } LocationActivity fragment = new LocationActivity(0); fragment.setMessageObject(message); presentFragment(fragment); } else if (message.type == MessageObject.TYPE_FILE || message.type == MessageObject.TYPE_TEXT) { if (message.getDocumentName().toLowerCase().endsWith("attheme")) { File locFile = null; if (message.messageOwner.attachPath != null && message.messageOwner.attachPath.length() != 0) { File f = new File(message.messageOwner.attachPath); if (f.exists()) { locFile = f; } } if (locFile == null) { File f = getFileLoader().getPathToMessage(message.messageOwner); if (f.exists()) { locFile = f; } } if (chatLayoutManager != null) { int lastPosition = chatLayoutManager.findLastVisibleItemPosition(); if (lastPosition < chatLayoutManager.getItemCount() - 1) { scrollToPositionOnRecreate = chatLayoutManager.findFirstVisibleItemPosition(); RecyclerListView.Holder holder = (RecyclerListView.Holder) chatListView.findViewHolderForAdapterPosition(scrollToPositionOnRecreate); if (holder != null) { scrollToOffsetOnRecreate = holder.itemView.getTop(); } else { scrollToPositionOnRecreate = -1; } } else { scrollToPositionOnRecreate = -1; } } Theme.ThemeInfo themeInfo = Theme.applyThemeFile(locFile, message.getDocumentName(), null, true); if (themeInfo != null) { presentFragment(new ThemePreviewActivity(themeInfo)); return; } else { scrollToPositionOnRecreate = -1; } } try { AndroidUtilities.openForView(message, getParentActivity(), null); } catch (Exception e) { alertUserOpenError(message); } } } @Override public void didPressInstantButton(ChatMessageCell cell, int type) { MessageObject messageObject = cell.getMessageObject(); if (type == 0) { if (messageObject.messageOwner.media != null && messageObject.messageOwner.media.webpage != null && messageObject.messageOwner.media.webpage.cached_page != null) { ArticleViewer.getInstance().setParentActivity(getParentActivity(), ChannelAdminLogActivity.this); ArticleViewer.getInstance().open(messageObject); } } else if (type == 5) { openVCard(getMessagesController().getUser(messageObject.messageOwner.media.user_id), messageObject.messageOwner.media.vcard, messageObject.messageOwner.media.first_name, messageObject.messageOwner.media.last_name); } else { if (messageObject.messageOwner.media != null && messageObject.messageOwner.media.webpage != null) { Browser.openUrl(getParentActivity(), messageObject.messageOwner.media.webpage.url); } } } }); chatMessageCell.setAllowAssistant(true); } else if (viewType == 1) { view = new ChatActionCell(mContext) { @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); // if alpha == 0, then visibleToUser == false, so we need to override it // to keep accessibility working correctly info.setVisibleToUser(true); } }; ((ChatActionCell) view).setDelegate(new ChatActionCell.ChatActionCellDelegate() { @Override public void didClickImage(ChatActionCell cell) { MessageObject message = cell.getMessageObject(); PhotoViewer.getInstance().setParentActivity(ChannelAdminLogActivity.this); TLRPC.PhotoSize photoSize = FileLoader.getClosestPhotoSizeWithSize(message.photoThumbs, 640); if (photoSize != null) { ImageLocation imageLocation = ImageLocation.getForPhoto(photoSize, message.messageOwner.action.photo); PhotoViewer.getInstance().openPhoto(photoSize.location, imageLocation, provider); } else { PhotoViewer.getInstance().openPhoto(message, null, 0, 0, 0, provider); } } @Override public boolean didLongPress(ChatActionCell cell, float x, float y) { return createMenu(cell); } @Override public void needOpenUserProfile(long uid) { if (uid < 0) { Bundle args = new Bundle(); args.putLong("chat_id", -uid); if (MessagesController.getInstance(currentAccount).checkCanOpenChat(args, ChannelAdminLogActivity.this)) { presentFragment(new ChatActivity(args), true); } } else if (uid != UserConfig.getInstance(currentAccount).getClientUserId()) { Bundle args = new Bundle(); args.putLong("user_id", uid); addCanBanUser(args, uid); ProfileActivity fragment = new ProfileActivity(args); fragment.setPlayProfileAnimation(0); presentFragment(fragment); } } public void needOpenInviteLink(final TLRPC.TL_chatInviteExported invite) { if (linviteLoading) { return; } Object cachedInvite = invitesCache.containsKey(invite.link) ? invitesCache.get(invite.link) : null; if (cachedInvite == null) { TLRPC.TL_messages_getExportedChatInvite req = new TLRPC.TL_messages_getExportedChatInvite(); req.peer = getMessagesController().getInputPeer(-currentChat.id); req.link = invite.link; linviteLoading = true; boolean[] canceled = new boolean[1]; final AlertDialog progressDialog = new AlertDialog(getParentActivity(), AlertDialog.ALERT_TYPE_SPINNER); progressDialog.setOnCancelListener(dialogInterface -> { linviteLoading = false; canceled[0] = true; }); progressDialog.showDelayed(300); int reqId = getConnectionsManager().sendRequest(req, (response, error) -> { TLRPC.TL_messages_exportedChatInvite resInvite = null; if (error == null) { resInvite = (TLRPC.TL_messages_exportedChatInvite) response; for (int i = 0; i < resInvite.users.size(); i++) { TLRPC.User user = resInvite.users.get(i); if (usersMap == null) { usersMap = new HashMap<>(); } usersMap.put(user.id, user); } } TLRPC.TL_messages_exportedChatInvite finalInvite = resInvite; AndroidUtilities.runOnUIThread(() -> { linviteLoading = false; invitesCache.put(invite.link, finalInvite == null ? 0 : finalInvite); if (canceled[0]) { return; } progressDialog.dismiss(); if (finalInvite != null) { showInviteLinkBottomSheet(finalInvite, usersMap); } else { BulletinFactory.of(ChannelAdminLogActivity.this).createSimpleBulletin(R.raw.linkbroken, LocaleController.getString("LinkHashExpired", R.string.LinkHashExpired)).show(); } }); }); getConnectionsManager().bindRequestToGuid(reqId, classGuid); } else if (cachedInvite instanceof TLRPC.TL_messages_exportedChatInvite) { showInviteLinkBottomSheet((TLRPC.TL_messages_exportedChatInvite) cachedInvite, usersMap); } else { BulletinFactory.of(ChannelAdminLogActivity.this).createSimpleBulletin(R.raw.linkbroken, LocaleController.getString("LinkHashExpired", R.string.LinkHashExpired)).show(); } } @Override public BaseFragment getBaseFragment() { return ChannelAdminLogActivity.this; } @Override public long getDialogId() { return -currentChat.id; } @Override public void didPressReplyMessage(ChatActionCell cell, int id) { } @Override public void didPressBotButton(MessageObject messageObject, TLRPC.KeyboardButton button) { } }); } else if (viewType == 2) { view = new ChatUnreadCell(mContext, null); } else { view = new ChatLoadingCell(mContext, contentView, null); } view.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT)); return new RecyclerListView.Holder(view); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (position == loadingUpRow) { ChatLoadingCell loadingCell = (ChatLoadingCell) holder.itemView; loadingCell.setProgressVisible(loadsCount > 1); } else if (position >= messagesStartRow && position < messagesEndRow) { MessageObject message = messages.get(messages.size() - (position - messagesStartRow) - 1); View view = holder.itemView; if (view instanceof ChatMessageCell) { final ChatMessageCell messageCell = (ChatMessageCell) view; messageCell.isChat = true; int nextType = getItemViewType(position + 1); int prevType = getItemViewType(position - 1); boolean pinnedBotton; boolean pinnedTop; if (!(message.messageOwner.reply_markup instanceof TLRPC.TL_replyInlineMarkup) && nextType == holder.getItemViewType()) { MessageObject nextMessage = messages.get(messages.size() - (position + 1 - messagesStartRow) - 1); pinnedBotton = nextMessage.isOutOwner() == message.isOutOwner() && (nextMessage.getFromChatId() == message.getFromChatId()) && Math.abs(nextMessage.messageOwner.date - message.messageOwner.date) <= 5 * 60; } else { pinnedBotton = false; } if (prevType == holder.getItemViewType()) { MessageObject prevMessage = messages.get(messages.size() - (position - messagesStartRow)); pinnedTop = !(prevMessage.messageOwner.reply_markup instanceof TLRPC.TL_replyInlineMarkup) && prevMessage.isOutOwner() == message.isOutOwner() && (prevMessage.getFromChatId() == message.getFromChatId()) && Math.abs(prevMessage.messageOwner.date - message.messageOwner.date) <= 5 * 60; } else { pinnedTop = false; } messageCell.setMessageObject(message, null, pinnedBotton, pinnedTop); messageCell.setHighlighted(false); messageCell.setHighlightedText(null); } else if (view instanceof ChatActionCell) { ChatActionCell actionCell = (ChatActionCell) view; actionCell.setMessageObject(message); actionCell.setAlpha(1.0f); } } } @Override public int getItemViewType(int position) { if (position >= messagesStartRow && position < messagesEndRow) { return messages.get(messages.size() - (position - messagesStartRow) - 1).contentType; } return 4; } @Override public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) { if (holder.itemView instanceof ChatMessageCell || holder.itemView instanceof ChatActionCell) { View view = holder.itemView; holder.itemView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { view.getViewTreeObserver().removeOnPreDrawListener(this); int height = chatListView.getMeasuredHeight(); int top = view.getTop(); int bottom = view.getBottom(); int viewTop = top >= 0 ? 0 : -top; int viewBottom = view.getMeasuredHeight(); if (viewBottom > height) { viewBottom = viewTop + height; } if (holder.itemView instanceof ChatMessageCell) { ((ChatMessageCell) view).setVisiblePart(viewTop, viewBottom - viewTop, contentView.getHeightWithKeyboard() - AndroidUtilities.dp(48) - chatListView.getTop(), 0, view.getY() + actionBar.getMeasuredHeight() - contentView.getBackgroundTranslationY(), contentView.getMeasuredWidth(), contentView.getBackgroundSizeY(), 0, 0); } else if (holder.itemView instanceof ChatActionCell) { if (actionBar != null && contentView != null) { ((ChatActionCell) view).setVisiblePart(view.getY() + actionBar.getMeasuredHeight() - contentView.getBackgroundTranslationY(), contentView.getBackgroundSizeY()); } } return true; } }); } if (holder.itemView instanceof ChatMessageCell) { final ChatMessageCell messageCell = (ChatMessageCell) holder.itemView; MessageObject message = messageCell.getMessageObject(); messageCell.setBackgroundDrawable(null); messageCell.setCheckPressed(true, false); messageCell.setHighlighted(false); } } public void updateRowWithMessageObject(MessageObject messageObject) { int index = messages.indexOf(messageObject); if (index == -1) { return; } notifyItemChanged(messagesStartRow + messages.size() - index - 1); } @Override public void notifyDataSetChanged() { updateRows(); try { super.notifyDataSetChanged(); } catch (Exception e) { FileLog.e(e); } } @Override public void notifyItemChanged(int position) { updateRows(); try { super.notifyItemChanged(position); } catch (Exception e) { FileLog.e(e); } } @Override public void notifyItemRangeChanged(int positionStart, int itemCount) { updateRows(); try { super.notifyItemRangeChanged(positionStart, itemCount); } catch (Exception e) { FileLog.e(e); } } @Override public void notifyItemInserted(int position) { updateRows(); try { super.notifyItemInserted(position); } catch (Exception e) { FileLog.e(e); } } @Override public void notifyItemMoved(int fromPosition, int toPosition) { updateRows(); try { super.notifyItemMoved(fromPosition, toPosition); } catch (Exception e) { FileLog.e(e); } } @Override public void notifyItemRangeInserted(int positionStart, int itemCount) { updateRows(); try { super.notifyItemRangeInserted(positionStart, itemCount); } catch (Exception e) { FileLog.e(e); } } @Override public void notifyItemRemoved(int position) { updateRows(); try { super.notifyItemRemoved(position); } catch (Exception e) { FileLog.e(e); } } @Override public void notifyItemRangeRemoved(int positionStart, int itemCount) { updateRows(); try { super.notifyItemRangeRemoved(positionStart, itemCount); } catch (Exception e) { FileLog.e(e); } } } private void showInviteLinkBottomSheet(TLRPC.TL_messages_exportedChatInvite invite, HashMap<Long, TLRPC.User> usersMap) { TLRPC.ChatFull chatInfo = getMessagesController().getChatFull(currentChat.id); InviteLinkBottomSheet inviteLinkBottomSheet = new InviteLinkBottomSheet(contentView.getContext(), (TLRPC.TL_chatInviteExported) invite.invite, chatInfo, usersMap, ChannelAdminLogActivity.this, chatInfo.id, false, ChatObject.isChannel(currentChat)); inviteLinkBottomSheet.setInviteDelegate(new InviteLinkBottomSheet.InviteDelegate() { @Override public void permanentLinkReplaced(TLRPC.TL_chatInviteExported oldLink, TLRPC.TL_chatInviteExported newLink) { } @Override public void linkRevoked(TLRPC.TL_chatInviteExported invite) { TLRPC.TL_channelAdminLogEvent event = new TLRPC.TL_channelAdminLogEvent(); int size = messages.size(); invite.revoked = true; TLRPC.TL_channelAdminLogEventActionExportedInviteRevoke revokeAction = new TLRPC.TL_channelAdminLogEventActionExportedInviteRevoke(); revokeAction.invite = invite; event.action = revokeAction; event.date = (int) (System.currentTimeMillis() / 1000L); event.user_id = getAccountInstance().getUserConfig().clientUserId; MessageObject messageObject = new MessageObject(currentAccount, event, messages, messagesByDays, currentChat, mid, true); if (messageObject.contentType < 0) { return; } int addCount = messages.size() - size; if (addCount > 0) { chatListItemAnimator.setShouldAnimateEnterFromBottom(true); chatAdapter.notifyItemRangeInserted(chatAdapter.messagesEndRow, addCount); moveScrollToLastMessage(); } invitesCache.remove(invite.link); } @Override public void onLinkDeleted(TLRPC.TL_chatInviteExported invite) { int size = messages.size(); int messagesEndRow = chatAdapter.messagesEndRow; TLRPC.TL_channelAdminLogEvent event = new TLRPC.TL_channelAdminLogEvent(); TLRPC.TL_channelAdminLogEventActionExportedInviteDelete deleteAction = new TLRPC.TL_channelAdminLogEventActionExportedInviteDelete(); deleteAction.invite = invite; event.action = deleteAction; event.date = (int) (System.currentTimeMillis() / 1000L); event.user_id = getAccountInstance().getUserConfig().clientUserId; MessageObject messageObject = new MessageObject(currentAccount, event, messages, messagesByDays, currentChat, mid, true); if (messageObject.contentType < 0) { return; } int addCount = messages.size() - size; if (addCount > 0) { chatListItemAnimator.setShouldAnimateEnterFromBottom(true); chatAdapter.notifyItemRangeInserted(chatAdapter.messagesEndRow, addCount); moveScrollToLastMessage(); } invitesCache.remove(invite.link); } @Override public void onLinkEdited(TLRPC.TL_chatInviteExported invite) { TLRPC.TL_channelAdminLogEvent event = new TLRPC.TL_channelAdminLogEvent(); TLRPC.TL_channelAdminLogEventActionExportedInviteEdit editAction = new TLRPC.TL_channelAdminLogEventActionExportedInviteEdit(); editAction.new_invite = invite; editAction.prev_invite = invite; event.action = editAction; event.date = (int) (System.currentTimeMillis() / 1000L); event.user_id = getAccountInstance().getUserConfig().clientUserId; MessageObject messageObject = new MessageObject(currentAccount, event, messages, messagesByDays, currentChat, mid, true); if (messageObject.contentType < 0) { return; } chatAdapter.notifyDataSetChanged(); moveScrollToLastMessage(); } }); inviteLinkBottomSheet.show(); } @Override public ArrayList<ThemeDescription> getThemeDescriptions() { ArrayList<ThemeDescription> themeDescriptions = new ArrayList<>(); themeDescriptions.add(new ThemeDescription(fragmentView, 0, null, null, null, null, Theme.key_chat_wallpaper)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_actionBarDefault)); themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_LISTGLOWCOLOR, null, null, null, null, Theme.key_actionBarDefault)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_ITEMSCOLOR, null, null, null, null, Theme.key_actionBarDefaultIcon)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SELECTORCOLOR, null, null, null, null, Theme.key_actionBarDefaultSelector)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SUBMENUBACKGROUND, null, null, null, null, Theme.key_actionBarDefaultSubmenuBackground)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SUBMENUITEM, null, null, null, null, Theme.key_actionBarDefaultSubmenuItem)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SUBMENUITEM | ThemeDescription.FLAG_IMAGECOLOR, null, null, null, null, Theme.key_actionBarDefaultSubmenuItemIcon)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_actionBarDefault)); themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_LISTGLOWCOLOR, null, null, null, null, Theme.key_actionBarDefault)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_ITEMSCOLOR, null, null, null, null, Theme.key_actionBarDefaultIcon)); themeDescriptions.add(new ThemeDescription(avatarContainer.getTitleTextView(), ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_actionBarDefaultTitle)); themeDescriptions.add(new ThemeDescription(avatarContainer.getSubtitleTextView(), ThemeDescription.FLAG_TEXTCOLOR, null, new Paint[]{Theme.chat_statusPaint, Theme.chat_statusRecordPaint}, null, null, Theme.key_actionBarDefaultSubtitle, null)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SELECTORCOLOR, null, null, null, null, Theme.key_actionBarDefaultSelector)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.avatarDrawables, null, Theme.key_avatar_text)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_backgroundRed)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_backgroundOrange)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_backgroundViolet)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_backgroundGreen)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_backgroundCyan)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_backgroundBlue)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_backgroundPink)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_nameInMessageRed)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_nameInMessageOrange)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_nameInMessageViolet)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_nameInMessageGreen)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_nameInMessageCyan)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_nameInMessageBlue)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_nameInMessagePink)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInDrawable, Theme.chat_msgInMediaDrawable}, null, Theme.key_chat_inBubble)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInSelectedDrawable, Theme.chat_msgInMediaSelectedDrawable}, null, Theme.key_chat_inBubbleSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgInDrawable.getShadowDrawables(), null, Theme.key_chat_inBubbleShadow)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgInMediaDrawable.getShadowDrawables(), null, Theme.key_chat_inBubbleShadow)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgOutDrawable.getShadowDrawables(), null, Theme.key_chat_outBubbleShadow)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgOutMediaDrawable.getShadowDrawables(), null, Theme.key_chat_outBubbleShadow)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutDrawable, Theme.chat_msgOutMediaDrawable}, null, Theme.key_chat_outBubble)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutDrawable, Theme.chat_msgOutMediaDrawable}, null, Theme.key_chat_outBubbleGradient1)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutDrawable, Theme.chat_msgOutMediaDrawable}, null, Theme.key_chat_outBubbleGradient2)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutDrawable, Theme.chat_msgOutMediaDrawable}, null, Theme.key_chat_outBubbleGradient3)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutSelectedDrawable, Theme.chat_msgOutMediaSelectedDrawable}, null, Theme.key_chat_outBubbleSelected)); themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_TEXTCOLOR, new Class[]{ChatActionCell.class}, Theme.chat_actionTextPaint, null, null, Theme.key_chat_serviceText)); themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_LINKCOLOR, new Class[]{ChatActionCell.class}, Theme.chat_actionTextPaint, null, null, Theme.key_chat_serviceLink)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_botCardDrawable, Theme.chat_shareIconDrawable, Theme.chat_botInlineDrawable, Theme.chat_botLinkDrawable, Theme.chat_goIconDrawable, Theme.chat_commentStickerDrawable}, null, Theme.key_chat_serviceIcon)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class, ChatActionCell.class}, null, null, null, Theme.key_chat_serviceBackground)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class, ChatActionCell.class}, null, null, null, Theme.key_chat_serviceBackgroundSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_messageTextIn)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_messageTextOut)); themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_LINKCOLOR, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_messageLinkIn, null)); themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_LINKCOLOR, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_messageLinkOut, null)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutCheckDrawable}, null, Theme.key_chat_outSentCheck)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutCheckSelectedDrawable}, null, Theme.key_chat_outSentCheckSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutCheckReadDrawable, Theme.chat_msgOutHalfCheckDrawable}, null, Theme.key_chat_outSentCheckRead)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutCheckReadSelectedDrawable, Theme.chat_msgOutHalfCheckSelectedDrawable}, null, Theme.key_chat_outSentCheckReadSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgMediaCheckDrawable, Theme.chat_msgMediaHalfCheckDrawable}, null, Theme.key_chat_mediaSentCheck)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutViewsDrawable, Theme.chat_msgOutRepliesDrawable, Theme.chat_msgOutPinnedDrawable}, null, Theme.key_chat_outViews)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutViewsSelectedDrawable, Theme.chat_msgOutRepliesSelectedDrawable, Theme.chat_msgOutPinnedSelectedDrawable}, null, Theme.key_chat_outViewsSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInViewsDrawable, Theme.chat_msgInRepliesDrawable, Theme.chat_msgInPinnedDrawable}, null, Theme.key_chat_inViews)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInViewsSelectedDrawable, Theme.chat_msgInRepliesSelectedDrawable, Theme.chat_msgInPinnedSelectedDrawable}, null, Theme.key_chat_inViewsSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgMediaViewsDrawable, Theme.chat_msgMediaRepliesDrawable, Theme.chat_msgMediaPinnedDrawable}, null, Theme.key_chat_mediaViews)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutMenuDrawable}, null, Theme.key_chat_outMenu)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutMenuSelectedDrawable}, null, Theme.key_chat_outMenuSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInMenuDrawable}, null, Theme.key_chat_inMenu)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInMenuSelectedDrawable}, null, Theme.key_chat_inMenuSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgMediaMenuDrawable}, null, Theme.key_chat_mediaMenu)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutInstantDrawable}, null, Theme.key_chat_outInstant)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInInstantDrawable, Theme.chat_commentDrawable, Theme.chat_commentArrowDrawable}, null, Theme.key_chat_inInstant)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgOutCallDrawable, null, Theme.key_chat_outInstant)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgOutCallSelectedDrawable, null, Theme.key_chat_outInstantSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgInCallDrawable, null, Theme.key_chat_inInstant)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgInCallSelectedDrawable, null, Theme.key_chat_inInstantSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgCallUpGreenDrawable}, null, Theme.key_chat_outGreenCall)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgCallDownRedDrawable}, null, Theme.key_chat_inRedCall)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgCallDownGreenDrawable}, null, Theme.key_chat_inGreenCall)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, Theme.chat_msgErrorPaint, null, null, Theme.key_chat_sentError)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgErrorDrawable}, null, Theme.key_chat_sentErrorIcon)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, Theme.chat_durationPaint, null, null, Theme.key_chat_previewDurationText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, Theme.chat_gamePaint, null, null, Theme.key_chat_previewGameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inPreviewInstantText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outPreviewInstantText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, Theme.chat_deleteProgressPaint, null, null, Theme.key_chat_secretTimeText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_stickerNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, Theme.chat_botButtonPaint, null, null, Theme.key_chat_botButtonText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inForwardedNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outForwardedNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inViaBotNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outViaBotNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_stickerViaBotNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inReplyLine)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outReplyLine)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_stickerReplyLine)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inReplyNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outReplyNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_stickerReplyNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inReplyMessageText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outReplyMessageText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inReplyMediaMessageText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outReplyMediaMessageText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inReplyMediaMessageSelectedText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outReplyMediaMessageSelectedText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_stickerReplyMessageText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inPreviewLine)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outPreviewLine)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inSiteNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outSiteNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inContactNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outContactNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inContactPhoneText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outContactPhoneText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_mediaProgress)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inAudioProgress)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outAudioProgress)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inAudioSelectedProgress)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outAudioSelectedProgress)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_mediaTimeText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inTimeText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outTimeText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inTimeSelectedText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outTimeSelectedText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inAudioPerformerText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outAudioPerformerText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inAudioTitleText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outAudioTitleText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inAudioDurationText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outAudioDurationText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inAudioDurationSelectedText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outAudioDurationSelectedText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inAudioSeekbar)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outAudioSeekbar)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inAudioSeekbarSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outAudioSeekbarSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inAudioSeekbarFill)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inAudioCacheSeekbar)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outAudioSeekbarFill)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outAudioCacheSeekbar)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inVoiceSeekbar)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outVoiceSeekbar)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inVoiceSeekbarSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outVoiceSeekbarSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inVoiceSeekbarFill)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outVoiceSeekbarFill)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inFileProgress)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outFileProgress)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inFileProgressSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outFileProgressSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inFileNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outFileNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inFileInfoText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outFileInfoText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inFileInfoSelectedText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outFileInfoSelectedText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inFileBackground)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outFileBackground)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inFileBackgroundSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outFileBackgroundSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inVenueInfoText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outVenueInfoText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inVenueInfoSelectedText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outVenueInfoSelectedText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_mediaInfoText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, Theme.chat_urlPaint, null, null, Theme.key_chat_linkSelectBackground)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, Theme.chat_textSearchSelectionPaint, null, null, Theme.key_chat_textSelectBackground)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outLoader)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outMediaIcon)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outLoaderSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outMediaIconSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inLoader)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inMediaIcon)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inLoaderSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inMediaIconSelected)); themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_BACKGROUNDFILTER, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_contactDrawable[0]}, null, Theme.key_chat_inContactBackground)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_contactDrawable[0]}, null, Theme.key_chat_inContactIcon)); themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_BACKGROUNDFILTER, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_contactDrawable[1]}, null, Theme.key_chat_outContactBackground)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_contactDrawable[1]}, null, Theme.key_chat_outContactIcon)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inLocationBackground)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_locationDrawable[0]}, null, Theme.key_chat_inLocationIcon)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_locationDrawable[1]}, null, Theme.key_chat_outLocationIcon)); themeDescriptions.add(new ThemeDescription(bottomOverlayChat, 0, null, Theme.chat_composeBackgroundPaint, null, null, Theme.key_chat_messagePanelBackground)); themeDescriptions.add(new ThemeDescription(bottomOverlayChat, 0, null, null, new Drawable[]{Theme.chat_composeShadowDrawable}, null, Theme.key_chat_messagePanelShadow)); themeDescriptions.add(new ThemeDescription(bottomOverlayChatText, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_chat_fieldOverlayText)); themeDescriptions.add(new ThemeDescription(emptyView, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_chat_serviceText)); themeDescriptions.add(new ThemeDescription(progressBar, ThemeDescription.FLAG_PROGRESSBAR, null, null, null, null, Theme.key_chat_serviceText)); themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_USEBACKGROUNDDRAWABLE, new Class[]{ChatUnreadCell.class}, new String[]{"backgroundLayout"}, null, null, null, Theme.key_chat_unreadMessagesStartBackground)); themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_IMAGECOLOR, new Class[]{ChatUnreadCell.class}, new String[]{"imageView"}, null, null, null, Theme.key_chat_unreadMessagesStartArrowIcon)); themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_TEXTCOLOR, new Class[]{ChatUnreadCell.class}, new String[]{"textView"}, null, null, null, Theme.key_chat_unreadMessagesStartText)); themeDescriptions.add(new ThemeDescription(progressView2, ThemeDescription.FLAG_SERVICEBACKGROUND, null, null, null, null, Theme.key_chat_serviceBackground)); themeDescriptions.add(new ThemeDescription(emptyView, ThemeDescription.FLAG_SERVICEBACKGROUND, null, null, null, null, Theme.key_chat_serviceBackground)); themeDescriptions.add(new ThemeDescription(undoView, ThemeDescription.FLAG_BACKGROUNDFILTER, null, null, null, null, Theme.key_undo_background)); themeDescriptions.add(new ThemeDescription(undoView, 0, new Class[]{UndoView.class}, new String[]{"undoImageView"}, null, null, null, Theme.key_undo_cancelColor)); themeDescriptions.add(new ThemeDescription(undoView, 0, new Class[]{UndoView.class}, new String[]{"undoTextView"}, null, null, null, Theme.key_undo_cancelColor)); themeDescriptions.add(new ThemeDescription(undoView, 0, new Class[]{UndoView.class}, new String[]{"infoTextView"}, null, null, null, Theme.key_undo_infoColor)); themeDescriptions.add(new ThemeDescription(undoView, 0, new Class[]{UndoView.class}, new String[]{"textPaint"}, null, null, null, Theme.key_undo_infoColor)); themeDescriptions.add(new ThemeDescription(undoView, 0, new Class[]{UndoView.class}, new String[]{"progressPaint"}, null, null, null, Theme.key_undo_infoColor)); themeDescriptions.add(new ThemeDescription(undoView, ThemeDescription.FLAG_IMAGECOLOR, new Class[]{UndoView.class}, new String[]{"leftImageView"}, null, null, null, Theme.key_undo_infoColor)); return themeDescriptions; } }
flyun/chatAir
TMessagesProj/src/main/java/org/telegram/ui/ChannelAdminLogActivity.java
41,686
package org.telegram.messenger.voip; import org.json.JSONException; import org.json.JSONObject; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.BuildVars; import org.telegram.messenger.FileLog; import org.webrtc.ContextUtils; import org.webrtc.VideoSink; import java.util.Arrays; import java.util.List; public final class Instance { public static final List<String> AVAILABLE_VERSIONS = Arrays.asList("2.4.4", "2.7.7", "5.0.0", "6.0.0", "7.0.0", "8.0.0", "9.0.0", "10.0.0", "11.0.0"); public static final int AUDIO_STATE_MUTED = 0; public static final int AUDIO_STATE_ACTIVE = 1; public static final int VIDEO_STATE_INACTIVE = 0; public static final int VIDEO_STATE_PAUSED = 1; public static final int VIDEO_STATE_ACTIVE = 2; //region Constants public static final int NET_TYPE_UNKNOWN = 0; public static final int NET_TYPE_GPRS = 1; public static final int NET_TYPE_EDGE = 2; public static final int NET_TYPE_3G = 3; public static final int NET_TYPE_HSPA = 4; public static final int NET_TYPE_LTE = 5; public static final int NET_TYPE_WIFI = 6; public static final int NET_TYPE_ETHERNET = 7; public static final int NET_TYPE_OTHER_HIGH_SPEED = 8; public static final int NET_TYPE_OTHER_LOW_SPEED = 9; public static final int NET_TYPE_DIALUP = 10; public static final int NET_TYPE_OTHER_MOBILE = 11; public static final int ENDPOINT_TYPE_INET = 0; public static final int ENDPOINT_TYPE_LAN = 1; public static final int ENDPOINT_TYPE_UDP_RELAY = 2; public static final int ENDPOINT_TYPE_TCP_RELAY = 3; public static final int STATE_WAIT_INIT = 1; public static final int STATE_WAIT_INIT_ACK = 2; public static final int STATE_ESTABLISHED = 3; public static final int STATE_FAILED = 4; public static final int STATE_RECONNECTING = 5; public static final int DATA_SAVING_NEVER = 0; public static final int DATA_SAVING_MOBILE = 1; public static final int DATA_SAVING_ALWAYS = 2; public static final int DATA_SAVING_ROAMING = 3; public static final int PEER_CAP_GROUP_CALLS = 1; // Java-side Errors public static final String ERROR_CONNECTION_SERVICE = "ERROR_CONNECTION_SERVICE"; public static final String ERROR_INSECURE_UPGRADE = "ERROR_INSECURE_UPGRADE"; public static final String ERROR_LOCALIZED = "ERROR_LOCALIZED"; public static final String ERROR_PRIVACY = "ERROR_PRIVACY"; public static final String ERROR_PEER_OUTDATED = "ERROR_PEER_OUTDATED"; // Native-side Errors public static final String ERROR_UNKNOWN = "ERROR_UNKNOWN"; public static final String ERROR_INCOMPATIBLE = "ERROR_INCOMPATIBLE"; public static final String ERROR_TIMEOUT = "ERROR_TIMEOUT"; public static final String ERROR_AUDIO_IO = "ERROR_AUDIO_IO"; //endregion private static ServerConfig globalServerConfig = new ServerConfig(new JSONObject()); private static int bufferSize; private static NativeInstance instance; private Instance() { } public static ServerConfig getGlobalServerConfig() { return globalServerConfig; } public static void setGlobalServerConfig(String serverConfigJson) { try { globalServerConfig = new ServerConfig(new JSONObject(serverConfigJson)); if (instance != null) { instance.setGlobalServerConfig(serverConfigJson); } } catch (JSONException e) { if (BuildVars.LOGS_ENABLED) { FileLog.e("failed to parse tgvoip server config", e); } } } public static void destroyInstance() { instance = null; } public static NativeInstance makeInstance(String version, Config config, String persistentStateFilePath, Endpoint[] endpoints, Proxy proxy, int networkType, EncryptionKey encryptionKey, VideoSink remoteSink, long videoCapturer, NativeInstance.AudioLevelsCallback audioLevelsCallback) { if (!"2.4.4".equals(version)) { ContextUtils.initialize(ApplicationLoader.applicationContext); } instance = NativeInstance.make(version, config, persistentStateFilePath, endpoints, proxy, networkType, encryptionKey, remoteSink, videoCapturer, audioLevelsCallback); setGlobalServerConfig(globalServerConfig.jsonObject.toString()); setBufferSize(bufferSize); return instance; } public static void setBufferSize(int size) { bufferSize = size; if (instance != null) { instance.setBufferSize(size); } } public static int getConnectionMaxLayer() { return 92; } public static String getVersion() { return instance != null ? instance.getVersion() : null; } private static void checkHasDelegate() { if (instance == null) { throw new IllegalStateException("tgvoip version is not set"); } } public interface OnStateUpdatedListener { void onStateUpdated(int state, boolean inTransition); } public interface OnSignalBarsUpdatedListener { void onSignalBarsUpdated(int signalBars); } public interface OnSignalingDataListener { void onSignalingData(byte[] data); } public interface OnRemoteMediaStateUpdatedListener { void onMediaStateUpdated(int audioState, int videoState); } public static final class Config { public final double initializationTimeout; public final double receiveTimeout; public final int dataSaving; public final boolean enableP2p; public final boolean enableAec; public final boolean enableNs; public final boolean enableAgc; public final boolean enableCallUpgrade; public final String logPath; public final String statsLogPath; public final int maxApiLayer; public final boolean enableSm; public Config(double initializationTimeout, double receiveTimeout, int dataSaving, boolean enableP2p, boolean enableAec, boolean enableNs, boolean enableAgc, boolean enableCallUpgrade, boolean enableSm, String logPath, String statsLogPath, int maxApiLayer) { this.initializationTimeout = initializationTimeout; this.receiveTimeout = receiveTimeout; this.dataSaving = dataSaving; this.enableP2p = enableP2p; this.enableAec = enableAec; this.enableNs = enableNs; this.enableAgc = enableAgc; this.enableCallUpgrade = enableCallUpgrade; this.logPath = logPath; this.statsLogPath = statsLogPath; this.maxApiLayer = maxApiLayer; this.enableSm = enableSm; } @Override public String toString() { return "Config{" + "initializationTimeout=" + initializationTimeout + ", receiveTimeout=" + receiveTimeout + ", dataSaving=" + dataSaving + ", enableP2p=" + enableP2p + ", enableAec=" + enableAec + ", enableNs=" + enableNs + ", enableAgc=" + enableAgc + ", enableCallUpgrade=" + enableCallUpgrade + ", logPath='" + logPath + '\'' + ", statsLogPath='" + statsLogPath + '\'' + ", maxApiLayer=" + maxApiLayer + ", enableSm=" + enableSm + '}'; } } public static final class Endpoint { public final boolean isRtc; public final long id; public final String ipv4; public final String ipv6; public final int port; public final int type; public final byte[] peerTag; public final boolean turn; public final boolean stun; public final String username; public final String password; public final boolean tcp; public Endpoint(boolean isRtc, long id, String ipv4, String ipv6, int port, int type, byte[] peerTag, boolean turn, boolean stun, String username, String password, boolean tcp) { this.isRtc = isRtc; this.id = id; this.ipv4 = ipv4; this.ipv6 = ipv6; this.port = port; this.type = type; this.peerTag = peerTag; this.turn = turn; this.stun = stun; this.username = username; this.password = password; this.tcp = tcp; } @Override public String toString() { return "Endpoint{" + "id=" + id + ", ipv4='" + ipv4 + '\'' + ", ipv6='" + ipv6 + '\'' + ", port=" + port + ", type=" + type + ", peerTag=" + Arrays.toString(peerTag) + ", turn=" + turn + ", stun=" + stun + ", username=" + username + ", password=" + password + ", tcp=" + tcp + '}'; } } public static final class Proxy { public final String host; public final int port; public final String login; public final String password; public Proxy(String host, int port, String login, String password) { this.host = host; this.port = port; this.login = login; this.password = password; } @Override public String toString() { return "Proxy{" + "host='" + host + '\'' + ", port=" + port + ", login='" + login + '\'' + ", password='" + password + '\'' + '}'; } } public static final class EncryptionKey { public final byte[] value; public final boolean isOutgoing; public EncryptionKey(byte[] value, boolean isOutgoing) { this.value = value; this.isOutgoing = isOutgoing; } @Override public String toString() { return "EncryptionKey{" + "value=" + Arrays.toString(value) + ", isOutgoing=" + isOutgoing + '}'; } } public static final class FinalState { public final byte[] persistentState; public String debugLog; public final TrafficStats trafficStats; public final boolean isRatingSuggested; public FinalState(byte[] persistentState, String debugLog, TrafficStats trafficStats, boolean isRatingSuggested) { this.persistentState = persistentState; this.debugLog = debugLog; this.trafficStats = trafficStats; this.isRatingSuggested = isRatingSuggested; } @Override public String toString() { return "FinalState{" + "persistentState=" + Arrays.toString(persistentState) + ", debugLog='" + debugLog + '\'' + ", trafficStats=" + trafficStats + ", isRatingSuggested=" + isRatingSuggested + '}'; } } public static final class TrafficStats { public final long bytesSentWifi; public final long bytesReceivedWifi; public final long bytesSentMobile; public final long bytesReceivedMobile; public TrafficStats(long bytesSentWifi, long bytesReceivedWifi, long bytesSentMobile, long bytesReceivedMobile) { this.bytesSentWifi = bytesSentWifi; this.bytesReceivedWifi = bytesReceivedWifi; this.bytesSentMobile = bytesSentMobile; this.bytesReceivedMobile = bytesReceivedMobile; } @Override public String toString() { return "TrafficStats{" + "bytesSentWifi=" + bytesSentWifi + ", bytesReceivedWifi=" + bytesReceivedWifi + ", bytesSentMobile=" + bytesSentMobile + ", bytesReceivedMobile=" + bytesReceivedMobile + '}'; } } public static final class Fingerprint { public final String hash; public final String setup; public final String fingerprint; public Fingerprint(String hash, String setup, String fingerprint) { this.hash = hash; this.setup = setup; this.fingerprint = fingerprint; } @Override public String toString() { return "Fingerprint{" + "hash=" + hash + ", setup=" + setup + ", fingerprint=" + fingerprint + '}'; } } public static final class Candidate { public final String port; public final String protocol; public final String network; public final String generation; public final String id; public final String component; public final String foundation; public final String priority; public final String ip; public final String type; public final String tcpType; public final String relAddr; public final String relPort; public Candidate(String port, String protocol, String network, String generation, String id, String component, String foundation, String priority, String ip, String type, String tcpType, String relAddr, String relPort) { this.port = port; this.protocol = protocol; this.network = network; this.generation = generation; this.id = id; this.component = component; this.foundation = foundation; this.priority = priority; this.ip = ip; this.type = type; this.tcpType = tcpType; this.relAddr = relAddr; this.relPort = relPort; } @Override public String toString() { return "Candidate{" + "port=" + port + ", protocol=" + protocol + ", network=" + network + ", generation=" + generation + ", id=" + id + ", component=" + component + ", foundation=" + foundation + ", priority=" + priority + ", ip=" + ip + ", type=" + type + ", tcpType=" + tcpType + ", relAddr=" + relAddr + ", relPort=" + relPort + '}'; } } public static final class ServerConfig { public final boolean useSystemNs; public final boolean useSystemAec; public final boolean enableStunMarking; public final double hangupUiTimeout; public final boolean enable_vp8_encoder; public final boolean enable_vp8_decoder; public final boolean enable_vp9_encoder; public final boolean enable_vp9_decoder; public final boolean enable_h265_encoder; public final boolean enable_h265_decoder; public final boolean enable_h264_encoder; public final boolean enable_h264_decoder; private final JSONObject jsonObject; private ServerConfig(JSONObject jsonObject) { this.jsonObject = jsonObject; this.useSystemNs = jsonObject.optBoolean("use_system_ns", true); this.useSystemAec = jsonObject.optBoolean("use_system_aec", true); this.enableStunMarking = jsonObject.optBoolean("voip_enable_stun_marking", false); this.hangupUiTimeout = jsonObject.optDouble("hangup_ui_timeout", 5); this.enable_vp8_encoder = jsonObject.optBoolean("enable_vp8_encoder", true); this.enable_vp8_decoder = jsonObject.optBoolean("enable_vp8_decoder", true); this.enable_vp9_encoder = jsonObject.optBoolean("enable_vp9_encoder", true); this.enable_vp9_decoder = jsonObject.optBoolean("enable_vp9_decoder", true); this.enable_h265_encoder = jsonObject.optBoolean("enable_h265_encoder", true); this.enable_h265_decoder = jsonObject.optBoolean("enable_h265_decoder", true); this.enable_h264_encoder = jsonObject.optBoolean("enable_h264_encoder", true); this.enable_h264_decoder = jsonObject.optBoolean("enable_h264_decoder", true); } public String getString(String key) { return getString(key, ""); } public String getString(String key, String fallback) { return jsonObject.optString(key, fallback); } } }
jimdaxu/Telegram
TMessagesProj/src/main/java/org/telegram/messenger/voip/Instance.java
41,687
/* * Copyright 2019 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ package org.webrtc; import androidx.annotation.Nullable; /** * Lightweight abstraction for an object that can receive video frames, process them, and pass them * on to another object. This object is also allowed to observe capturer start/stop. */ public interface VideoProcessor extends CapturerObserver { public static class FrameAdaptationParameters { public final int cropX; public final int cropY; public final int cropWidth; public final int cropHeight; public final int scaleWidth; public final int scaleHeight; public final long timestampNs; public final boolean drop; public FrameAdaptationParameters(int cropX, int cropY, int cropWidth, int cropHeight, int scaleWidth, int scaleHeight, long timestampNs, boolean drop) { this.cropX = cropX; this.cropY = cropY; this.cropWidth = cropWidth; this.cropHeight = cropHeight; this.scaleWidth = scaleWidth; this.scaleHeight = scaleHeight; this.timestampNs = timestampNs; this.drop = drop; } } /** * This is a chance to access an unadapted frame. The default implementation applies the * adaptation and forwards the frame to {@link #onFrameCaptured(VideoFrame)}. */ default void onFrameCaptured(VideoFrame frame, FrameAdaptationParameters parameters) { VideoFrame adaptedFrame = applyFrameAdaptationParameters(frame, parameters); if (adaptedFrame != null) { onFrameCaptured(adaptedFrame); adaptedFrame.release(); } } /** * Set the sink that receives the output from this processor. Null can be passed in to unregister * a sink. */ void setSink(@Nullable VideoSink sink); /** * Applies the frame adaptation parameters to a frame. Returns null if the frame is meant to be * dropped. Returns a new frame. The caller is responsible for releasing the returned frame. */ public static @Nullable VideoFrame applyFrameAdaptationParameters( VideoFrame frame, FrameAdaptationParameters parameters) { if (parameters.drop) { return null; } final VideoFrame.Buffer adaptedBuffer = frame.getBuffer().cropAndScale(parameters.cropX, parameters.cropY, parameters.cropWidth, parameters.cropHeight, parameters.scaleWidth, parameters.scaleHeight); return new VideoFrame(adaptedBuffer, frame.getRotation(), parameters.timestampNs); } }
NekoX-Dev/NekoX
TMessagesProj/src/main/java/org/webrtc/VideoProcessor.java
41,688
/* * Copyright 2017 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ package org.webrtc; /** Enumeration of supported video codec types. */ enum VideoCodecMimeType { VP8("video/x-vnd.on2.vp8"), VP9("video/x-vnd.on2.vp9"), H264("video/avc"), H265("video/hevc"), AV1("video/av01"); private final String mimeType; private VideoCodecMimeType(String mimeType) { this.mimeType = mimeType; } String mimeType() { return mimeType; } }
NekoX-Dev/NekoX
TMessagesProj/src/main/java/org/webrtc/VideoCodecMimeType.java
41,689
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.weex.ui.view; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Rect; import android.media.MediaPlayer; import android.net.Uri; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewTreeObserver; import android.widget.FrameLayout; import android.widget.MediaController; import android.widget.ProgressBar; import android.widget.VideoView; import org.apache.weex.ui.view.gesture.WXGesture; import org.apache.weex.ui.view.gesture.WXGestureObservable; import org.apache.weex.utils.WXResourceUtils; public class WXVideoView extends VideoView implements WXGestureObservable { private WXGesture wxGesture; private VideoPlayListener mVideoPauseListener; public WXVideoView(Context context) { super(context); } @Override public void registerGestureListener(WXGesture wxGesture) { this.wxGesture = wxGesture; } @Override public WXGesture getGestureListener() { return wxGesture; } public void setOnVideoPauseListener(VideoPlayListener listener) { mVideoPauseListener = listener; } @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouchEvent(MotionEvent event) { boolean result = super.onTouchEvent(event); if (wxGesture != null) { result |= wxGesture.onTouch(this, event); } return result; } @Override public void start() { super.start(); if (mVideoPauseListener != null) { mVideoPauseListener.onStart(); } } @Override public void pause() { super.pause(); if (mVideoPauseListener != null) { mVideoPauseListener.onPause(); } } public interface VideoPlayListener { void onPause(); void onStart(); } public static class Wrapper extends FrameLayout implements ViewTreeObserver.OnGlobalLayoutListener { private WXVideoView mVideoView; private ProgressBar mProgressBar; private MediaController mMediaController; private Uri mUri; private MediaPlayer.OnPreparedListener mOnPreparedListener; private MediaPlayer.OnErrorListener mOnErrorListener; private MediaPlayer.OnCompletionListener mOnCompletionListener; private WXVideoView.VideoPlayListener mVideoPlayListener; private boolean mControls = true; public Wrapper(Context context) { super(context); init(context); } public Wrapper(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public Wrapper(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } private void init(Context context) { setBackgroundColor(WXResourceUtils.getColor("#ee000000")); mProgressBar = new ProgressBar(context); FrameLayout.LayoutParams pLayoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT); mProgressBar.setLayoutParams(pLayoutParams); pLayoutParams.gravity = Gravity.CENTER; addView(mProgressBar); getViewTreeObserver().addOnGlobalLayoutListener(this); } public ProgressBar getProgressBar() { return mProgressBar; } public @Nullable WXVideoView getVideoView() { return mVideoView; } /** * Create if not existed. Will cause request focus. * * @return */ public @NonNull WXVideoView createIfNotExist() { if (mVideoView == null) { createVideoView(); } return mVideoView; } public @Nullable MediaController getMediaController() { return mMediaController; } public void setVideoURI(Uri uri) { mUri = uri; if (mVideoView != null) { mVideoView.setVideoURI(uri); } } public void start() { if (mVideoView != null) { mVideoView.start(); } } public void pause() { if (mVideoView != null) { mVideoView.pause(); } } public void stopPlayback() { if (mVideoView != null) { mVideoView.stopPlayback(); } } public void resume() { if (mVideoView != null) { mVideoView.resume(); } } public void setOnErrorListener(MediaPlayer.OnErrorListener l) { mOnErrorListener = l; if (mVideoView != null) { mVideoView.setOnErrorListener(l); } } public void setOnPreparedListener(MediaPlayer.OnPreparedListener l) { mOnPreparedListener = l; if (mVideoView != null) { mVideoView.setOnPreparedListener(l); } } public void setOnCompletionListener(MediaPlayer.OnCompletionListener l) { mOnCompletionListener = l; if (mVideoView != null) { mVideoView.setOnCompletionListener(l); } } public void setOnVideoPauseListener(VideoPlayListener listener) { mVideoPlayListener = listener; if (mVideoView != null) { mVideoView.setOnVideoPauseListener(listener); } } public void setControls(boolean controls) { mControls = controls; if (mVideoView != null && mMediaController != null) { if (!mControls) { mMediaController.setVisibility(View.GONE); } else { mMediaController.setVisibility(View.VISIBLE); } } } private synchronized void createVideoView() { if(mVideoView != null){ return; } Context context = getContext(); WXVideoView video = new WXVideoView(context); FrameLayout.LayoutParams videoLayoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT); videoLayoutParams.gravity = Gravity.CENTER; video.setLayoutParams(videoLayoutParams); addView(video, 0);//first child video.setOnErrorListener(mOnErrorListener); video.setOnPreparedListener(mOnPreparedListener); video.setOnCompletionListener(mOnCompletionListener); video.setOnVideoPauseListener(mVideoPlayListener); MediaController controller = new MediaController(context); controller.setAnchorView(this); video.setMediaController(controller); controller.setMediaPlayer(video); if (!mControls) { controller.setVisibility(View.GONE); } else { controller.setVisibility(View.VISIBLE); } mMediaController = controller; mVideoView = video; mVideoView.setZOrderOnTop(true); if(mUri != null) { setVideoURI(mUri); } } @SuppressLint("NewApi") private void removeSelfFromViewTreeObserver() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { getViewTreeObserver().removeOnGlobalLayoutListener(this); } else { getViewTreeObserver().removeGlobalOnLayoutListener(this); } } public boolean createVideoViewIfVisible(){ Rect visibleRect = new Rect(); if (mVideoView != null) { return true; } else if (getGlobalVisibleRect(visibleRect) && !visibleRect.isEmpty()) { createVideoView(); return true; } return false; } @Override public void onGlobalLayout() { if(createVideoViewIfVisible()){ removeSelfFromViewTreeObserver(); } } } }
kuaifan/WeexSDK
android/sdk/src/main/java/org/apache/weex/ui/view/WXVideoView.java
41,690
package org.schabi.newpipe.download; import static org.schabi.newpipe.extractor.stream.DeliveryMethod.PROGRESSIVE_HTTP; import static org.schabi.newpipe.util.ListHelper.getStreamsOfSpecifiedDelivery; import static org.schabi.newpipe.util.Localization.assureCorrectAppLanguage; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.IBinder; import android.provider.Settings; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.RadioGroup; import android.widget.SeekBar; import android.widget.Toast; import androidx.activity.result.ActivityResult; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult; import androidx.annotation.IdRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.view.menu.ActionMenuItemView; import androidx.appcompat.widget.Toolbar; import androidx.collection.SparseArrayCompat; import androidx.documentfile.provider.DocumentFile; import androidx.fragment.app.DialogFragment; import androidx.preference.PreferenceManager; import com.nononsenseapps.filepicker.Utils; import org.schabi.newpipe.MainActivity; import org.schabi.newpipe.R; import org.schabi.newpipe.databinding.DownloadDialogBinding; import org.schabi.newpipe.error.ErrorInfo; import org.schabi.newpipe.error.ErrorUtil; import org.schabi.newpipe.error.UserAction; import org.schabi.newpipe.extractor.MediaFormat; import org.schabi.newpipe.extractor.NewPipe; import org.schabi.newpipe.extractor.localization.Localization; import org.schabi.newpipe.extractor.stream.AudioStream; import org.schabi.newpipe.extractor.stream.Stream; import org.schabi.newpipe.extractor.stream.StreamInfo; import org.schabi.newpipe.extractor.stream.SubtitlesStream; import org.schabi.newpipe.extractor.stream.VideoStream; import org.schabi.newpipe.settings.NewPipeSettings; import org.schabi.newpipe.streams.io.NoFileManagerSafeGuard; import org.schabi.newpipe.streams.io.StoredDirectoryHelper; import org.schabi.newpipe.streams.io.StoredFileHelper; import org.schabi.newpipe.util.FilePickerActivityHelper; import org.schabi.newpipe.util.FilenameUtils; import org.schabi.newpipe.util.ListHelper; import org.schabi.newpipe.util.PermissionHelper; import org.schabi.newpipe.util.SecondaryStreamHelper; import org.schabi.newpipe.util.SimpleOnSeekBarChangeListener; import org.schabi.newpipe.util.StreamItemAdapter; import org.schabi.newpipe.util.StreamItemAdapter.StreamInfoWrapper; import org.schabi.newpipe.util.AudioTrackAdapter; import org.schabi.newpipe.util.AudioTrackAdapter.AudioTracksWrapper; import org.schabi.newpipe.util.ThemeHelper; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.Optional; import icepick.Icepick; import icepick.State; import io.reactivex.rxjava3.disposables.CompositeDisposable; import us.shandian.giga.get.MissionRecoveryInfo; import us.shandian.giga.postprocessing.Postprocessing; import us.shandian.giga.service.DownloadManager; import us.shandian.giga.service.DownloadManagerService; import us.shandian.giga.service.DownloadManagerService.DownloadManagerBinder; import us.shandian.giga.service.MissionState; public class DownloadDialog extends DialogFragment implements RadioGroup.OnCheckedChangeListener, AdapterView.OnItemSelectedListener { private static final String TAG = "DialogFragment"; private static final boolean DEBUG = MainActivity.DEBUG; @State StreamInfo currentInfo; @State StreamInfoWrapper<VideoStream> wrappedVideoStreams; @State StreamInfoWrapper<SubtitlesStream> wrappedSubtitleStreams; @State AudioTracksWrapper wrappedAudioTracks; @State int selectedAudioTrackIndex; @State int selectedVideoIndex; // set in the constructor @State int selectedAudioIndex = 0; // default to the first item @State int selectedSubtitleIndex = 0; // default to the first item private StoredDirectoryHelper mainStorageAudio = null; private StoredDirectoryHelper mainStorageVideo = null; private DownloadManager downloadManager = null; private ActionMenuItemView okButton = null; private Context context = null; private boolean askForSavePath; private AudioTrackAdapter audioTrackAdapter; private StreamItemAdapter<AudioStream, Stream> audioStreamsAdapter; private StreamItemAdapter<VideoStream, AudioStream> videoStreamsAdapter; private StreamItemAdapter<SubtitlesStream, Stream> subtitleStreamsAdapter; private final CompositeDisposable disposables = new CompositeDisposable(); private DownloadDialogBinding dialogBinding; private SharedPreferences prefs; // Variables for file name and MIME type when picking new folder because it's not set yet private String filenameTmp; private String mimeTmp; private final ActivityResultLauncher<Intent> requestDownloadSaveAsLauncher = registerForActivityResult( new StartActivityForResult(), this::requestDownloadSaveAsResult); private final ActivityResultLauncher<Intent> requestDownloadPickAudioFolderLauncher = registerForActivityResult( new StartActivityForResult(), this::requestDownloadPickAudioFolderResult); private final ActivityResultLauncher<Intent> requestDownloadPickVideoFolderLauncher = registerForActivityResult( new StartActivityForResult(), this::requestDownloadPickVideoFolderResult); /*////////////////////////////////////////////////////////////////////////// // Instance creation //////////////////////////////////////////////////////////////////////////*/ public DownloadDialog() { // Just an empty default no-arg ctor to keep Fragment.instantiate() happy // otherwise InstantiationException will be thrown when fragment is recreated // TODO: Maybe use a custom FragmentFactory instead? } /** * Create a new download dialog with the video, audio and subtitle streams from the provided * stream info. Video streams and video-only streams will be put into a single list menu, * sorted according to their resolution and the default video resolution will be selected. * * @param context the context to use just to obtain preferences and strings (will not be stored) * @param info the info from which to obtain downloadable streams and other info (e.g. title) */ public DownloadDialog(@NonNull final Context context, @NonNull final StreamInfo info) { this.currentInfo = info; final List<AudioStream> audioStreams = getStreamsOfSpecifiedDelivery(info.getAudioStreams(), PROGRESSIVE_HTTP); final List<List<AudioStream>> groupedAudioStreams = ListHelper.getGroupedAudioStreams(context, audioStreams); this.wrappedAudioTracks = new AudioTracksWrapper(groupedAudioStreams, context); this.selectedAudioTrackIndex = ListHelper.getDefaultAudioTrackGroup(context, groupedAudioStreams); // TODO: Adapt this code when the downloader support other types of stream deliveries final List<VideoStream> videoStreams = ListHelper.getSortedStreamVideosList( context, getStreamsOfSpecifiedDelivery(info.getVideoStreams(), PROGRESSIVE_HTTP), getStreamsOfSpecifiedDelivery(info.getVideoOnlyStreams(), PROGRESSIVE_HTTP), false, // If there are multiple languages available, prefer streams without audio // to allow language selection wrappedAudioTracks.size() > 1 ); this.wrappedVideoStreams = new StreamInfoWrapper<>(videoStreams, context); this.wrappedSubtitleStreams = new StreamInfoWrapper<>( getStreamsOfSpecifiedDelivery(info.getSubtitles(), PROGRESSIVE_HTTP), context); this.selectedVideoIndex = ListHelper.getDefaultResolutionIndex(context, videoStreams); } /*////////////////////////////////////////////////////////////////////////// // Android lifecycle //////////////////////////////////////////////////////////////////////////*/ @Override public void onCreate(@Nullable final Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DEBUG) { Log.d(TAG, "onCreate() called with: " + "savedInstanceState = [" + savedInstanceState + "]"); } if (!PermissionHelper.checkStoragePermissions(getActivity(), PermissionHelper.DOWNLOAD_DIALOG_REQUEST_CODE)) { dismiss(); return; } // context will remain null if dismiss() was called above, allowing to check whether the // dialog is being dismissed in onViewCreated() context = getContext(); setStyle(STYLE_NO_TITLE, ThemeHelper.getDialogTheme(context)); Icepick.restoreInstanceState(this, savedInstanceState); this.audioTrackAdapter = new AudioTrackAdapter(wrappedAudioTracks); this.subtitleStreamsAdapter = new StreamItemAdapter<>(wrappedSubtitleStreams); updateSecondaryStreams(); final Intent intent = new Intent(context, DownloadManagerService.class); context.startService(intent); context.bindService(intent, new ServiceConnection() { @Override public void onServiceConnected(final ComponentName cname, final IBinder service) { final DownloadManagerBinder mgr = (DownloadManagerBinder) service; mainStorageAudio = mgr.getMainStorageAudio(); mainStorageVideo = mgr.getMainStorageVideo(); downloadManager = mgr.getDownloadManager(); askForSavePath = mgr.askForSavePath(); okButton.setEnabled(true); context.unbindService(this); } @Override public void onServiceDisconnected(final ComponentName name) { // nothing to do } }, Context.BIND_AUTO_CREATE); } /** * Update the displayed video streams based on the selected audio track. */ private void updateSecondaryStreams() { final StreamInfoWrapper<AudioStream> audioStreams = getWrappedAudioStreams(); final var secondaryStreams = new SparseArrayCompat<SecondaryStreamHelper<AudioStream>>(4); final List<VideoStream> videoStreams = wrappedVideoStreams.getStreamsList(); wrappedVideoStreams.resetInfo(); for (int i = 0; i < videoStreams.size(); i++) { if (!videoStreams.get(i).isVideoOnly()) { continue; } final AudioStream audioStream = SecondaryStreamHelper.getAudioStreamFor( context, audioStreams.getStreamsList(), videoStreams.get(i)); if (audioStream != null) { secondaryStreams.append(i, new SecondaryStreamHelper<>(audioStreams, audioStream)); } else if (DEBUG) { final MediaFormat mediaFormat = videoStreams.get(i).getFormat(); if (mediaFormat != null) { Log.w(TAG, "No audio stream candidates for video format " + mediaFormat.name()); } else { Log.w(TAG, "No audio stream candidates for unknown video format"); } } } this.videoStreamsAdapter = new StreamItemAdapter<>(wrappedVideoStreams, secondaryStreams); this.audioStreamsAdapter = new StreamItemAdapter<>(audioStreams); } @Override public View onCreateView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { if (DEBUG) { Log.d(TAG, "onCreateView() called with: " + "inflater = [" + inflater + "], container = [" + container + "], " + "savedInstanceState = [" + savedInstanceState + "]"); } return inflater.inflate(R.layout.download_dialog, container); } @Override public void onViewCreated(@NonNull final View view, @Nullable final Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); dialogBinding = DownloadDialogBinding.bind(view); if (context == null) { return; // the dialog is being dismissed, see the call to dismiss() in onCreate() } dialogBinding.fileName.setText(FilenameUtils.createFilename(getContext(), currentInfo.getName())); selectedAudioIndex = ListHelper.getDefaultAudioFormat(getContext(), getWrappedAudioStreams().getStreamsList()); selectedSubtitleIndex = getSubtitleIndexBy(subtitleStreamsAdapter.getAll()); dialogBinding.qualitySpinner.setOnItemSelectedListener(this); dialogBinding.audioStreamSpinner.setOnItemSelectedListener(this); dialogBinding.audioTrackSpinner.setOnItemSelectedListener(this); dialogBinding.videoAudioGroup.setOnCheckedChangeListener(this); initToolbar(dialogBinding.toolbarLayout.toolbar); setupDownloadOptions(); prefs = PreferenceManager.getDefaultSharedPreferences(requireContext()); final int threads = prefs.getInt(getString(R.string.default_download_threads), 3); dialogBinding.threadsCount.setText(String.valueOf(threads)); dialogBinding.threads.setProgress(threads - 1); dialogBinding.threads.setOnSeekBarChangeListener(new SimpleOnSeekBarChangeListener() { @Override public void onProgressChanged(@NonNull final SeekBar seekbar, final int progress, final boolean fromUser) { final int newProgress = progress + 1; prefs.edit().putInt(getString(R.string.default_download_threads), newProgress) .apply(); dialogBinding.threadsCount.setText(String.valueOf(newProgress)); } }); fetchStreamsSize(); } private void initToolbar(final Toolbar toolbar) { if (DEBUG) { Log.d(TAG, "initToolbar() called with: toolbar = [" + toolbar + "]"); } toolbar.setTitle(R.string.download_dialog_title); toolbar.setNavigationIcon(R.drawable.ic_arrow_back); toolbar.inflateMenu(R.menu.dialog_url); toolbar.setNavigationOnClickListener(v -> dismiss()); toolbar.setNavigationContentDescription(R.string.cancel); okButton = toolbar.findViewById(R.id.okay); okButton.setEnabled(false); // disable until the download service connection is done toolbar.setOnMenuItemClickListener(item -> { if (item.getItemId() == R.id.okay) { prepareSelectedDownload(); return true; } return false; }); } @Override public void onDestroy() { super.onDestroy(); disposables.clear(); } @Override public void onDestroyView() { dialogBinding = null; super.onDestroyView(); } @Override public void onSaveInstanceState(@NonNull final Bundle outState) { super.onSaveInstanceState(outState); Icepick.saveInstanceState(this, outState); } /*////////////////////////////////////////////////////////////////////////// // Video, audio and subtitle spinners //////////////////////////////////////////////////////////////////////////*/ private void fetchStreamsSize() { disposables.clear(); disposables.add(StreamInfoWrapper.fetchMoreInfoForWrapper(wrappedVideoStreams) .subscribe(result -> { if (dialogBinding.videoAudioGroup.getCheckedRadioButtonId() == R.id.video_button) { setupVideoSpinner(); } }, throwable -> ErrorUtil.showSnackbar(context, new ErrorInfo(throwable, UserAction.DOWNLOAD_OPEN_DIALOG, "Downloading video stream size", currentInfo.getServiceId())))); disposables.add(StreamInfoWrapper.fetchMoreInfoForWrapper(getWrappedAudioStreams()) .subscribe(result -> { if (dialogBinding.videoAudioGroup.getCheckedRadioButtonId() == R.id.audio_button) { setupAudioSpinner(); } }, throwable -> ErrorUtil.showSnackbar(context, new ErrorInfo(throwable, UserAction.DOWNLOAD_OPEN_DIALOG, "Downloading audio stream size", currentInfo.getServiceId())))); disposables.add(StreamInfoWrapper.fetchMoreInfoForWrapper(wrappedSubtitleStreams) .subscribe(result -> { if (dialogBinding.videoAudioGroup.getCheckedRadioButtonId() == R.id.subtitle_button) { setupSubtitleSpinner(); } }, throwable -> ErrorUtil.showSnackbar(context, new ErrorInfo(throwable, UserAction.DOWNLOAD_OPEN_DIALOG, "Downloading subtitle stream size", currentInfo.getServiceId())))); } private void setupAudioTrackSpinner() { if (getContext() == null) { return; } dialogBinding.audioTrackSpinner.setAdapter(audioTrackAdapter); dialogBinding.audioTrackSpinner.setSelection(selectedAudioTrackIndex); } private void setupAudioSpinner() { if (getContext() == null) { return; } dialogBinding.qualitySpinner.setVisibility(View.GONE); setRadioButtonsState(true); dialogBinding.audioStreamSpinner.setAdapter(audioStreamsAdapter); dialogBinding.audioStreamSpinner.setSelection(selectedAudioIndex); dialogBinding.audioStreamSpinner.setVisibility(View.VISIBLE); dialogBinding.audioTrackSpinner.setVisibility( wrappedAudioTracks.size() > 1 ? View.VISIBLE : View.GONE); dialogBinding.audioTrackPresentInVideoText.setVisibility(View.GONE); } private void setupVideoSpinner() { if (getContext() == null) { return; } dialogBinding.qualitySpinner.setAdapter(videoStreamsAdapter); dialogBinding.qualitySpinner.setSelection(selectedVideoIndex); dialogBinding.qualitySpinner.setVisibility(View.VISIBLE); setRadioButtonsState(true); dialogBinding.audioStreamSpinner.setVisibility(View.GONE); onVideoStreamSelected(); } private void onVideoStreamSelected() { final boolean isVideoOnly = videoStreamsAdapter.getItem(selectedVideoIndex).isVideoOnly(); dialogBinding.audioTrackSpinner.setVisibility( isVideoOnly && wrappedAudioTracks.size() > 1 ? View.VISIBLE : View.GONE); dialogBinding.audioTrackPresentInVideoText.setVisibility( !isVideoOnly && wrappedAudioTracks.size() > 1 ? View.VISIBLE : View.GONE); } private void setupSubtitleSpinner() { if (getContext() == null) { return; } dialogBinding.qualitySpinner.setAdapter(subtitleStreamsAdapter); dialogBinding.qualitySpinner.setSelection(selectedSubtitleIndex); dialogBinding.qualitySpinner.setVisibility(View.VISIBLE); setRadioButtonsState(true); dialogBinding.audioStreamSpinner.setVisibility(View.GONE); dialogBinding.audioTrackSpinner.setVisibility(View.GONE); dialogBinding.audioTrackPresentInVideoText.setVisibility(View.GONE); } /*////////////////////////////////////////////////////////////////////////// // Activity results //////////////////////////////////////////////////////////////////////////*/ private void requestDownloadPickAudioFolderResult(final ActivityResult result) { requestDownloadPickFolderResult( result, getString(R.string.download_path_audio_key), DownloadManager.TAG_AUDIO); } private void requestDownloadPickVideoFolderResult(final ActivityResult result) { requestDownloadPickFolderResult( result, getString(R.string.download_path_video_key), DownloadManager.TAG_VIDEO); } private void requestDownloadSaveAsResult(@NonNull final ActivityResult result) { if (result.getResultCode() != Activity.RESULT_OK) { return; } if (result.getData() == null || result.getData().getData() == null) { showFailedDialog(R.string.general_error); return; } if (FilePickerActivityHelper.isOwnFileUri(context, result.getData().getData())) { final File file = Utils.getFileForUri(result.getData().getData()); checkSelectedDownload(null, Uri.fromFile(file), file.getName(), StoredFileHelper.DEFAULT_MIME); return; } final DocumentFile docFile = DocumentFile.fromSingleUri(context, result.getData().getData()); if (docFile == null) { showFailedDialog(R.string.general_error); return; } // check if the selected file was previously used checkSelectedDownload(null, result.getData().getData(), docFile.getName(), docFile.getType()); } private void requestDownloadPickFolderResult(@NonNull final ActivityResult result, final String key, final String tag) { if (result.getResultCode() != Activity.RESULT_OK) { return; } if (result.getData() == null || result.getData().getData() == null) { showFailedDialog(R.string.general_error); return; } Uri uri = result.getData().getData(); if (FilePickerActivityHelper.isOwnFileUri(context, uri)) { uri = Uri.fromFile(Utils.getFileForUri(uri)); } else { context.grantUriPermission(context.getPackageName(), uri, StoredDirectoryHelper.PERMISSION_FLAGS); } PreferenceManager.getDefaultSharedPreferences(context).edit().putString(key, uri.toString()).apply(); try { final StoredDirectoryHelper mainStorage = new StoredDirectoryHelper(context, uri, tag); checkSelectedDownload(mainStorage, mainStorage.findFile(filenameTmp), filenameTmp, mimeTmp); } catch (final IOException e) { showFailedDialog(R.string.general_error); } } /*////////////////////////////////////////////////////////////////////////// // Listeners //////////////////////////////////////////////////////////////////////////*/ @Override public void onCheckedChanged(final RadioGroup group, @IdRes final int checkedId) { if (DEBUG) { Log.d(TAG, "onCheckedChanged() called with: " + "group = [" + group + "], checkedId = [" + checkedId + "]"); } boolean flag = true; switch (checkedId) { case R.id.audio_button: setupAudioSpinner(); break; case R.id.video_button: setupVideoSpinner(); break; case R.id.subtitle_button: setupSubtitleSpinner(); flag = false; break; } dialogBinding.threads.setEnabled(flag); } @Override public void onItemSelected(final AdapterView<?> parent, final View view, final int position, final long id) { if (DEBUG) { Log.d(TAG, "onItemSelected() called with: " + "parent = [" + parent + "], view = [" + view + "], " + "position = [" + position + "], id = [" + id + "]"); } switch (parent.getId()) { case R.id.quality_spinner: switch (dialogBinding.videoAudioGroup.getCheckedRadioButtonId()) { case R.id.video_button: selectedVideoIndex = position; onVideoStreamSelected(); break; case R.id.subtitle_button: selectedSubtitleIndex = position; break; } onItemSelectedSetFileName(); break; case R.id.audio_track_spinner: final boolean trackChanged = selectedAudioTrackIndex != position; selectedAudioTrackIndex = position; if (trackChanged) { updateSecondaryStreams(); fetchStreamsSize(); } break; case R.id.audio_stream_spinner: selectedAudioIndex = position; } } private void onItemSelectedSetFileName() { final String fileName = FilenameUtils.createFilename(getContext(), currentInfo.getName()); final String prevFileName = Optional.ofNullable(dialogBinding.fileName.getText()) .map(Object::toString) .orElse(""); if (prevFileName.isEmpty() || prevFileName.equals(fileName) || prevFileName.startsWith(getString(R.string.caption_file_name, fileName, ""))) { // only update the file name field if it was not edited by the user switch (dialogBinding.videoAudioGroup.getCheckedRadioButtonId()) { case R.id.audio_button: case R.id.video_button: if (!prevFileName.equals(fileName)) { // since the user might have switched between audio and video, the correct // text might already be in place, so avoid resetting the cursor position dialogBinding.fileName.setText(fileName); } break; case R.id.subtitle_button: final String setSubtitleLanguageCode = subtitleStreamsAdapter .getItem(selectedSubtitleIndex).getLanguageTag(); // this will reset the cursor position, which is bad UX, but it can't be avoided dialogBinding.fileName.setText(getString( R.string.caption_file_name, fileName, setSubtitleLanguageCode)); break; } } } @Override public void onNothingSelected(final AdapterView<?> parent) { } /*////////////////////////////////////////////////////////////////////////// // Download //////////////////////////////////////////////////////////////////////////*/ protected void setupDownloadOptions() { setRadioButtonsState(false); setupAudioTrackSpinner(); final boolean isVideoStreamsAvailable = videoStreamsAdapter.getCount() > 0; final boolean isAudioStreamsAvailable = audioStreamsAdapter.getCount() > 0; final boolean isSubtitleStreamsAvailable = subtitleStreamsAdapter.getCount() > 0; dialogBinding.audioButton.setVisibility(isAudioStreamsAvailable ? View.VISIBLE : View.GONE); dialogBinding.videoButton.setVisibility(isVideoStreamsAvailable ? View.VISIBLE : View.GONE); dialogBinding.subtitleButton.setVisibility(isSubtitleStreamsAvailable ? View.VISIBLE : View.GONE); prefs = PreferenceManager.getDefaultSharedPreferences(requireContext()); final String defaultMedia = prefs.getString(getString(R.string.last_used_download_type), getString(R.string.last_download_type_video_key)); if (isVideoStreamsAvailable && (defaultMedia.equals(getString(R.string.last_download_type_video_key)))) { dialogBinding.videoButton.setChecked(true); setupVideoSpinner(); } else if (isAudioStreamsAvailable && (defaultMedia.equals(getString(R.string.last_download_type_audio_key)))) { dialogBinding.audioButton.setChecked(true); setupAudioSpinner(); } else if (isSubtitleStreamsAvailable && (defaultMedia.equals(getString(R.string.last_download_type_subtitle_key)))) { dialogBinding.subtitleButton.setChecked(true); setupSubtitleSpinner(); } else if (isVideoStreamsAvailable) { dialogBinding.videoButton.setChecked(true); setupVideoSpinner(); } else if (isAudioStreamsAvailable) { dialogBinding.audioButton.setChecked(true); setupAudioSpinner(); } else if (isSubtitleStreamsAvailable) { dialogBinding.subtitleButton.setChecked(true); setupSubtitleSpinner(); } else { Toast.makeText(getContext(), R.string.no_streams_available_download, Toast.LENGTH_SHORT).show(); dismiss(); } } private void setRadioButtonsState(final boolean enabled) { dialogBinding.audioButton.setEnabled(enabled); dialogBinding.videoButton.setEnabled(enabled); dialogBinding.subtitleButton.setEnabled(enabled); } private StreamInfoWrapper<AudioStream> getWrappedAudioStreams() { if (selectedAudioTrackIndex < 0 || selectedAudioTrackIndex > wrappedAudioTracks.size()) { return StreamInfoWrapper.empty(); } return wrappedAudioTracks.getTracksList().get(selectedAudioTrackIndex); } private int getSubtitleIndexBy(@NonNull final List<SubtitlesStream> streams) { final Localization preferredLocalization = NewPipe.getPreferredLocalization(); int candidate = 0; for (int i = 0; i < streams.size(); i++) { final Locale streamLocale = streams.get(i).getLocale(); final boolean languageEquals = streamLocale.getLanguage() != null && preferredLocalization.getLanguageCode() != null && streamLocale.getLanguage() .equals(new Locale(preferredLocalization.getLanguageCode()).getLanguage()); final boolean countryEquals = streamLocale.getCountry() != null && streamLocale.getCountry().equals(preferredLocalization.getCountryCode()); if (languageEquals) { if (countryEquals) { return i; } candidate = i; } } return candidate; } @NonNull private String getNameEditText() { final String str = Objects.requireNonNull(dialogBinding.fileName.getText()).toString() .trim(); return FilenameUtils.createFilename(context, str.isEmpty() ? currentInfo.getName() : str); } private void showFailedDialog(@StringRes final int msg) { assureCorrectAppLanguage(requireContext()); new AlertDialog.Builder(context) .setTitle(R.string.general_error) .setMessage(msg) .setNegativeButton(getString(R.string.ok), null) .show(); } private void launchDirectoryPicker(final ActivityResultLauncher<Intent> launcher) { NoFileManagerSafeGuard.launchSafe(launcher, StoredDirectoryHelper.getPicker(context), TAG, context); } private void prepareSelectedDownload() { final StoredDirectoryHelper mainStorage; final MediaFormat format; final String selectedMediaType; final long size; // first, build the filename and get the output folder (if possible) // later, run a very very very large file checking logic filenameTmp = getNameEditText().concat("."); switch (dialogBinding.videoAudioGroup.getCheckedRadioButtonId()) { case R.id.audio_button: selectedMediaType = getString(R.string.last_download_type_audio_key); mainStorage = mainStorageAudio; format = audioStreamsAdapter.getItem(selectedAudioIndex).getFormat(); size = getWrappedAudioStreams().getSizeInBytes(selectedAudioIndex); if (format == MediaFormat.WEBMA_OPUS) { mimeTmp = "audio/ogg"; filenameTmp += "opus"; } else if (format != null) { mimeTmp = format.mimeType; filenameTmp += format.getSuffix(); } break; case R.id.video_button: selectedMediaType = getString(R.string.last_download_type_video_key); mainStorage = mainStorageVideo; format = videoStreamsAdapter.getItem(selectedVideoIndex).getFormat(); size = wrappedVideoStreams.getSizeInBytes(selectedVideoIndex); if (format != null) { mimeTmp = format.mimeType; filenameTmp += format.getSuffix(); } break; case R.id.subtitle_button: selectedMediaType = getString(R.string.last_download_type_subtitle_key); mainStorage = mainStorageVideo; // subtitle & video files go together format = subtitleStreamsAdapter.getItem(selectedSubtitleIndex).getFormat(); size = wrappedSubtitleStreams.getSizeInBytes(selectedSubtitleIndex); if (format != null) { mimeTmp = format.mimeType; } if (format == MediaFormat.TTML) { filenameTmp += MediaFormat.SRT.getSuffix(); } else if (format != null) { filenameTmp += format.getSuffix(); } break; default: throw new RuntimeException("No stream selected"); } if (!askForSavePath && (mainStorage == null || mainStorage.isDirect() == NewPipeSettings.useStorageAccessFramework(context) || mainStorage.isInvalidSafStorage())) { // Pick new download folder if one of: // - Download folder is not set // - Download folder uses SAF while SAF is disabled // - Download folder doesn't use SAF while SAF is enabled // - Download folder uses SAF but the user manually revoked access to it Toast.makeText(context, getString(R.string.no_dir_yet), Toast.LENGTH_LONG).show(); if (dialogBinding.videoAudioGroup.getCheckedRadioButtonId() == R.id.audio_button) { launchDirectoryPicker(requestDownloadPickAudioFolderLauncher); } else { launchDirectoryPicker(requestDownloadPickVideoFolderLauncher); } return; } if (askForSavePath) { final Uri initialPath; if (NewPipeSettings.useStorageAccessFramework(context)) { initialPath = null; } else { final File initialSavePath; if (dialogBinding.videoAudioGroup.getCheckedRadioButtonId() == R.id.audio_button) { initialSavePath = NewPipeSettings.getDir(Environment.DIRECTORY_MUSIC); } else { initialSavePath = NewPipeSettings.getDir(Environment.DIRECTORY_MOVIES); } initialPath = Uri.parse(initialSavePath.getAbsolutePath()); } NoFileManagerSafeGuard.launchSafe(requestDownloadSaveAsLauncher, StoredFileHelper.getNewPicker(context, filenameTmp, mimeTmp, initialPath), TAG, context); return; } // Check for free storage space final long freeSpace = mainStorage.getFreeStorageSpace(); if (freeSpace <= size) { Toast.makeText(context, getString(R. string.error_insufficient_storage), Toast.LENGTH_LONG).show(); // move the user to storage setting tab final Intent storageSettingsIntent = new Intent(Settings. ACTION_INTERNAL_STORAGE_SETTINGS); if (storageSettingsIntent.resolveActivity(context.getPackageManager()) != null) { startActivity(storageSettingsIntent); } return; } // check for existing file with the same name checkSelectedDownload(mainStorage, mainStorage.findFile(filenameTmp), filenameTmp, mimeTmp); // remember the last media type downloaded by the user prefs.edit().putString(getString(R.string.last_used_download_type), selectedMediaType) .apply(); } private void checkSelectedDownload(final StoredDirectoryHelper mainStorage, final Uri targetFile, final String filename, final String mime) { StoredFileHelper storage; try { if (mainStorage == null) { // using SAF on older android version storage = new StoredFileHelper(context, null, targetFile, ""); } else if (targetFile == null) { // the file does not exist, but it is probably used in a pending download storage = new StoredFileHelper(mainStorage.getUri(), filename, mime, mainStorage.getTag()); } else { // the target filename is already use, attempt to use it storage = new StoredFileHelper(context, mainStorage.getUri(), targetFile, mainStorage.getTag()); } } catch (final Exception e) { ErrorUtil.createNotification(requireContext(), new ErrorInfo(e, UserAction.DOWNLOAD_FAILED, "Getting storage")); return; } // get state of potential mission referring to the same file final MissionState state = downloadManager.checkForExistingMission(storage); @StringRes final int msgBtn; @StringRes final int msgBody; // this switch checks if there is already a mission referring to the same file switch (state) { case Finished: // there is already a finished mission msgBtn = R.string.overwrite; msgBody = R.string.overwrite_finished_warning; break; case Pending: msgBtn = R.string.overwrite; msgBody = R.string.download_already_pending; break; case PendingRunning: msgBtn = R.string.generate_unique_name; msgBody = R.string.download_already_running; break; case None: // there is no mission referring to the same file if (mainStorage == null) { // This part is called if: // * using SAF on older android version // * save path not defined // * if the file exists overwrite it, is not necessary ask if (!storage.existsAsFile() && !storage.create()) { showFailedDialog(R.string.error_file_creation); return; } continueSelectedDownload(storage); return; } else if (targetFile == null) { // This part is called if: // * the filename is not used in a pending/finished download // * the file does not exists, create if (!mainStorage.mkdirs()) { showFailedDialog(R.string.error_path_creation); return; } storage = mainStorage.createFile(filename, mime); if (storage == null || !storage.canWrite()) { showFailedDialog(R.string.error_file_creation); return; } continueSelectedDownload(storage); return; } msgBtn = R.string.overwrite; msgBody = R.string.overwrite_unrelated_warning; break; default: return; // unreachable } final AlertDialog.Builder askDialog = new AlertDialog.Builder(context) .setTitle(R.string.download_dialog_title) .setMessage(msgBody) .setNegativeButton(R.string.cancel, null); final StoredFileHelper finalStorage = storage; if (mainStorage == null) { // This part is called if: // * using SAF on older android version // * save path not defined switch (state) { case Pending: case Finished: askDialog.setPositiveButton(msgBtn, (dialog, which) -> { dialog.dismiss(); downloadManager.forgetMission(finalStorage); continueSelectedDownload(finalStorage); }); break; } askDialog.show(); return; } askDialog.setPositiveButton(msgBtn, (dialog, which) -> { dialog.dismiss(); StoredFileHelper storageNew; switch (state) { case Finished: case Pending: downloadManager.forgetMission(finalStorage); case None: if (targetFile == null) { storageNew = mainStorage.createFile(filename, mime); } else { try { // try take (or steal) the file storageNew = new StoredFileHelper(context, mainStorage.getUri(), targetFile, mainStorage.getTag()); } catch (final IOException e) { Log.e(TAG, "Failed to take (or steal) the file in " + targetFile.toString()); storageNew = null; } } if (storageNew != null && storageNew.canWrite()) { continueSelectedDownload(storageNew); } else { showFailedDialog(R.string.error_file_creation); } break; case PendingRunning: storageNew = mainStorage.createUniqueFile(filename, mime); if (storageNew == null) { showFailedDialog(R.string.error_file_creation); } else { continueSelectedDownload(storageNew); } break; } }); askDialog.show(); } private void continueSelectedDownload(@NonNull final StoredFileHelper storage) { if (!storage.canWrite()) { showFailedDialog(R.string.permission_denied); return; } // check if the selected file has to be overwritten, by simply checking its length try { if (storage.length() > 0) { storage.truncate(); } } catch (final IOException e) { Log.e(TAG, "Failed to truncate the file: " + storage.getUri().toString(), e); showFailedDialog(R.string.overwrite_failed); return; } final Stream selectedStream; Stream secondaryStream = null; final char kind; int threads = dialogBinding.threads.getProgress() + 1; final String[] urls; final List<MissionRecoveryInfo> recoveryInfo; String psName = null; String[] psArgs = null; long nearLength = 0; // more download logic: select muxer, subtitle converter, etc. switch (dialogBinding.videoAudioGroup.getCheckedRadioButtonId()) { case R.id.audio_button: kind = 'a'; selectedStream = audioStreamsAdapter.getItem(selectedAudioIndex); if (selectedStream.getFormat() == MediaFormat.M4A) { psName = Postprocessing.ALGORITHM_M4A_NO_DASH; } else if (selectedStream.getFormat() == MediaFormat.WEBMA_OPUS) { psName = Postprocessing.ALGORITHM_OGG_FROM_WEBM_DEMUXER; } break; case R.id.video_button: kind = 'v'; selectedStream = videoStreamsAdapter.getItem(selectedVideoIndex); final SecondaryStreamHelper<AudioStream> secondary = videoStreamsAdapter .getAllSecondary() .get(wrappedVideoStreams.getStreamsList().indexOf(selectedStream)); if (secondary != null) { secondaryStream = secondary.getStream(); if (selectedStream.getFormat() == MediaFormat.MPEG_4) { psName = Postprocessing.ALGORITHM_MP4_FROM_DASH_MUXER; } else { psName = Postprocessing.ALGORITHM_WEBM_MUXER; } final long videoSize = wrappedVideoStreams.getSizeInBytes( (VideoStream) selectedStream); // set nearLength, only, if both sizes are fetched or known. This probably // does not work on slow networks but is later updated in the downloader if (secondary.getSizeInBytes() > 0 && videoSize > 0) { nearLength = secondary.getSizeInBytes() + videoSize; } } break; case R.id.subtitle_button: threads = 1; // use unique thread for subtitles due small file size kind = 's'; selectedStream = subtitleStreamsAdapter.getItem(selectedSubtitleIndex); if (selectedStream.getFormat() == MediaFormat.TTML) { psName = Postprocessing.ALGORITHM_TTML_CONVERTER; psArgs = new String[] { selectedStream.getFormat().getSuffix(), "false" // ignore empty frames }; } break; default: return; } if (secondaryStream == null) { urls = new String[] { selectedStream.getContent() }; recoveryInfo = List.of(new MissionRecoveryInfo(selectedStream)); } else { if (secondaryStream.getDeliveryMethod() != PROGRESSIVE_HTTP) { throw new IllegalArgumentException("Unsupported stream delivery format" + secondaryStream.getDeliveryMethod()); } urls = new String[] { selectedStream.getContent(), secondaryStream.getContent() }; recoveryInfo = List.of( new MissionRecoveryInfo(selectedStream), new MissionRecoveryInfo(secondaryStream) ); } DownloadManagerService.startMission(context, urls, storage, kind, threads, currentInfo.getUrl(), psName, psArgs, nearLength, new ArrayList<>(recoveryInfo)); Toast.makeText(context, getString(R.string.download_has_started), Toast.LENGTH_SHORT).show(); dismiss(); } }
TeamNewPipe/NewPipe
app/src/main/java/org/schabi/newpipe/download/DownloadDialog.java
41,691
/* * This is the source code of Telegram for Android v. 6.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2020. */ package org.telegram.messenger.video; import android.annotation.SuppressLint; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BlendMode; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.RectF; import android.graphics.SurfaceTexture; import android.graphics.Typeface; import android.opengl.GLES11Ext; import android.opengl.GLES20; import android.opengl.GLES30; import android.opengl.GLUtils; import android.opengl.Matrix; import android.os.Build; import android.text.Layout; import android.text.SpannableString; import android.text.Spanned; import android.text.style.ReplacementSpan; import android.util.Log; import android.util.Pair; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.inputmethod.EditorInfo; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.exifinterface.media.ExifInterface; import com.google.zxing.common.detector.MathUtils; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.Bitmaps; import org.telegram.messenger.BuildVars; import org.telegram.messenger.Emoji; import org.telegram.messenger.FileLog; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MediaController; import org.telegram.messenger.MessageObject; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; import org.telegram.messenger.VideoEditedInfo; import org.telegram.tgnet.TLRPC; import org.telegram.ui.Components.AnimatedEmojiDrawable; import org.telegram.ui.Components.AnimatedEmojiSpan; import org.telegram.ui.Components.AnimatedFileDrawable; import org.telegram.ui.Components.BlurringShader; import org.telegram.ui.Components.EditTextEffects; import org.telegram.ui.Components.FilterShaders; import org.telegram.ui.Components.Paint.Views.EditTextOutline; import org.telegram.ui.Components.Paint.Views.LocationMarker; import org.telegram.ui.Components.Paint.Views.PaintTextOptionsView; import org.telegram.ui.Components.RLottieDrawable; import org.telegram.ui.Components.Rect; import org.telegram.ui.Stories.recorder.StoryEntry; import java.io.File; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.channels.FileChannel; import java.util.ArrayList; import javax.microedition.khronos.opengles.GL10; public class TextureRenderer { private FloatBuffer verticesBuffer; private FloatBuffer gradientVerticesBuffer; private FloatBuffer gradientTextureBuffer; private FloatBuffer textureBuffer; private FloatBuffer renderTextureBuffer; private FloatBuffer bitmapVerticesBuffer; private FloatBuffer blurVerticesBuffer; private FloatBuffer partsVerticesBuffer[]; private FloatBuffer partsTextureBuffer; private ArrayList<StoryEntry.Part> parts; private int[] partsTexture; private boolean useMatrixForImagePath; float[] bitmapData = { -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, }; private FilterShaders filterShaders; private String paintPath; private String blurPath; private String imagePath; private int imageWidth, imageHeight; private ArrayList<VideoEditedInfo.MediaEntity> mediaEntities; private ArrayList<AnimatedEmojiDrawable> emojiDrawables; private int originalWidth; private int originalHeight; private int transformedWidth; private int transformedHeight; private BlurringShader blur; private static final String VERTEX_SHADER = "uniform mat4 uMVPMatrix;\n" + "uniform mat4 uSTMatrix;\n" + "attribute vec4 aPosition;\n" + "attribute vec4 aTextureCoord;\n" + "varying vec2 vTextureCoord;\n" + "void main() {\n" + " gl_Position = uMVPMatrix * aPosition;\n" + " vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" + "}\n"; private static final String VERTEX_SHADER_300 = "#version 320 es\n" + "uniform mat4 uMVPMatrix;\n" + "uniform mat4 uSTMatrix;\n" + "in vec4 aPosition;\n" + "in vec4 aTextureCoord;\n" + "out vec2 vTextureCoord;\n" + "void main() {\n" + " gl_Position = uMVPMatrix * aPosition;\n" + " vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" + "}\n"; private static final String FRAGMENT_EXTERNAL_SHADER = "#extension GL_OES_EGL_image_external : require\n" + "precision highp float;\n" + "varying vec2 vTextureCoord;\n" + "uniform samplerExternalOES sTexture;\n" + "void main() {\n" + " gl_FragColor = texture2D(sTexture, vTextureCoord);" + "}\n"; private static final String FRAGMENT_SHADER = "precision highp float;\n" + "varying vec2 vTextureCoord;\n" + "uniform sampler2D sTexture;\n" + "void main() {\n" + " gl_FragColor = texture2D(sTexture, vTextureCoord);\n" + "}\n"; private static final String GRADIENT_FRAGMENT_SHADER = "precision highp float;\n" + "varying vec2 vTextureCoord;\n" + "uniform vec4 gradientTopColor;\n" + "uniform vec4 gradientBottomColor;\n" + "float interleavedGradientNoise(vec2 n) {\n" + " return fract(52.9829189 * fract(.06711056 * n.x + .00583715 * n.y));\n" + "}\n" + "void main() {\n" + " gl_FragColor = mix(gradientTopColor, gradientBottomColor, vTextureCoord.y + (.2 * interleavedGradientNoise(gl_FragCoord.xy) - .1));\n" + "}\n"; private int NUM_FILTER_SHADER = -1; private int NUM_EXTERNAL_SHADER = -1; private int NUM_GRADIENT_SHADER = -1; private float[] mMVPMatrix = new float[16]; private float[] mSTMatrix = new float[16]; private float[] mSTMatrixIdentity = new float[16]; private int mTextureID; private int[] mProgram; private int[] muMVPMatrixHandle; private int[] muSTMatrixHandle; private int[] maPositionHandle; private int[] maTextureHandle; private int gradientTopColorHandle, gradientBottomColorHandle; private int texSizeHandle; // todo: HDR handles private int simpleShaderProgram; private int simplePositionHandle; private int simpleInputTexCoordHandle; private int simpleSourceImageHandle; private int blurShaderProgram; private int blurPositionHandle; private int blurInputTexCoordHandle; private int blurBlurImageHandle; private int blurMaskImageHandle; private int[] paintTexture; private int[] stickerTexture; private Bitmap stickerBitmap; private Canvas stickerCanvas; private float videoFps; private int imageOrientation; private boolean blendEnabled; private boolean isPhoto; private boolean firstFrame = true; Path path; Paint xRefPaint; Paint textColorPaint; private final MediaController.CropState cropState; private int[] blurTexture; private int gradientTopColor, gradientBottomColor; public TextureRenderer( MediaController.SavedFilterState savedFilterState, String image, String paint, String blurtex, ArrayList<VideoEditedInfo.MediaEntity> entities, MediaController.CropState cropState, int w, int h, int originalWidth, int originalHeight, int rotation, float fps, boolean photo, Integer gradientTopColor, Integer gradientBottomColor, StoryEntry.HDRInfo hdrInfo, ArrayList<StoryEntry.Part> parts ) { isPhoto = photo; this.parts = parts; float[] texData = { 0.f, 0.f, 1.f, 0.f, 0.f, 1.f, 1.f, 1.f, }; if (BuildVars.LOGS_ENABLED) { FileLog.d("start textureRenderer w = " + w + " h = " + h + " r = " + rotation + " fps = " + fps); if (cropState != null) { FileLog.d("cropState px = " + cropState.cropPx + " py = " + cropState.cropPy + " cScale = " + cropState.cropScale + " cropRotate = " + cropState.cropRotate + " pw = " + cropState.cropPw + " ph = " + cropState.cropPh + " tw = " + cropState.transformWidth + " th = " + cropState.transformHeight + " tr = " + cropState.transformRotation + " mirror = " + cropState.mirrored); } } textureBuffer = ByteBuffer.allocateDirect(texData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer(); textureBuffer.put(texData).position(0); bitmapVerticesBuffer = ByteBuffer.allocateDirect(bitmapData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer(); bitmapVerticesBuffer.put(bitmapData).position(0); Matrix.setIdentityM(mSTMatrix, 0); Matrix.setIdentityM(mSTMatrixIdentity, 0); if (savedFilterState != null) { filterShaders = new FilterShaders(true, hdrInfo); filterShaders.setDelegate(FilterShaders.getFilterShadersDelegate(savedFilterState)); } transformedWidth = w; transformedHeight = h; this.originalWidth = originalWidth; this.originalHeight = originalHeight; imagePath = image; paintPath = paint; blurPath = blurtex; mediaEntities = entities; videoFps = fps == 0 ? 30 : fps; this.cropState = cropState; int count = 0; NUM_EXTERNAL_SHADER = count++; if (gradientBottomColor != null && gradientTopColor != null) { NUM_GRADIENT_SHADER = count++; } if (filterShaders != null) { NUM_FILTER_SHADER = count++; } mProgram = new int[count]; muMVPMatrixHandle = new int[count]; muSTMatrixHandle = new int[count]; maPositionHandle = new int[count]; maTextureHandle = new int[count]; Matrix.setIdentityM(mMVPMatrix, 0); int textureRotation = 0; if (gradientBottomColor != null && gradientTopColor != null) { final float[] verticesData = { -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f }; gradientVerticesBuffer = ByteBuffer.allocateDirect(verticesData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer(); gradientVerticesBuffer.put(verticesData).position(0); final float[] textureData = { 0, isPhoto ? 1 : 0, 1, isPhoto ? 1 : 0, 0, isPhoto ? 0 : 1, 1, isPhoto ? 0 : 1 }; gradientTextureBuffer = ByteBuffer.allocateDirect(textureData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer(); gradientTextureBuffer.put(textureData).position(0); this.gradientTopColor = gradientTopColor; this.gradientBottomColor = gradientBottomColor; } if (cropState != null) { if (cropState.useMatrix != null) { useMatrixForImagePath = true; float[] verticesData = { 0, 0, originalWidth, 0, 0, originalHeight, originalWidth, originalHeight }; cropState.useMatrix.mapPoints(verticesData); for (int a = 0; a < 4; a++) { verticesData[a * 2] = verticesData[a * 2] / w * 2f - 1f; verticesData[a * 2 + 1] = 1f - verticesData[a * 2 + 1] / h * 2f; } verticesBuffer = ByteBuffer.allocateDirect(verticesData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer(); verticesBuffer.put(verticesData).position(0); } else { float[] verticesData = { 0, 0, w, 0, 0, h, w, h, }; textureRotation = cropState.transformRotation; transformedWidth *= cropState.cropPw; transformedHeight *= cropState.cropPh; float angle = (float) (-cropState.cropRotate * (Math.PI / 180.0f)); for (int a = 0; a < 4; a++) { float x1 = verticesData[a * 2] - w / 2; float y1 = verticesData[a * 2 + 1] - h / 2; float x2 = (float) (x1 * Math.cos(angle) - y1 * Math.sin(angle) + cropState.cropPx * w) * cropState.cropScale; float y2 = (float) (x1 * Math.sin(angle) + y1 * Math.cos(angle) - cropState.cropPy * h) * cropState.cropScale; verticesData[a * 2] = x2 / transformedWidth * 2; verticesData[a * 2 + 1] = y2 / transformedHeight * 2; } verticesBuffer = ByteBuffer.allocateDirect(verticesData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer(); verticesBuffer.put(verticesData).position(0); } } else { float[] verticesData = { -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, }; verticesBuffer = ByteBuffer.allocateDirect(verticesData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer(); verticesBuffer.put(verticesData).position(0); } float[] textureData; if (filterShaders != null) { if (textureRotation == 90) { textureData = new float[]{ 1.f, 1.f, 1.f, 0.f, 0.f, 1.f, 0.f, 0.f }; } else if (textureRotation == 180) { textureData = new float[]{ 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f }; } else if (textureRotation == 270) { textureData = new float[]{ 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f }; } else { textureData = new float[]{ 0.f, 1.f, 1.f, 1.f, 0.f, 0.f, 1.f, 0.f }; } } else { if (textureRotation == 90) { textureData = new float[]{ 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f }; } else if (textureRotation == 180) { textureData = new float[]{ 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f }; } else if (textureRotation == 270) { textureData = new float[]{ 0.f, 1.f, 0.f, 0.f, 1.f, 1.f, 1.f, 0.f }; } else { textureData = new float[]{ 0.f, 0.f, 1.f, 0.f, 0.f, 1.f, 1.f, 1.f }; } } if (!isPhoto && useMatrixForImagePath) { textureData[1] = 1f - textureData[1]; textureData[3] = 1f - textureData[3]; textureData[5] = 1f - textureData[5]; textureData[7] = 1f - textureData[7]; } if (cropState != null && cropState.mirrored) { for (int a = 0; a < 4; a++) { if (textureData[a * 2] > 0.5f) { textureData[a * 2] = 0.0f; } else { textureData[a * 2] = 1.0f; } } } renderTextureBuffer = ByteBuffer.allocateDirect(textureData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer(); renderTextureBuffer.put(textureData).position(0); } public int getTextureId() { return mTextureID; } private void drawGradient() { if (NUM_GRADIENT_SHADER < 0) { return; } GLES20.glUseProgram(mProgram[NUM_GRADIENT_SHADER]); GLES20.glVertexAttribPointer(maPositionHandle[NUM_GRADIENT_SHADER], 2, GLES20.GL_FLOAT, false, 8, gradientVerticesBuffer); GLES20.glEnableVertexAttribArray(maPositionHandle[NUM_GRADIENT_SHADER]); GLES20.glVertexAttribPointer(maTextureHandle[NUM_GRADIENT_SHADER], 2, GLES20.GL_FLOAT, false, 8, gradientTextureBuffer); GLES20.glEnableVertexAttribArray(maTextureHandle[NUM_GRADIENT_SHADER]); GLES20.glUniformMatrix4fv(muSTMatrixHandle[NUM_GRADIENT_SHADER], 1, false, mSTMatrix, 0); GLES20.glUniformMatrix4fv(muMVPMatrixHandle[NUM_GRADIENT_SHADER], 1, false, mMVPMatrix, 0); GLES20.glUniform4f(gradientTopColorHandle, Color.red(gradientTopColor) / 255f, Color.green(gradientTopColor) / 255f, Color.blue(gradientTopColor) / 255f, Color.alpha(gradientTopColor) / 255f); GLES20.glUniform4f(gradientBottomColorHandle, Color.red(gradientBottomColor) / 255f, Color.green(gradientBottomColor) / 255f, Color.blue(gradientBottomColor) / 255f, Color.alpha(gradientBottomColor) / 255f); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); } public void drawFrame(SurfaceTexture st) { boolean blurred = false; if (isPhoto) { drawGradient(); } else { st.getTransformMatrix(mSTMatrix); if (BuildVars.LOGS_ENABLED && firstFrame) { StringBuilder builder = new StringBuilder(); for (int a = 0; a < mSTMatrix.length; a++) { builder.append(mSTMatrix[a]).append(", "); } FileLog.d("stMatrix = " + builder); firstFrame = false; } if (blendEnabled) { GLES20.glDisable(GLES20.GL_BLEND); blendEnabled = false; } int texture; int target; int index; float[] stMatrix; if (filterShaders != null) { filterShaders.onVideoFrameUpdate(mSTMatrix); GLES20.glViewport(0, 0, originalWidth, originalHeight); filterShaders.drawSkinSmoothPass(); filterShaders.drawEnhancePass(); filterShaders.drawSharpenPass(); filterShaders.drawCustomParamsPass(); blurred = filterShaders.drawBlurPass(); GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0); if (transformedWidth != originalWidth || transformedHeight != originalHeight) { GLES20.glViewport(0, 0, transformedWidth, transformedHeight); } texture = filterShaders.getRenderTexture(blurred ? 0 : 1); index = NUM_FILTER_SHADER; target = GLES20.GL_TEXTURE_2D; stMatrix = mSTMatrixIdentity; } else { texture = mTextureID; index = NUM_EXTERNAL_SHADER; target = GLES11Ext.GL_TEXTURE_EXTERNAL_OES; stMatrix = mSTMatrix; } drawGradient(); GLES20.glUseProgram(mProgram[index]); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture(target, texture); GLES20.glVertexAttribPointer(maPositionHandle[index], 2, GLES20.GL_FLOAT, false, 8, verticesBuffer); GLES20.glEnableVertexAttribArray(maPositionHandle[index]); GLES20.glVertexAttribPointer(maTextureHandle[index], 2, GLES20.GL_FLOAT, false, 8, renderTextureBuffer); GLES20.glEnableVertexAttribArray(maTextureHandle[index]); if (texSizeHandle != 0) { GLES20.glUniform2f(texSizeHandle, transformedWidth, transformedHeight); } GLES20.glUniformMatrix4fv(muSTMatrixHandle[index], 1, false, stMatrix, 0); GLES20.glUniformMatrix4fv(muMVPMatrixHandle[index], 1, false, mMVPMatrix, 0); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); } if (blur != null) { if (!blendEnabled) { GLES20.glEnable(GLES20.GL_BLEND); GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE_MINUS_SRC_ALPHA); blendEnabled = true; } int tex = -1, w = 1, h = 1; if (imagePath != null && paintTexture != null) { tex = paintTexture[0]; w = imageWidth; h = imageHeight; } else if (filterShaders != null) { tex = filterShaders.getRenderTexture(blurred ? 0 : 1); w = filterShaders.getRenderBufferWidth(); h = filterShaders.getRenderBufferHeight(); } if (tex != -1) { blur.draw(null, tex, w, h); GLES20.glViewport(0, 0, transformedWidth, transformedHeight); GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0); GLES20.glUseProgram(blurShaderProgram); GLES20.glEnableVertexAttribArray(blurInputTexCoordHandle); GLES20.glVertexAttribPointer(blurInputTexCoordHandle, 2, GLES20.GL_FLOAT, false, 8, gradientTextureBuffer); GLES20.glEnableVertexAttribArray(blurPositionHandle); GLES20.glVertexAttribPointer(blurPositionHandle, 2, GLES20.GL_FLOAT, false, 8, blurVerticesBuffer); GLES20.glUniform1i(blurBlurImageHandle, 0); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, blur.getTexture()); GLES20.glUniform1i(blurMaskImageHandle, 1); GLES20.glActiveTexture(GLES20.GL_TEXTURE1); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, blurTexture[0]); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); } } if (isPhoto || paintTexture != null || stickerTexture != null || partsTexture != null) { GLES20.glUseProgram(simpleShaderProgram); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glUniform1i(simpleSourceImageHandle, 0); GLES20.glEnableVertexAttribArray(simpleInputTexCoordHandle); GLES20.glVertexAttribPointer(simpleInputTexCoordHandle, 2, GLES20.GL_FLOAT, false, 8, textureBuffer); GLES20.glEnableVertexAttribArray(simplePositionHandle); } if (paintTexture != null && imagePath != null) { for (int a = 0; a < 1; a++) { drawTexture(true, paintTexture[a], -10000, -10000, -10000, -10000, 0, false, useMatrixForImagePath && isPhoto && a == 0, -1); } } if (partsTexture != null) { for (int a = 0; a < partsTexture.length; a++) { drawTexture(true, partsTexture[a], -10000, -10000, -10000, -10000, 0, false, false, a); } } if (paintTexture != null) { for (int a = (imagePath != null ? 1 : 0); a < paintTexture.length; a++) { drawTexture(true, paintTexture[a], -10000, -10000, -10000, -10000, 0, false, useMatrixForImagePath && isPhoto && a == 0, -1); } } if (stickerTexture != null) { for (int a = 0, N = mediaEntities.size(); a < N; a++) { drawEntity(mediaEntities.get(a), mediaEntities.get(a).color); } } GLES20.glFinish(); } private void drawEntity(VideoEditedInfo.MediaEntity entity, int textColor) { if (entity.ptr != 0) { if (entity.bitmap == null || entity.W <= 0 || entity.H <= 0) { return; } RLottieDrawable.getFrame(entity.ptr, (int) entity.currentFrame, entity.bitmap, entity.W, entity.H, entity.bitmap.getRowBytes(), true); applyRoundRadius(entity, entity.bitmap, (entity.subType & 8) != 0 ? textColor : 0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, stickerTexture[0]); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, entity.bitmap, 0); entity.currentFrame += entity.framesPerDraw; if (entity.currentFrame >= entity.metadata[0]) { entity.currentFrame = 0; } drawTexture(false, stickerTexture[0], entity.x, entity.y, entity.width, entity.height, entity.rotation, (entity.subType & 2) != 0); } else if (entity.animatedFileDrawable != null) { int lastFrame = (int) entity.currentFrame; entity.currentFrame += entity.framesPerDraw; int currentFrame = (int) entity.currentFrame; while (lastFrame != currentFrame) { entity.animatedFileDrawable.getNextFrame(); currentFrame--; } Bitmap frameBitmap = entity.animatedFileDrawable.getBackgroundBitmap(); if (frameBitmap != null) { if (stickerCanvas == null && stickerBitmap != null) { stickerCanvas = new Canvas(stickerBitmap); if (stickerBitmap.getHeight() != frameBitmap.getHeight() || stickerBitmap.getWidth() != frameBitmap.getWidth()) { stickerCanvas.scale(stickerBitmap.getWidth() / (float) frameBitmap.getWidth(), stickerBitmap.getHeight() / (float) frameBitmap.getHeight()); } } if (stickerBitmap != null) { stickerBitmap.eraseColor(Color.TRANSPARENT); stickerCanvas.drawBitmap(frameBitmap, 0, 0, null); applyRoundRadius(entity, stickerBitmap, (entity.subType & 8) != 0 ? textColor : 0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, stickerTexture[0]); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, stickerBitmap, 0); drawTexture(false, stickerTexture[0], entity.x, entity.y, entity.width, entity.height, entity.rotation, (entity.subType & 2) != 0); } } } else { if (entity.bitmap != null) { GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, stickerTexture[0]); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, entity.bitmap, 0); drawTexture(false, stickerTexture[0], entity.x - entity.additionalWidth / 2f, entity.y - entity.additionalHeight / 2f, entity.width + entity.additionalWidth, entity.height + entity.additionalHeight, entity.rotation, entity.type == VideoEditedInfo.MediaEntity.TYPE_PHOTO && (entity.subType & 2) != 0); } if (entity.entities != null && !entity.entities.isEmpty()) { for (int i = 0; i < entity.entities.size(); ++i) { VideoEditedInfo.EmojiEntity e = entity.entities.get(i); if (e == null) { continue; } VideoEditedInfo.MediaEntity entity1 = e.entity; if (entity1 == null) { continue; } drawEntity(entity1, entity.color); } } } } private void applyRoundRadius(VideoEditedInfo.MediaEntity entity, Bitmap stickerBitmap, int color) { if (stickerBitmap == null || entity == null || entity.roundRadius == 0 && color == 0) { return; } if (entity.roundRadiusCanvas == null) { entity.roundRadiusCanvas = new Canvas(stickerBitmap); } if (entity.roundRadius != 0) { if (path == null) { path = new Path(); } if (xRefPaint == null) { xRefPaint = new Paint(Paint.ANTI_ALIAS_FLAG); xRefPaint.setColor(0xff000000); xRefPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); } float rad = Math.min(stickerBitmap.getWidth(), stickerBitmap.getHeight()) * entity.roundRadius; path.rewind(); RectF rect = new RectF(0, 0, stickerBitmap.getWidth(), stickerBitmap.getHeight()); path.addRoundRect(rect, rad, rad, Path.Direction.CCW); path.toggleInverseFillType(); entity.roundRadiusCanvas.drawPath(path, xRefPaint); } if (color != 0) { if (textColorPaint == null) { textColorPaint = new Paint(Paint.ANTI_ALIAS_FLAG); textColorPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); } textColorPaint.setColor(color); entity.roundRadiusCanvas.drawRect(0, 0, stickerBitmap.getWidth(), stickerBitmap.getHeight(), textColorPaint); } } private void drawTexture(boolean bind, int texture) { drawTexture(bind, texture, -10000, -10000, -10000, -10000, 0, false); } private void drawTexture(boolean bind, int texture, float x, float y, float w, float h, float rotation, boolean mirror) { drawTexture(bind, texture, x, y, w, h, rotation, mirror, false, -1); } private void drawTexture(boolean bind, int texture, float x, float y, float w, float h, float rotation, boolean mirror, boolean useCropMatrix, int matrixIndex) { if (!blendEnabled) { GLES20.glEnable(GLES20.GL_BLEND); GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE_MINUS_SRC_ALPHA); blendEnabled = true; } if (x <= -10000) { bitmapData[0] = -1.0f; bitmapData[1] = 1.0f; bitmapData[2] = 1.0f; bitmapData[3] = 1.0f; bitmapData[4] = -1.0f; bitmapData[5] = -1.0f; bitmapData[6] = 1.0f; bitmapData[7] = -1.0f; } else { x = x * 2 - 1.0f; y = (1.0f - y) * 2 - 1.0f; w = w * 2; h = h * 2; bitmapData[0] = x; bitmapData[1] = y; bitmapData[2] = x + w; bitmapData[3] = y; bitmapData[4] = x; bitmapData[5] = y - h; bitmapData[6] = x + w; bitmapData[7] = y - h; } float mx = (bitmapData[0] + bitmapData[2]) / 2; if (mirror) { float temp = bitmapData[2]; bitmapData[2] = bitmapData[0]; bitmapData[0] = temp; temp = bitmapData[6]; bitmapData[6] = bitmapData[4]; bitmapData[4] = temp; } if (rotation != 0) { float ratio = transformedWidth / (float) transformedHeight; float my = (bitmapData[5] + bitmapData[1]) / 2; for (int a = 0; a < 4; a++) { float x1 = bitmapData[a * 2 ] - mx; float y1 = (bitmapData[a * 2 + 1] - my) / ratio; bitmapData[a * 2 ] = (float) (x1 * Math.cos(rotation) - y1 * Math.sin(rotation)) + mx; bitmapData[a * 2 + 1] = (float) (x1 * Math.sin(rotation) + y1 * Math.cos(rotation)) * ratio + my; } } bitmapVerticesBuffer.put(bitmapData).position(0); GLES20.glVertexAttribPointer(simplePositionHandle, 2, GLES20.GL_FLOAT, false, 8, matrixIndex >= 0 ? partsVerticesBuffer[matrixIndex] : (useCropMatrix ? verticesBuffer : bitmapVerticesBuffer)); GLES20.glEnableVertexAttribArray(simpleInputTexCoordHandle); GLES20.glVertexAttribPointer(simpleInputTexCoordHandle, 2, GLES20.GL_FLOAT, false, 8, matrixIndex >= 0 ? partsTextureBuffer : (useCropMatrix ? renderTextureBuffer : textureBuffer)); if (bind) { GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture); } GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); } @RequiresApi(api = Build.VERSION_CODES.M) public void setBreakStrategy(EditTextOutline editText) { editText.setBreakStrategy(Layout.BREAK_STRATEGY_SIMPLE); } @SuppressLint("WrongConstant") public void surfaceCreated() { for (int a = 0; a < mProgram.length; a++) { String shader = null; if (a == NUM_EXTERNAL_SHADER) { shader = FRAGMENT_EXTERNAL_SHADER; } else if (a == NUM_FILTER_SHADER) { shader = FRAGMENT_SHADER; } else if (a == NUM_GRADIENT_SHADER) { shader = GRADIENT_FRAGMENT_SHADER; } if (shader == null) { continue; } mProgram[a] = createProgram(VERTEX_SHADER, shader, false); maPositionHandle[a] = GLES20.glGetAttribLocation(mProgram[a], "aPosition"); maTextureHandle[a] = GLES20.glGetAttribLocation(mProgram[a], "aTextureCoord"); muMVPMatrixHandle[a] = GLES20.glGetUniformLocation(mProgram[a], "uMVPMatrix"); muSTMatrixHandle[a] = GLES20.glGetUniformLocation(mProgram[a], "uSTMatrix"); if (a == NUM_GRADIENT_SHADER) { gradientTopColorHandle = GLES20.glGetUniformLocation(mProgram[a], "gradientTopColor"); gradientBottomColorHandle = GLES20.glGetUniformLocation(mProgram[a], "gradientBottomColor"); } } int[] textures = new int[1]; GLES20.glGenTextures(1, textures, 0); mTextureID = textures[0]; GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTextureID); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); if (blurPath != null && cropState != null && cropState.useMatrix != null) { blur = new BlurringShader(); if (!blur.setup(transformedWidth / (float) transformedHeight, true, 0)) { blur = null; } else { blur.updateGradient(gradientTopColor, gradientBottomColor); android.graphics.Matrix matrix = new android.graphics.Matrix(); matrix.postScale(originalWidth, originalHeight); matrix.postConcat(cropState.useMatrix); matrix.postScale(1f / transformedWidth, 1f / transformedHeight); android.graphics.Matrix imatrix = new android.graphics.Matrix(); matrix.invert(imatrix); blur.updateTransform(imatrix); } Bitmap bitmap = BitmapFactory.decodeFile(blurPath); if (bitmap != null) { blurTexture = new int[1]; GLES20.glGenTextures(1, blurTexture, 0); GLES20.glBindTexture(GL10.GL_TEXTURE_2D, blurTexture[0]); GLES20.glTexParameteri(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR); GLES20.glTexParameteri(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); GLES20.glTexParameteri(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); } else { blur = null; } if (blur != null) { final String fragShader = "varying highp vec2 vTextureCoord;" + "uniform sampler2D blurImage;" + "uniform sampler2D maskImage;" + "void main() {" + "gl_FragColor = texture2D(blurImage, vTextureCoord) * texture2D(maskImage, vTextureCoord).a;" + "}"; int vertexShader = FilterShaders.loadShader(GLES20.GL_VERTEX_SHADER, FilterShaders.simpleVertexShaderCode); int fragmentShader = FilterShaders.loadShader(GLES20.GL_FRAGMENT_SHADER, fragShader); if (vertexShader != 0 && fragmentShader != 0) { blurShaderProgram = GLES20.glCreateProgram(); GLES20.glAttachShader(blurShaderProgram, vertexShader); GLES20.glAttachShader(blurShaderProgram, fragmentShader); GLES20.glBindAttribLocation(blurShaderProgram, 0, "position"); GLES20.glBindAttribLocation(blurShaderProgram, 1, "inputTexCoord"); GLES20.glLinkProgram(blurShaderProgram); int[] linkStatus = new int[1]; GLES20.glGetProgramiv(blurShaderProgram, GLES20.GL_LINK_STATUS, linkStatus, 0); if (linkStatus[0] == 0) { GLES20.glDeleteProgram(blurShaderProgram); blurShaderProgram = 0; } else { blurPositionHandle = GLES20.glGetAttribLocation(blurShaderProgram, "position"); blurInputTexCoordHandle = GLES20.glGetAttribLocation(blurShaderProgram, "inputTexCoord"); blurBlurImageHandle = GLES20.glGetUniformLocation(blurShaderProgram, "blurImage"); blurMaskImageHandle = GLES20.glGetUniformLocation(blurShaderProgram, "maskImage"); float[] verticesData = { -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, }; blurVerticesBuffer = ByteBuffer.allocateDirect(verticesData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer(); blurVerticesBuffer.put(verticesData).position(0); } } else { blur = null; } } } if (filterShaders != null || imagePath != null || paintPath != null || mediaEntities != null || parts != null) { int vertexShader = FilterShaders.loadShader(GLES20.GL_VERTEX_SHADER, FilterShaders.simpleVertexShaderCode); int fragmentShader = FilterShaders.loadShader(GLES20.GL_FRAGMENT_SHADER, FilterShaders.simpleFragmentShaderCode); if (vertexShader != 0 && fragmentShader != 0) { simpleShaderProgram = GLES20.glCreateProgram(); GLES20.glAttachShader(simpleShaderProgram, vertexShader); GLES20.glAttachShader(simpleShaderProgram, fragmentShader); GLES20.glBindAttribLocation(simpleShaderProgram, 0, "position"); GLES20.glBindAttribLocation(simpleShaderProgram, 1, "inputTexCoord"); GLES20.glLinkProgram(simpleShaderProgram); int[] linkStatus = new int[1]; GLES20.glGetProgramiv(simpleShaderProgram, GLES20.GL_LINK_STATUS, linkStatus, 0); if (linkStatus[0] == 0) { GLES20.glDeleteProgram(simpleShaderProgram); simpleShaderProgram = 0; } else { simplePositionHandle = GLES20.glGetAttribLocation(simpleShaderProgram, "position"); simpleInputTexCoordHandle = GLES20.glGetAttribLocation(simpleShaderProgram, "inputTexCoord"); simpleSourceImageHandle = GLES20.glGetUniformLocation(simpleShaderProgram, "sTexture"); } } } if (filterShaders != null) { filterShaders.create(); filterShaders.setRenderData(null, 0, mTextureID, originalWidth, originalHeight); } if (imagePath != null || paintPath != null) { paintTexture = new int[(imagePath != null ? 1 : 0) + (paintPath != null ? 1 : 0)]; GLES20.glGenTextures(paintTexture.length, paintTexture, 0); try { for (int a = 0; a < paintTexture.length; a++) { String path; int angle = 0, invert = 0; if (a == 0 && imagePath != null) { path = imagePath; Pair<Integer, Integer> orientation = AndroidUtilities.getImageOrientation(path); angle = orientation.first; invert = orientation.second; } else { path = paintPath; } Bitmap bitmap = BitmapFactory.decodeFile(path); if (bitmap != null) { if (a == 0 && imagePath != null && !useMatrixForImagePath) { Bitmap newBitmap = Bitmap.createBitmap(transformedWidth, transformedHeight, Bitmap.Config.ARGB_8888); newBitmap.eraseColor(0xff000000); Canvas canvas = new Canvas(newBitmap); float scale; if (angle == 90 || angle == 270) { scale = Math.max(bitmap.getHeight() / (float) transformedWidth, bitmap.getWidth() / (float) transformedHeight); } else { scale = Math.max(bitmap.getWidth() / (float) transformedWidth, bitmap.getHeight() / (float) transformedHeight); } android.graphics.Matrix matrix = new android.graphics.Matrix(); matrix.postTranslate(-bitmap.getWidth() / 2, -bitmap.getHeight() / 2); matrix.postScale((invert == 1 ? -1.0f : 1.0f) / scale, (invert == 2 ? -1.0f : 1.0f) / scale); matrix.postRotate(angle); matrix.postTranslate(newBitmap.getWidth() / 2, newBitmap.getHeight() / 2); canvas.drawBitmap(bitmap, matrix, new Paint(Paint.FILTER_BITMAP_FLAG)); bitmap = newBitmap; } if (a == 0 && imagePath != null) { imageWidth = bitmap.getWidth(); imageHeight = bitmap.getHeight(); } GLES20.glBindTexture(GL10.GL_TEXTURE_2D, paintTexture[a]); GLES20.glTexParameteri(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR); GLES20.glTexParameteri(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); GLES20.glTexParameteri(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); } } } catch (Throwable e) { FileLog.e(e); } } if (parts != null && !parts.isEmpty()) { partsTexture = new int[parts.size()]; partsVerticesBuffer = new FloatBuffer[parts.size()]; GLES20.glGenTextures(partsTexture.length, partsTexture, 0); try { for (int a = 0; a < partsTexture.length; a++) { StoryEntry.Part part = parts.get(a); String path = part.file.getAbsolutePath(); BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, opts); opts.inJustDecodeBounds = false; opts.inSampleSize = StoryEntry.calculateInSampleSize(opts, transformedWidth, transformedHeight); Bitmap bitmap = BitmapFactory.decodeFile(path, opts); GLES20.glBindTexture(GL10.GL_TEXTURE_2D, partsTexture[a]); GLES20.glTexParameteri(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR); GLES20.glTexParameteri(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); GLES20.glTexParameteri(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); final float[] verticesData = { 0, 0, part.width, 0, 0, part.height, part.width, part.height }; part.matrix.mapPoints(verticesData); for (int i = 0; i < 4; i++) { verticesData[i * 2] = verticesData[i * 2] / transformedWidth * 2f - 1f; verticesData[i * 2 + 1] = 1f - verticesData[i * 2 + 1] / transformedHeight * 2f; } partsVerticesBuffer[a] = ByteBuffer.allocateDirect(verticesData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer(); partsVerticesBuffer[a].put(verticesData).position(0); } } catch (Throwable e2) { FileLog.e(e2); } final float[] textureData = { 0, 0, 1f, 0, 0, 1f, 1f, 1f }; partsTextureBuffer = ByteBuffer.allocateDirect(textureData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer(); partsTextureBuffer.put(textureData).position(0); } if (mediaEntities != null) { try { stickerBitmap = Bitmap.createBitmap(512, 512, Bitmap.Config.ARGB_8888); stickerTexture = new int[1]; GLES20.glGenTextures(1, stickerTexture, 0); GLES20.glBindTexture(GL10.GL_TEXTURE_2D, stickerTexture[0]); GLES20.glTexParameteri(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR); GLES20.glTexParameteri(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); GLES20.glTexParameteri(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); for (int a = 0, N = mediaEntities.size(); a < N; a++) { VideoEditedInfo.MediaEntity entity = mediaEntities.get(a); if (entity.type == VideoEditedInfo.MediaEntity.TYPE_STICKER || entity.type == VideoEditedInfo.MediaEntity.TYPE_PHOTO) { initStickerEntity(entity); } else if (entity.type == VideoEditedInfo.MediaEntity.TYPE_TEXT) { EditTextOutline editText = new EditTextOutline(ApplicationLoader.applicationContext); editText.getPaint().setAntiAlias(true); editText.drawAnimatedEmojiDrawables = false; editText.setBackgroundColor(Color.TRANSPARENT); editText.setPadding(AndroidUtilities.dp(7), AndroidUtilities.dp(7), AndroidUtilities.dp(7), AndroidUtilities.dp(7)); Typeface typeface; if (entity.textTypeface != null && (typeface = entity.textTypeface.getTypeface()) != null) { editText.setTypeface(typeface); } editText.setTextSize(TypedValue.COMPLEX_UNIT_PX, entity.fontSize); SpannableString text = new SpannableString(entity.text); for (VideoEditedInfo.EmojiEntity e : entity.entities) { if (e.documentAbsolutePath == null) { continue; } e.entity = new VideoEditedInfo.MediaEntity(); e.entity.text = e.documentAbsolutePath; e.entity.subType = e.subType; AnimatedEmojiSpan span = new AnimatedEmojiSpan(0L, 1f, editText.getPaint().getFontMetricsInt()) { @Override public void draw(@NonNull Canvas canvas, CharSequence charSequence, int start, int end, float x, int top, int y, int bottom, @NonNull Paint paint) { super.draw(canvas, charSequence, start, end, x, top, y, bottom, paint); float tcx = entity.x + (editText.getPaddingLeft() + x + measuredSize / 2f) / entity.viewWidth * entity.width; float tcy = entity.y + (editText.getPaddingTop() + top + (bottom - top) / 2f) / entity.viewHeight * entity.height; if (entity.rotation != 0) { float mx = entity.x + entity.width / 2f; float my = entity.y + entity.height / 2f; float ratio = transformedWidth / (float) transformedHeight; float x1 = tcx - mx; float y1 = (tcy - my) / ratio; tcx = (float) (x1 * Math.cos(-entity.rotation) - y1 * Math.sin(-entity.rotation)) + mx; tcy = (float) (x1 * Math.sin(-entity.rotation) + y1 * Math.cos(-entity.rotation)) * ratio + my; } e.entity.width = (float) measuredSize / entity.viewWidth * entity.width; e.entity.height = (float) measuredSize / entity.viewHeight * entity.height; e.entity.x = tcx - e.entity.width / 2f; e.entity.y = tcy - e.entity.height / 2f; e.entity.rotation = entity.rotation; if (e.entity.bitmap == null) initStickerEntity(e.entity); } }; text.setSpan(span, e.offset, e.offset + e.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } editText.setText(Emoji.replaceEmoji(text, editText.getPaint().getFontMetricsInt(), (int) (editText.getTextSize() * .8f), false)); editText.setTextColor(entity.color); CharSequence text2 = editText.getText(); if (text2 instanceof Spanned) { Emoji.EmojiSpan[] spans = ((Spanned) text2).getSpans(0, text2.length(), Emoji.EmojiSpan.class); for (int i = 0; i < spans.length; ++i) { spans[i].scale = .85f; } } int gravity; switch (entity.textAlign) { default: case PaintTextOptionsView.ALIGN_LEFT: gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL; break; case PaintTextOptionsView.ALIGN_CENTER: gravity = Gravity.CENTER; break; case PaintTextOptionsView.ALIGN_RIGHT: gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL; break; } editText.setGravity(gravity); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { int textAlign; switch (entity.textAlign) { default: case PaintTextOptionsView.ALIGN_LEFT: textAlign = LocaleController.isRTL ? View.TEXT_ALIGNMENT_TEXT_END : View.TEXT_ALIGNMENT_TEXT_START; break; case PaintTextOptionsView.ALIGN_CENTER: textAlign = View.TEXT_ALIGNMENT_CENTER; break; case PaintTextOptionsView.ALIGN_RIGHT: textAlign = LocaleController.isRTL ? View.TEXT_ALIGNMENT_TEXT_START : View.TEXT_ALIGNMENT_TEXT_END; break; } editText.setTextAlignment(textAlign); } editText.setHorizontallyScrolling(false); editText.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI); editText.setFocusableInTouchMode(true); editText.setInputType(editText.getInputType() | EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES); if (Build.VERSION.SDK_INT >= 23) { setBreakStrategy(editText); } if (entity.subType == 0) { editText.setFrameColor(entity.color); editText.setTextColor(AndroidUtilities.computePerceivedBrightness(entity.color) >= .721f ? Color.BLACK : Color.WHITE); } else if (entity.subType == 1) { editText.setFrameColor(AndroidUtilities.computePerceivedBrightness(entity.color) >= .25f ? 0x99000000 : 0x99ffffff); editText.setTextColor(entity.color); } else if (entity.subType == 2) { editText.setFrameColor(AndroidUtilities.computePerceivedBrightness(entity.color) >= .25f ? Color.BLACK : Color.WHITE); editText.setTextColor(entity.color); } else if (entity.subType == 3) { editText.setFrameColor(0); editText.setTextColor(entity.color); } editText.measure(View.MeasureSpec.makeMeasureSpec(entity.viewWidth, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(entity.viewHeight, View.MeasureSpec.EXACTLY)); editText.layout(0, 0, entity.viewWidth, entity.viewHeight); entity.bitmap = Bitmap.createBitmap(entity.viewWidth, entity.viewHeight, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(entity.bitmap); editText.draw(canvas); } else if (entity.type == VideoEditedInfo.MediaEntity.TYPE_LOCATION) { LocationMarker marker = new LocationMarker(ApplicationLoader.applicationContext, entity.density); marker.setText(entity.text); marker.setType(entity.subType, entity.color); marker.setMaxWidth(entity.viewWidth); if (entity.entities.size() == 1) { marker.forceEmoji(); } marker.measure(View.MeasureSpec.makeMeasureSpec(entity.viewWidth, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(entity.viewHeight, View.MeasureSpec.EXACTLY)); marker.layout(0, 0, entity.viewWidth, entity.viewHeight); float scale = entity.width * transformedWidth / entity.viewWidth; int w = (int) (entity.viewWidth * scale), h = (int) (entity.viewHeight * scale), pad = 8; entity.bitmap = Bitmap.createBitmap(w + pad + pad, h + pad + pad, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(entity.bitmap); canvas.translate(pad, pad); canvas.scale(scale, scale); marker.draw(canvas); entity.additionalWidth = (2 * pad) * scale / transformedWidth; entity.additionalHeight = (2 * pad) * scale / transformedHeight; if (entity.entities.size() == 1) { VideoEditedInfo.EmojiEntity e = entity.entities.get(0); e.entity = new VideoEditedInfo.MediaEntity(); e.entity.text = e.documentAbsolutePath; e.entity.subType = e.subType; RectF bounds = new RectF(); marker.getEmojiBounds(bounds); float tcx = entity.x + (bounds.centerX()) / entity.viewWidth * entity.width; float tcy = entity.y + (bounds.centerY()) / entity.viewHeight * entity.height; if (entity.rotation != 0) { float mx = entity.x + entity.width / 2f; float my = entity.y + entity.height / 2f; float ratio = transformedWidth / (float) transformedHeight; float x1 = tcx - mx; float y1 = (tcy - my) / ratio; tcx = (float) (x1 * Math.cos(-entity.rotation) - y1 * Math.sin(-entity.rotation)) + mx; tcy = (float) (x1 * Math.sin(-entity.rotation) + y1 * Math.cos(-entity.rotation)) * ratio + my; } e.entity.width = (float) bounds.width() / entity.viewWidth * entity.width; e.entity.height = (float) bounds.height() / entity.viewHeight * entity.height; e.entity.width *= LocationMarker.SCALE; e.entity.height *= LocationMarker.SCALE; e.entity.x = tcx - e.entity.width / 2f; e.entity.y = tcy - e.entity.height / 2f; e.entity.rotation = entity.rotation; initStickerEntity(e.entity); } } } } catch (Throwable e) { FileLog.e(e); } } } private void initStickerEntity(VideoEditedInfo.MediaEntity entity) { entity.W = (int) (entity.width * transformedWidth); entity.H = (int) (entity.height * transformedHeight); if (entity.W > 512) { entity.H = (int) (entity.H / (float) entity.W * 512); entity.W = 512; } if (entity.H > 512) { entity.W = (int) (entity.W / (float) entity.H * 512); entity.H = 512; } if ((entity.subType & 1) != 0) { if (entity.W <= 0 || entity.H <= 0) { return; } entity.bitmap = Bitmap.createBitmap(entity.W, entity.H, Bitmap.Config.ARGB_8888); entity.metadata = new int[3]; entity.ptr = RLottieDrawable.create(entity.text, null, entity.W, entity.H, entity.metadata, false, null, false, 0); entity.framesPerDraw = entity.metadata[1] / videoFps; } else if ((entity.subType & 4) != 0) { entity.animatedFileDrawable = new AnimatedFileDrawable(new File(entity.text), true, 0, 0, null, null, null, 0, UserConfig.selectedAccount, true, 512, 512, null); entity.framesPerDraw = entity.animatedFileDrawable.getFps() / videoFps; entity.currentFrame = 0; entity.animatedFileDrawable.getNextFrame(); } else { if (Build.VERSION.SDK_INT >= 19) { BitmapFactory.Options opts = new BitmapFactory.Options(); if (entity.type == VideoEditedInfo.MediaEntity.TYPE_PHOTO) { opts.inMutable = true; } entity.bitmap = BitmapFactory.decodeFile(entity.text, opts); } else { try { File path = new File(entity.text); RandomAccessFile file = new RandomAccessFile(path, "r"); ByteBuffer buffer = file.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, path.length()); BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inJustDecodeBounds = true; Utilities.loadWebpImage(null, buffer, buffer.limit(), bmOptions, true); if (entity.type == VideoEditedInfo.MediaEntity.TYPE_PHOTO) { bmOptions.inMutable = true; } entity.bitmap = Bitmaps.createBitmap(bmOptions.outWidth, bmOptions.outHeight, Bitmap.Config.ARGB_8888); Utilities.loadWebpImage(entity.bitmap, buffer, buffer.limit(), null, true); file.close(); } catch (Throwable e) { FileLog.e(e); } } if (entity.type == VideoEditedInfo.MediaEntity.TYPE_PHOTO && entity.bitmap != null) { entity.roundRadius = AndroidUtilities.dp(12) / (float) Math.min(entity.viewWidth, entity.viewHeight); Pair<Integer, Integer> orientation = AndroidUtilities.getImageOrientation(entity.text); entity.rotation -= Math.toRadians(orientation.first); if ((orientation.first / 90 % 2) == 1) { float cx = entity.x + entity.width / 2f, cy = entity.y + entity.height / 2f; float w = entity.width * transformedWidth / transformedHeight; entity.width = entity.height * transformedHeight / transformedWidth; entity.height = w; entity.x = cx - entity.width / 2f; entity.y = cy - entity.height / 2f; } applyRoundRadius(entity, entity.bitmap, 0); } else if (entity.bitmap != null) { float aspect = entity.bitmap.getWidth() / (float) entity.bitmap.getHeight(); if (aspect > 1) { float h = entity.height / aspect; entity.y += (entity.height - h) / 2; entity.height = h; } else if (aspect < 1) { float w = entity.width * aspect; entity.x += (entity.width - w) / 2; entity.width = w; } } } } private int createProgram(String vertexSource, String fragmentSource, boolean is300) { if (is300) { int vertexShader = FilterShaders.loadShader(GLES30.GL_VERTEX_SHADER, vertexSource); if (vertexShader == 0) { return 0; } int pixelShader = FilterShaders.loadShader(GLES30.GL_FRAGMENT_SHADER, fragmentSource); if (pixelShader == 0) { return 0; } int program = GLES30.glCreateProgram(); if (program == 0) { return 0; } GLES30.glAttachShader(program, vertexShader); GLES30.glAttachShader(program, pixelShader); GLES30.glLinkProgram(program); int[] linkStatus = new int[1]; GLES30.glGetProgramiv(program, GLES30.GL_LINK_STATUS, linkStatus, 0); if (linkStatus[0] != GLES30.GL_TRUE) { GLES30.glDeleteProgram(program); program = 0; } return program; } else { int vertexShader = FilterShaders.loadShader(GLES20.GL_VERTEX_SHADER, vertexSource); if (vertexShader == 0) { return 0; } int pixelShader = FilterShaders.loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource); if (pixelShader == 0) { return 0; } int program = GLES20.glCreateProgram(); if (program == 0) { return 0; } GLES20.glAttachShader(program, vertexShader); GLES20.glAttachShader(program, pixelShader); GLES20.glLinkProgram(program); int[] linkStatus = new int[1]; GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0); if (linkStatus[0] != GLES20.GL_TRUE) { GLES20.glDeleteProgram(program); program = 0; } return program; } } public void release() { if (mediaEntities != null) { for (int a = 0, N = mediaEntities.size(); a < N; a++) { VideoEditedInfo.MediaEntity entity = mediaEntities.get(a); if (entity.ptr != 0) { RLottieDrawable.destroy(entity.ptr); } if (entity.animatedFileDrawable != null) { entity.animatedFileDrawable.recycle(); } if (entity.view instanceof EditTextEffects) { ((EditTextEffects) entity.view).recycleEmojis(); } if (entity.bitmap != null) { entity.bitmap.recycle(); entity.bitmap = null; } } } } public void changeFragmentShader(String fragmentExternalShader, String fragmentShader, boolean is300) { if (NUM_EXTERNAL_SHADER >= 0 && NUM_EXTERNAL_SHADER < mProgram.length) { int newProgram = createProgram(is300 ? VERTEX_SHADER_300 : VERTEX_SHADER, fragmentExternalShader, is300); if (newProgram != 0) { GLES20.glDeleteProgram(mProgram[NUM_EXTERNAL_SHADER]); mProgram[NUM_EXTERNAL_SHADER] = newProgram; texSizeHandle = GLES20.glGetUniformLocation(newProgram, "texSize"); } } if (NUM_FILTER_SHADER >= 0 && NUM_FILTER_SHADER < mProgram.length) { int newProgram = createProgram(is300 ? VERTEX_SHADER_300 : VERTEX_SHADER, fragmentShader, is300); if (newProgram != 0) { GLES20.glDeleteProgram(mProgram[NUM_FILTER_SHADER]); mProgram[NUM_FILTER_SHADER] = newProgram; } } } }
MrCode403/Telegram
TMessagesProj/src/main/java/org/telegram/messenger/video/TextureRenderer.java
41,692
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.messenger; import android.text.TextUtils; import android.util.SparseArray; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import org.telegram.ui.LaunchActivity; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.regex.Matcher; import java.util.regex.Pattern; public class FileLoader extends BaseController { private static final int PRIORITY_STREAM = 4; public static final int PRIORITY_HIGH = 3; public static final int PRIORITY_NORMAL_UP = 2; public static final int PRIORITY_NORMAL = 1; public static final int PRIORITY_LOW = 0; private int priorityIncreasePointer; private static Pattern sentPattern; public static FilePathDatabase.FileMeta getFileMetadataFromParent(int currentAccount, Object parentObject) { if (parentObject instanceof String) { String str = (String) parentObject; if (str.startsWith("sent_")) { if (sentPattern == null) { sentPattern = Pattern.compile("sent_.*_([0-9]+)_([0-9]+)_([0-9]+)_([0-9]+)"); } try { Matcher matcher = sentPattern.matcher(str); if (matcher.matches()) { FilePathDatabase.FileMeta fileMeta = new FilePathDatabase.FileMeta(); fileMeta.messageId = Integer.parseInt(matcher.group(1)); fileMeta.dialogId = Long.parseLong(matcher.group(2)); fileMeta.messageType = Integer.parseInt(matcher.group(3)); fileMeta.messageSize = Long.parseLong(matcher.group(4)); return fileMeta; } } catch (Exception e) { FileLog.e(e); } } } else if (parentObject instanceof MessageObject) { MessageObject messageObject = (MessageObject) parentObject; FilePathDatabase.FileMeta fileMeta = new FilePathDatabase.FileMeta(); fileMeta.messageId = messageObject.getId(); fileMeta.dialogId = messageObject.getDialogId(); fileMeta.messageType = messageObject.type; fileMeta.messageSize = messageObject.getSize(); return fileMeta; } return null; } public static TLRPC.VideoSize getVectorMarkupVideoSize(TLRPC.Photo photo) { if (photo == null || photo.video_sizes == null) { return null; } for (int i = 0; i < photo.video_sizes.size(); i++) { TLRPC.VideoSize videoSize = photo.video_sizes.get(i); if (videoSize instanceof TLRPC.TL_videoSizeEmojiMarkup || videoSize instanceof TLRPC.TL_videoSizeStickerMarkup) { return videoSize; } } return null; } public static TLRPC.VideoSize getEmojiMarkup(ArrayList<TLRPC.VideoSize> video_sizes) { for (int i = 0; i < video_sizes.size(); i++) { if (video_sizes.get(i) instanceof TLRPC.TL_videoSizeEmojiMarkup || video_sizes.get(i) instanceof TLRPC.TL_videoSizeStickerMarkup) { return video_sizes.get(i); } } return null; } private int getPriorityValue(int priorityType) { if (priorityType == PRIORITY_STREAM) { return Integer.MAX_VALUE; } else if (priorityType == PRIORITY_HIGH) { priorityIncreasePointer++; return (1 << 20) + priorityIncreasePointer; } else if (priorityType == PRIORITY_NORMAL_UP) { priorityIncreasePointer++; return (1 << 16) + priorityIncreasePointer; } else if (priorityType == PRIORITY_NORMAL) { return 1 << 16; } else { return 0; } } public DispatchQueue getFileLoaderQueue() { return fileLoaderQueue; } public interface FileLoaderDelegate { void fileUploadProgressChanged(FileUploadOperation operation, String location, long uploadedSize, long totalSize, boolean isEncrypted); void fileDidUploaded(String location, TLRPC.InputFile inputFile, TLRPC.InputEncryptedFile inputEncryptedFile, byte[] key, byte[] iv, long totalFileSize); void fileDidFailedUpload(String location, boolean isEncrypted); void fileDidLoaded(String location, File finalFile, Object parentObject, int type); void fileDidFailedLoad(String location, int state); void fileLoadProgressChanged(FileLoadOperation operation, String location, long uploadedSize, long totalSize); } public static final int MEDIA_DIR_IMAGE = 0; public static final int MEDIA_DIR_AUDIO = 1; public static final int MEDIA_DIR_VIDEO = 2; public static final int MEDIA_DIR_DOCUMENT = 3; public static final int MEDIA_DIR_CACHE = 4; public static final int MEDIA_DIR_FILES = 5; public static final int MEDIA_DIR_IMAGE_PUBLIC = 100; public static final int MEDIA_DIR_VIDEO_PUBLIC = 101; public static final int IMAGE_TYPE_LOTTIE = 1; public static final int IMAGE_TYPE_ANIMATION = 2; public static final int IMAGE_TYPE_SVG = 3; public static final int IMAGE_TYPE_SVG_WHITE = 4; public static final int IMAGE_TYPE_THEME_PREVIEW = 5; // private final FileLoaderPriorityQueue largeFilesQueue = new FileLoaderPriorityQueue("large files queue", 2); // private final FileLoaderPriorityQueue filesQueue = new FileLoaderPriorityQueue("files queue", 3); // private final FileLoaderPriorityQueue imagesQueue = new FileLoaderPriorityQueue("imagesQueue queue", 6); // private final FileLoaderPriorityQueue audioQueue = new FileLoaderPriorityQueue("audioQueue queue", 3); private final FileLoaderPriorityQueue[] smallFilesQueue = new FileLoaderPriorityQueue[5]; private final FileLoaderPriorityQueue[] largeFilesQueue = new FileLoaderPriorityQueue[5]; public final static long DEFAULT_MAX_FILE_SIZE = 1024L * 1024L * 2000L; public final static long DEFAULT_MAX_FILE_SIZE_PREMIUM = DEFAULT_MAX_FILE_SIZE * 2L; public final static int PRELOAD_CACHE_TYPE = 11; private volatile static DispatchQueue fileLoaderQueue = new DispatchQueue("fileUploadQueue"); private final FilePathDatabase filePathDatabase; private final LinkedList<FileUploadOperation> uploadOperationQueue = new LinkedList<>(); private final LinkedList<FileUploadOperation> uploadSmallOperationQueue = new LinkedList<>(); private final ConcurrentHashMap<String, FileUploadOperation> uploadOperationPaths = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, FileUploadOperation> uploadOperationPathsEnc = new ConcurrentHashMap<>(); private int currentUploadOperationsCount = 0; private int currentUploadSmallOperationsCount = 0; private final ConcurrentHashMap<String, FileLoadOperation> loadOperationPaths = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, LoadOperationUIObject> loadOperationPathsUI = new ConcurrentHashMap<>(10, 1, 2); private HashMap<String, Long> uploadSizes = new HashMap<>(); private HashMap<String, Boolean> loadingVideos = new HashMap<>(); private String forceLoadingFile; private static SparseArray<File> mediaDirs = null; private FileLoaderDelegate delegate = null; private int lastReferenceId; private ConcurrentHashMap<Integer, Object> parentObjectReferences = new ConcurrentHashMap<>(); private static final FileLoader[] Instance = new FileLoader[UserConfig.MAX_ACCOUNT_COUNT]; public static FileLoader getInstance(int num) { FileLoader localInstance = Instance[num]; if (localInstance == null) { synchronized (FileLoader.class) { localInstance = Instance[num]; if (localInstance == null) { Instance[num] = localInstance = new FileLoader(num); } } } return localInstance; } public FileLoader(int instance) { super(instance); filePathDatabase = new FilePathDatabase(instance); for (int i = 0; i < smallFilesQueue.length; i++) { smallFilesQueue[i] = new FileLoaderPriorityQueue(instance, "smallFilesQueue dc" + (i + 1), FileLoaderPriorityQueue.TYPE_SMALL); largeFilesQueue[i] = new FileLoaderPriorityQueue(instance, "largeFilesQueue dc" + (i + 1), FileLoaderPriorityQueue.TYPE_LARGE); } dumpFilesQueue(); } public static void setMediaDirs(SparseArray<File> dirs) { mediaDirs = dirs; } public static File checkDirectory(int type) { return mediaDirs.get(type); } public static File getDirectory(int type) { File dir = mediaDirs.get(type); if (dir == null && type != FileLoader.MEDIA_DIR_CACHE) { dir = mediaDirs.get(FileLoader.MEDIA_DIR_CACHE); } if (BuildVars.NO_SCOPED_STORAGE) { try { if (dir != null && !dir.isDirectory()) { dir.mkdirs(); } } catch (Exception e) { //don't promt } } return dir; } public int getFileReference(Object parentObject) { int reference = lastReferenceId++; parentObjectReferences.put(reference, parentObject); return reference; } public Object getParentObject(int reference) { return parentObjectReferences.get(reference); } public void setLoadingVideoInternal(TLRPC.Document document, boolean player) { String key = getAttachFileName(document); String dKey = key + (player ? "p" : ""); loadingVideos.put(dKey, true); getNotificationCenter().postNotificationName(NotificationCenter.videoLoadingStateChanged, key); } public void setLoadingVideo(TLRPC.Document document, boolean player, boolean schedule) { if (document == null) { return; } if (schedule) { AndroidUtilities.runOnUIThread(() -> setLoadingVideoInternal(document, player)); } else { setLoadingVideoInternal(document, player); } } public void setLoadingVideoForPlayer(TLRPC.Document document, boolean player) { if (document == null) { return; } String key = getAttachFileName(document); if (loadingVideos.containsKey(key + (player ? "" : "p"))) { loadingVideos.put(key + (player ? "p" : ""), true); } } private void removeLoadingVideoInternal(TLRPC.Document document, boolean player) { String key = getAttachFileName(document); String dKey = key + (player ? "p" : ""); if (loadingVideos.remove(dKey) != null) { getNotificationCenter().postNotificationName(NotificationCenter.videoLoadingStateChanged, key); } } public void removeLoadingVideo(TLRPC.Document document, boolean player, boolean schedule) { if (document == null) { return; } if (schedule) { AndroidUtilities.runOnUIThread(() -> removeLoadingVideoInternal(document, player)); } else { removeLoadingVideoInternal(document, player); } } public boolean isLoadingVideo(TLRPC.Document document, boolean player) { return document != null && loadingVideos.containsKey(getAttachFileName(document) + (player ? "p" : "")); } public boolean isLoadingVideoAny(TLRPC.Document document) { return isLoadingVideo(document, false) || isLoadingVideo(document, true); } public void cancelFileUpload(final String location, final boolean enc) { fileLoaderQueue.postRunnable(() -> { FileUploadOperation operation; if (!enc) { operation = uploadOperationPaths.get(location); } else { operation = uploadOperationPathsEnc.get(location); } uploadSizes.remove(location); if (operation != null) { uploadOperationPathsEnc.remove(location); uploadOperationQueue.remove(operation); uploadSmallOperationQueue.remove(operation); operation.cancel(); } }); } public void checkUploadNewDataAvailable(final String location, final boolean encrypted, final long newAvailableSize, final long finalSize) { fileLoaderQueue.postRunnable(() -> { FileUploadOperation operation; if (encrypted) { operation = uploadOperationPathsEnc.get(location); } else { operation = uploadOperationPaths.get(location); } if (operation != null) { operation.checkNewDataAvailable(newAvailableSize, finalSize); } else if (finalSize != 0) { uploadSizes.put(location, finalSize); } }); } public void onNetworkChanged(final boolean slow) { fileLoaderQueue.postRunnable(() -> { for (ConcurrentHashMap.Entry<String, FileUploadOperation> entry : uploadOperationPaths.entrySet()) { entry.getValue().onNetworkChanged(slow); } for (ConcurrentHashMap.Entry<String, FileUploadOperation> entry : uploadOperationPathsEnc.entrySet()) { entry.getValue().onNetworkChanged(slow); } }); } public void uploadFile(final String location, final boolean encrypted, final boolean small, final int type) { uploadFile(location, encrypted, small, 0, type, false); } public void uploadFile(final String location, final boolean encrypted, final boolean small, final long estimatedSize, final int type, boolean forceSmallFile) { if (location == null) { return; } fileLoaderQueue.postRunnable(() -> { if (encrypted) { if (uploadOperationPathsEnc.containsKey(location)) { return; } } else { if (uploadOperationPaths.containsKey(location)) { return; } } long esimated = estimatedSize; if (esimated != 0) { Long finalSize = uploadSizes.get(location); if (finalSize != null) { esimated = 0; uploadSizes.remove(location); } } FileUploadOperation operation = new FileUploadOperation(currentAccount, location, encrypted, esimated, type); if (delegate != null && estimatedSize != 0) { delegate.fileUploadProgressChanged(operation, location, 0, estimatedSize, encrypted); } if (encrypted) { uploadOperationPathsEnc.put(location, operation); } else { uploadOperationPaths.put(location, operation); } if (forceSmallFile) { operation.setForceSmallFile(); } operation.setDelegate(new FileUploadOperation.FileUploadOperationDelegate() { @Override public void didFinishUploadingFile(final FileUploadOperation operation, final TLRPC.InputFile inputFile, final TLRPC.InputEncryptedFile inputEncryptedFile, final byte[] key, final byte[] iv) { fileLoaderQueue.postRunnable(() -> { if (encrypted) { uploadOperationPathsEnc.remove(location); } else { uploadOperationPaths.remove(location); } if (small) { currentUploadSmallOperationsCount--; if (currentUploadSmallOperationsCount < 1) { FileUploadOperation operation12 = uploadSmallOperationQueue.poll(); if (operation12 != null) { currentUploadSmallOperationsCount++; operation12.start(); } } } else { currentUploadOperationsCount--; if (currentUploadOperationsCount < 1) { FileUploadOperation operation12 = uploadOperationQueue.poll(); if (operation12 != null) { currentUploadOperationsCount++; operation12.start(); } } } if (delegate != null) { delegate.fileDidUploaded(location, inputFile, inputEncryptedFile, key, iv, operation.getTotalFileSize()); } }); } @Override public void didFailedUploadingFile(final FileUploadOperation operation) { fileLoaderQueue.postRunnable(() -> { if (encrypted) { uploadOperationPathsEnc.remove(location); } else { uploadOperationPaths.remove(location); } if (delegate != null) { delegate.fileDidFailedUpload(location, encrypted); } if (small) { currentUploadSmallOperationsCount--; if (currentUploadSmallOperationsCount < 1) { FileUploadOperation operation1 = uploadSmallOperationQueue.poll(); if (operation1 != null) { currentUploadSmallOperationsCount++; operation1.start(); } } } else { currentUploadOperationsCount--; if (currentUploadOperationsCount < 1) { FileUploadOperation operation1 = uploadOperationQueue.poll(); if (operation1 != null) { currentUploadOperationsCount++; operation1.start(); } } } }); } @Override public void didChangedUploadProgress(FileUploadOperation operation, long uploadedSize, long totalSize) { if (delegate != null) { delegate.fileUploadProgressChanged(operation, location, uploadedSize, totalSize, encrypted); } } }); if (small) { if (currentUploadSmallOperationsCount < 1) { currentUploadSmallOperationsCount++; operation.start(); } else { uploadSmallOperationQueue.add(operation); } } else { if (currentUploadOperationsCount < 1) { currentUploadOperationsCount++; operation.start(); } else { uploadOperationQueue.add(operation); } } }); } public void setForceStreamLoadingFile(TLRPC.FileLocation location, String ext) { if (location == null) { return; } fileLoaderQueue.postRunnable(() -> { forceLoadingFile = getAttachFileName(location, ext); FileLoadOperation operation = loadOperationPaths.get(forceLoadingFile); if (operation != null) { if (operation.isPreloadVideoOperation()) { operation.setIsPreloadVideoOperation(false); } operation.setForceRequest(true); operation.setPriority(getPriorityValue(PRIORITY_STREAM)); operation.getQueue().add(operation); operation.getQueue().checkLoadingOperations(); } }); } public void cancelLoadFile(TLRPC.Document document) { cancelLoadFile(document, false); } public void cancelLoadFile(TLRPC.Document document, boolean deleteFile) { cancelLoadFile(document, null, null, null, null, null, deleteFile); } public void cancelLoadFile(SecureDocument document) { cancelLoadFile(null, document, null, null, null, null, false); } public void cancelLoadFile(WebFile document) { cancelLoadFile(null, null, document, null, null, null, false); } public void cancelLoadFile(TLRPC.PhotoSize photo) { cancelLoadFile(photo, false); } public void cancelLoadFile(TLRPC.PhotoSize photo, boolean deleteFile) { cancelLoadFile(null, null, null, photo.location, null, null, deleteFile); } public void cancelLoadFile(TLRPC.FileLocation location, String ext) { cancelLoadFile(location, ext, false); } public void cancelLoadFile(TLRPC.FileLocation location, String ext, boolean deleteFile) { cancelLoadFile(null, null, null, location, ext, null, deleteFile); } public void cancelLoadFile(String fileName) { cancelLoadFile(null, null, null, null, null, fileName, true); } public void cancelLoadFiles(ArrayList<String> fileNames) { for (int a = 0, N = fileNames.size(); a < N; a++) { cancelLoadFile(null, null, null, null, null, fileNames.get(a), true); } } private void cancelLoadFile(final TLRPC.Document document, final SecureDocument secureDocument, final WebFile webDocument, final TLRPC.FileLocation location, final String locationExt, String name, boolean deleteFile) { if (location == null && document == null && webDocument == null && secureDocument == null && TextUtils.isEmpty(name)) { return; } final String fileName; if (location != null) { fileName = getAttachFileName(location, locationExt); } else if (document != null) { fileName = getAttachFileName(document); } else if (secureDocument != null) { fileName = getAttachFileName(secureDocument); } else if (webDocument != null) { fileName = getAttachFileName(webDocument); } else { fileName = name; } LoadOperationUIObject uiObject = loadOperationPathsUI.remove(fileName); Runnable runnable = uiObject != null ? uiObject.loadInternalRunnable : null; boolean removed = uiObject != null; if (runnable != null) { fileLoaderQueue.cancelRunnable(runnable); } fileLoaderQueue.postRunnable(() -> { FileLoadOperation operation = loadOperationPaths.remove(fileName); if (operation != null) { FileLoaderPriorityQueue queue = operation.getQueue(); queue.cancel(operation); } }); if (removed && document != null) { AndroidUtilities.runOnUIThread(() -> { getNotificationCenter().postNotificationName(NotificationCenter.onDownloadingFilesChanged); }); } } public void cancelLoadAllFiles() { for (String fileName : loadOperationPathsUI.keySet()) { LoadOperationUIObject uiObject = loadOperationPathsUI.get(fileName); Runnable runnable = uiObject != null ? uiObject.loadInternalRunnable : null; boolean removed = uiObject != null; if (runnable != null) { fileLoaderQueue.cancelRunnable(runnable); } fileLoaderQueue.postRunnable(() -> { FileLoadOperation operation = loadOperationPaths.remove(fileName); if (operation != null) { FileLoaderPriorityQueue queue = operation.getQueue(); queue.cancel(operation); } }); // if (removed && document != null) { // AndroidUtilities.runOnUIThread(() -> { // getNotificationCenter().postNotificationName(NotificationCenter.onDownloadingFilesChanged); // }); // } } } public boolean isLoadingFile(final String fileName) { return fileName != null && loadOperationPathsUI.containsKey(fileName); } public float getBufferedProgressFromPosition(final float position, final String fileName) { if (TextUtils.isEmpty(fileName)) { return 0; } FileLoadOperation loadOperation = loadOperationPaths.get(fileName); if (loadOperation != null) { return loadOperation.getDownloadedLengthFromOffset(position); } else { return 0.0f; } } public void loadFile(ImageLocation imageLocation, Object parentObject, String ext, int priority, int cacheType) { if (imageLocation == null) { return; } if (cacheType == 0 && (imageLocation.isEncrypted() || imageLocation.photoSize != null && imageLocation.getSize() == 0)) { cacheType = 1; } loadFile(imageLocation.document, imageLocation.secureDocument, imageLocation.webFile, imageLocation.location, imageLocation, parentObject, ext, imageLocation.getSize(), priority, cacheType); } public void loadFile(SecureDocument secureDocument, int priority) { if (secureDocument == null) { return; } loadFile(null, secureDocument, null, null, null, null, null, 0, priority, 1); } public void loadFile(TLRPC.Document document, Object parentObject, int priority, int cacheType) { if (document == null) { return; } if (cacheType == 0 && document.key != null) { cacheType = 1; } loadFile(document, null, null, null, null, parentObject, null, 0, priority, cacheType); } public void loadFile(WebFile document, int priority, int cacheType) { loadFile(null, null, document, null, null, null, null, 0, priority, cacheType); } private FileLoadOperation loadFileInternal(final TLRPC.Document document, final SecureDocument secureDocument, final WebFile webDocument, TLRPC.TL_fileLocationToBeDeprecated location, final ImageLocation imageLocation, Object parentObject, final String locationExt, final long locationSize, int priority, final FileLoadOperationStream stream, final long streamOffset, boolean streamPriority, final int cacheType) { String fileName; if (location != null) { fileName = getAttachFileName(location, locationExt); } else if (secureDocument != null) { fileName = getAttachFileName(secureDocument); } else if (document != null) { fileName = getAttachFileName(document); } else if (webDocument != null) { fileName = getAttachFileName(webDocument); } else { fileName = null; } if (fileName == null || fileName.contains("" + Integer.MIN_VALUE)) { return null; } if (cacheType != 10 && !TextUtils.isEmpty(fileName) && !fileName.contains("" + Integer.MIN_VALUE)) { loadOperationPathsUI.put(fileName, new LoadOperationUIObject()); } if (document != null && parentObject instanceof MessageObject && ((MessageObject) parentObject).putInDownloadsStore && !((MessageObject) parentObject).isAnyKindOfSticker()) { getDownloadController().startDownloadFile(document, (MessageObject) parentObject); } final String finalFileName = fileName; FileLoadOperation operation = loadOperationPaths.get(finalFileName); priority = getPriorityValue(priority); if (operation != null) { if (cacheType != 10 && operation.isPreloadVideoOperation()) { operation.setIsPreloadVideoOperation(false); } operation.setForceRequest(priority > 0); operation.setPriority(priority); operation.setStream(stream, streamPriority, streamOffset); operation.getQueue().add(operation); operation.updateProgress(); operation.getQueue().checkLoadingOperations(); FileLog.d("load operation update position fileName=" + finalFileName + " position in queue " + operation.getPositionInQueue() + " account=" + currentAccount); return operation; } File tempDir = getDirectory(MEDIA_DIR_CACHE); File storeDir = tempDir; int type = MEDIA_DIR_CACHE; long documentId = 0; int dcId = 0; if (secureDocument != null) { operation = new FileLoadOperation(secureDocument); type = MEDIA_DIR_DOCUMENT; } else if (location != null) { documentId = location.volume_id; dcId = location.dc_id; operation = new FileLoadOperation(imageLocation, parentObject, locationExt, locationSize); type = MEDIA_DIR_IMAGE; } else if (document != null) { operation = new FileLoadOperation(document, parentObject); if (MessageObject.isVoiceDocument(document)) { type = MEDIA_DIR_AUDIO; } else if (MessageObject.isVideoDocument(document)) { type = MEDIA_DIR_VIDEO; documentId = document.id; dcId = document.dc_id; } else { type = MEDIA_DIR_DOCUMENT; documentId = document.id; dcId = document.dc_id; } if (MessageObject.isRoundVideoDocument(document)) { documentId = 0; dcId = 0; } } else if (webDocument != null) { operation = new FileLoadOperation(currentAccount, webDocument); if (webDocument.location != null) { type = MEDIA_DIR_CACHE; } else if (MessageObject.isVoiceWebDocument(webDocument)) { type = MEDIA_DIR_AUDIO; } else if (MessageObject.isVideoWebDocument(webDocument)) { type = MEDIA_DIR_VIDEO; } else if (MessageObject.isImageWebDocument(webDocument)) { type = MEDIA_DIR_IMAGE; } else { type = MEDIA_DIR_DOCUMENT; } } FileLoaderPriorityQueue loaderQueue; int index = Utilities.clamp(operation.getDatacenterId() - 1, 4, 0); if (operation.totalBytesCount > 20 * 1024 * 1024) {//20mb loaderQueue = largeFilesQueue[index]; } else { loaderQueue = smallFilesQueue[index]; } String storeFileName = fileName; if (cacheType == 0 || cacheType == 10) { if (documentId != 0) { String path = getFileDatabase().getPath(documentId, dcId, type, true); boolean customPath = false; if (path != null) { File file = new File(path); if (file.exists()) { customPath = true; storeFileName = file.getName(); storeDir = file.getParentFile(); } } if (!customPath) { storeFileName = fileName; storeDir = getDirectory(type); boolean saveCustomPath = false; if ((type == MEDIA_DIR_IMAGE || type == MEDIA_DIR_VIDEO) && canSaveToPublicStorage(parentObject)) { File newDir; if (type == MEDIA_DIR_IMAGE) { newDir = getDirectory(MEDIA_DIR_IMAGE_PUBLIC); } else { newDir = getDirectory(MEDIA_DIR_VIDEO_PUBLIC); } if (newDir != null) { storeDir = newDir; saveCustomPath = true; } } else if (!TextUtils.isEmpty(getDocumentFileName(document)) && canSaveAsFile(parentObject)) { storeFileName = getDocumentFileName(document); File newDir = getDirectory(MEDIA_DIR_FILES); if (newDir != null) { storeDir = newDir; saveCustomPath = true; } } if (saveCustomPath) { operation.pathSaveData = new FilePathDatabase.PathData(documentId, dcId, type); } } } else { storeDir = getDirectory(type); } } else if (cacheType == 2) { operation.setEncryptFile(true); } operation.setPaths(currentAccount, fileName, loaderQueue, storeDir, tempDir, storeFileName); if (cacheType == 10) { operation.setIsPreloadVideoOperation(true); } final int finalType = type; FileLoadOperation.FileLoadOperationDelegate fileLoadOperationDelegate = new FileLoadOperation.FileLoadOperationDelegate() { @Override public void didPreFinishLoading(FileLoadOperation operation, File finalFile) { FileLoaderPriorityQueue queue = operation.getQueue(); fileLoaderQueue.postRunnable(() -> { operation.preFinished = true; queue.checkLoadingOperations(); }); } @Override public void didFinishLoadingFile(FileLoadOperation operation, File finalFile) { if (!operation.isPreloadVideoOperation() && operation.isPreloadFinished()) { return; } FilePathDatabase.FileMeta fileMeta = getFileMetadataFromParent(currentAccount, parentObject); if (fileMeta != null) { getFileLoader().getFileDatabase().saveFileDialogId(finalFile, fileMeta); } if (parentObject instanceof MessageObject) { MessageObject messageObject = (MessageObject) parentObject; if (document != null && messageObject.putInDownloadsStore) { getDownloadController().onDownloadComplete(messageObject); } } if (!operation.isPreloadVideoOperation()) { loadOperationPathsUI.remove(fileName); if (delegate != null) { delegate.fileDidLoaded(fileName, finalFile, parentObject, finalType); } } checkDownloadQueue(operation, operation.getQueue(), 100); } @Override public void didFailedLoadingFile(FileLoadOperation operation, int reason) { loadOperationPathsUI.remove(fileName); checkDownloadQueue(operation, operation.getQueue()); if (delegate != null) { delegate.fileDidFailedLoad(fileName, reason); } if (document != null && parentObject instanceof MessageObject && reason == 0) { getDownloadController().onDownloadFail((MessageObject) parentObject, reason); } else if (reason == -1) { LaunchActivity.checkFreeDiscSpaceStatic(2); } } @Override public void didChangedLoadProgress(FileLoadOperation operation, long uploadedSize, long totalSize) { if (delegate != null) { delegate.fileLoadProgressChanged(operation, fileName, uploadedSize, totalSize); } } @Override public void saveFilePath(FilePathDatabase.PathData pathSaveData, File cacheFileFinal) { getFileDatabase().putPath(pathSaveData.id, pathSaveData.dc, pathSaveData.type, cacheFileFinal != null ? cacheFileFinal.toString() : null); } @Override public boolean hasAnotherRefOnFile(String path) { return getFileDatabase().hasAnotherRefOnFile(path); } }; operation.setDelegate(fileLoadOperationDelegate); loadOperationPaths.put(finalFileName, operation); operation.setPriority(priority); if (stream != null) { operation.setStream(stream, streamPriority, streamOffset); } loaderQueue.add(operation); loaderQueue.checkLoadingOperations(); if (BuildVars.LOGS_ENABLED) { FileLog.d("create load operation fileName=" + finalFileName + " documentName=" + getDocumentFileName(document) + "size=" + AndroidUtilities.formatFileSize(operation.totalBytesCount) + " position in queue " + operation.getPositionInQueue() + " account=" + currentAccount); } return operation; } private boolean canSaveAsFile(Object parentObject) { if (parentObject instanceof MessageObject) { MessageObject messageObject = (MessageObject) parentObject; if (!messageObject.isDocument()) { return false; } return true; } return false; } private boolean canSaveToPublicStorage(Object parentObject) { if (BuildVars.NO_SCOPED_STORAGE) { return false; } FilePathDatabase.FileMeta metadata = getFileMetadataFromParent(currentAccount, parentObject); MessageObject messageObject = null; if (metadata != null) { int flag; long dialogId = metadata.dialogId; if (getMessagesController().isChatNoForwards(getMessagesController().getChat(-dialogId)) || DialogObject.isEncryptedDialog(dialogId)) { return false; } if (parentObject instanceof MessageObject) { messageObject = (MessageObject) parentObject; if (messageObject.isRoundVideo() || messageObject.isVoice() || messageObject.isAnyKindOfSticker() || messageObject.messageOwner.noforwards) { return false; } } else { if (metadata.messageType == MessageObject.TYPE_ROUND_VIDEO || metadata.messageType == MessageObject.TYPE_STICKER || metadata.messageType == MessageObject.TYPE_VOICE) { return false; } } if (dialogId >= 0) { flag = SharedConfig.SAVE_TO_GALLERY_FLAG_PEER; } else { if (ChatObject.isChannelAndNotMegaGroup(getMessagesController().getChat(-dialogId))) { flag = SharedConfig.SAVE_TO_GALLERY_FLAG_CHANNELS; } else { flag = SharedConfig.SAVE_TO_GALLERY_FLAG_GROUP; } } if (SaveToGallerySettingsHelper.needSave(flag, metadata, messageObject, currentAccount)) { return true; } } return false; } private void addOperationToQueue(FileLoadOperation operation, LinkedList<FileLoadOperation> queue) { int priority = operation.getPriority(); if (priority > 0) { int index = queue.size(); for (int a = 0, size = queue.size(); a < size; a++) { FileLoadOperation queuedOperation = queue.get(a); if (queuedOperation.getPriority() < priority) { index = a; break; } } queue.add(index, operation); } else { queue.add(operation); } } private void loadFile(final TLRPC.Document document, final SecureDocument secureDocument, final WebFile webDocument, TLRPC.TL_fileLocationToBeDeprecated location, final ImageLocation imageLocation, final Object parentObject, final String locationExt, final long locationSize, final int priority, final int cacheType) { String fileName; if (location != null) { fileName = getAttachFileName(location, locationExt); } else if (document != null) { fileName = getAttachFileName(document); } else if (webDocument != null) { fileName = getAttachFileName(webDocument); } else { fileName = null; } Runnable runnable = () -> loadFileInternal(document, secureDocument, webDocument, location, imageLocation, parentObject, locationExt, locationSize, priority, null, 0, false, cacheType); if (cacheType != 10 && !TextUtils.isEmpty(fileName) && !fileName.contains("" + Integer.MIN_VALUE)) { LoadOperationUIObject uiObject = new FileLoader.LoadOperationUIObject(); uiObject.loadInternalRunnable = runnable; loadOperationPathsUI.put(fileName, uiObject); } fileLoaderQueue.postRunnable(runnable); } protected FileLoadOperation loadStreamFile(final FileLoadOperationStream stream, final TLRPC.Document document, final ImageLocation location, final Object parentObject, final long offset, final boolean priority, int loadingPriority) { final CountDownLatch semaphore = new CountDownLatch(1); final FileLoadOperation[] result = new FileLoadOperation[1]; fileLoaderQueue.postRunnable(() -> { result[0] = loadFileInternal(document, null, null, document == null && location != null ? location.location : null, location, parentObject, document == null && location != null ? "mp4" : null, document == null && location != null ? location.currentSize : 0, loadingPriority, stream, offset, priority, document == null ? 1 : 0); semaphore.countDown(); }); try { semaphore.await(); } catch (Exception e) { FileLog.e(e, false); } return result[0]; } private void checkDownloadQueue(FileLoadOperation operation, FileLoaderPriorityQueue queue) { checkDownloadQueue(operation, queue, 0); } private void checkDownloadQueue(FileLoadOperation operation, FileLoaderPriorityQueue queue, long delay) { fileLoaderQueue.postRunnable(() -> { if (queue.remove(operation)) { loadOperationPaths.remove(operation.getFileName()); queue.checkLoadingOperations(); } }, delay); } public void setDelegate(FileLoaderDelegate fileLoaderDelegate) { delegate = fileLoaderDelegate; } public static String getMessageFileName(TLRPC.Message message) { if (message == null) { return ""; } if (message instanceof TLRPC.TL_messageService) { if (message.action.photo != null) { ArrayList<TLRPC.PhotoSize> sizes = message.action.photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize()); if (sizeFull != null) { return getAttachFileName(sizeFull); } } } } else { if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaDocument) { return getAttachFileName(MessageObject.getMedia(message).document); } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaPhoto) { ArrayList<TLRPC.PhotoSize> sizes = MessageObject.getMedia(message).photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize(), false, null, true); if (sizeFull != null) { return getAttachFileName(sizeFull); } } } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaWebPage) { if (MessageObject.getMedia(message).webpage.document != null) { return getAttachFileName(MessageObject.getMedia(message).webpage.document); } else if (MessageObject.getMedia(message).webpage.photo != null) { ArrayList<TLRPC.PhotoSize> sizes = MessageObject.getMedia(message).webpage.photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize()); if (sizeFull != null) { return getAttachFileName(sizeFull); } } } } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaInvoice) { TLRPC.WebDocument document = ((TLRPC.TL_messageMediaInvoice) MessageObject.getMedia(message)).webPhoto; if (document != null) { return Utilities.MD5(document.url) + "." + ImageLoader.getHttpUrlExtension(document.url, getMimeTypePart(document.mime_type)); } } } return ""; } public File getPathToMessage(TLRPC.Message message) { return getPathToMessage(message, true); } public File getPathToMessage(TLRPC.Message message, boolean useFileDatabaseQueue) { if (message == null) { return new File(""); } if (message instanceof TLRPC.TL_messageService) { if (message.action.photo != null) { ArrayList<TLRPC.PhotoSize> sizes = message.action.photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize()); if (sizeFull != null) { return getPathToAttach(sizeFull, null, false, useFileDatabaseQueue); } } } } else { if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaDocument) { return getPathToAttach(MessageObject.getMedia(message).document, null, MessageObject.getMedia(message).ttl_seconds != 0, useFileDatabaseQueue); } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaPhoto) { ArrayList<TLRPC.PhotoSize> sizes = MessageObject.getMedia(message).photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize(), false, null, true); if (sizeFull != null) { return getPathToAttach(sizeFull, null, MessageObject.getMedia(message).ttl_seconds != 0, useFileDatabaseQueue); } } } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaWebPage) { if (MessageObject.getMedia(message).webpage.document != null) { return getPathToAttach(MessageObject.getMedia(message).webpage.document, null, false, useFileDatabaseQueue); } else if (MessageObject.getMedia(message).webpage.photo != null) { ArrayList<TLRPC.PhotoSize> sizes = MessageObject.getMedia(message).webpage.photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize()); if (sizeFull != null) { return getPathToAttach(sizeFull, null, false, useFileDatabaseQueue); } } } } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaInvoice) { return getPathToAttach(((TLRPC.TL_messageMediaInvoice) MessageObject.getMedia(message)).photo, null, true, useFileDatabaseQueue); } } return new File(""); } public File getPathToAttach(TLObject attach) { return getPathToAttach(attach, null, false); } public File getPathToAttach(TLObject attach, boolean forceCache) { return getPathToAttach(attach, null, forceCache); } public File getPathToAttach(TLObject attach, String ext, boolean forceCache) { return getPathToAttach(attach, null, ext, forceCache, true); } public File getPathToAttach(TLObject attach, String ext, boolean forceCache, boolean useFileDatabaseQueue) { return getPathToAttach(attach, null, ext, forceCache, useFileDatabaseQueue); } /** * Return real file name. Used before file.exist() */ public File getPathToAttach(TLObject attach, String size, String ext, boolean forceCache, boolean useFileDatabaseQueue) { File dir = null; long documentId = 0; int dcId = 0; int type = 0; if (forceCache) { dir = getDirectory(MEDIA_DIR_CACHE); } else { if (attach instanceof TLRPC.Document) { TLRPC.Document document = (TLRPC.Document) attach; if (!TextUtils.isEmpty(document.localPath)) { return new File(document.localPath); } if (document.key != null) { type = MEDIA_DIR_CACHE; } else { if (MessageObject.isVoiceDocument(document)) { type = MEDIA_DIR_AUDIO; } else if (MessageObject.isVideoDocument(document)) { type = MEDIA_DIR_VIDEO; } else { type = MEDIA_DIR_DOCUMENT; } } documentId = document.id; dcId = document.dc_id; dir = getDirectory(type); } else if (attach instanceof TLRPC.Photo) { TLRPC.PhotoSize photoSize = getClosestPhotoSizeWithSize(((TLRPC.Photo) attach).sizes, AndroidUtilities.getPhotoSize()); return getPathToAttach(photoSize, ext, false, useFileDatabaseQueue); } else if (attach instanceof TLRPC.PhotoSize) { TLRPC.PhotoSize photoSize = (TLRPC.PhotoSize) attach; if (photoSize instanceof TLRPC.TL_photoStrippedSize || photoSize instanceof TLRPC.TL_photoPathSize) { dir = null; } else if (photoSize.location == null || photoSize.location.key != null || photoSize.location.volume_id == Integer.MIN_VALUE && photoSize.location.local_id < 0 || photoSize.size < 0) { dir = getDirectory(type = MEDIA_DIR_CACHE); } else { dir = getDirectory(type = MEDIA_DIR_IMAGE); } documentId = photoSize.location.volume_id; dcId = photoSize.location.dc_id; } else if (attach instanceof TLRPC.TL_videoSize) { TLRPC.TL_videoSize videoSize = (TLRPC.TL_videoSize) attach; if (videoSize.location == null || videoSize.location.key != null || videoSize.location.volume_id == Integer.MIN_VALUE && videoSize.location.local_id < 0 || videoSize.size < 0) { dir = getDirectory(type = MEDIA_DIR_CACHE); } else { dir = getDirectory(type = MEDIA_DIR_IMAGE); } documentId = videoSize.location.volume_id; dcId = videoSize.location.dc_id; } else if (attach instanceof TLRPC.FileLocation) { TLRPC.FileLocation fileLocation = (TLRPC.FileLocation) attach; if (fileLocation.key != null || fileLocation.volume_id == Integer.MIN_VALUE && fileLocation.local_id < 0) { dir = getDirectory(MEDIA_DIR_CACHE); } else { documentId = fileLocation.volume_id; dcId = fileLocation.dc_id; dir = getDirectory(type = MEDIA_DIR_IMAGE); } } else if (attach instanceof TLRPC.UserProfilePhoto || attach instanceof TLRPC.ChatPhoto) { if (size == null) { size = "s"; } if ("s".equals(size)) { dir = getDirectory(MEDIA_DIR_CACHE); } else { dir = getDirectory(MEDIA_DIR_IMAGE); } } else if (attach instanceof WebFile) { WebFile document = (WebFile) attach; if (document.mime_type.startsWith("image/")) { dir = getDirectory(MEDIA_DIR_IMAGE); } else if (document.mime_type.startsWith("audio/")) { dir = getDirectory(MEDIA_DIR_AUDIO); } else if (document.mime_type.startsWith("video/")) { dir = getDirectory(MEDIA_DIR_VIDEO); } else { dir = getDirectory(MEDIA_DIR_DOCUMENT); } } else if (attach instanceof TLRPC.TL_secureFile || attach instanceof SecureDocument) { dir = getDirectory(MEDIA_DIR_CACHE); } } if (dir == null) { return new File(""); } if (documentId != 0) { String path = getInstance(UserConfig.selectedAccount).getFileDatabase().getPath(documentId, dcId, type, useFileDatabaseQueue); if (path != null) { return new File(path); } } return new File(dir, getAttachFileName(attach, ext)); } public FilePathDatabase getFileDatabase() { return filePathDatabase; } public static TLRPC.PhotoSize getClosestPhotoSizeWithSize(ArrayList<TLRPC.PhotoSize> sizes, int side) { return getClosestPhotoSizeWithSize(sizes, side, false); } public static TLRPC.PhotoSize getClosestPhotoSizeWithSize(ArrayList<TLRPC.PhotoSize> sizes, int side, boolean byMinSide) { return getClosestPhotoSizeWithSize(sizes, side, byMinSide, null, false); } public static TLRPC.PhotoSize getClosestPhotoSizeWithSize(ArrayList<TLRPC.PhotoSize> sizes, int side, boolean byMinSide, TLRPC.PhotoSize toIgnore, boolean ignoreStripped) { if (sizes == null || sizes.isEmpty()) { return null; } int lastSide = 0; TLRPC.PhotoSize closestObject = null; for (int a = 0; a < sizes.size(); a++) { TLRPC.PhotoSize obj = sizes.get(a); if (obj == null || obj == toIgnore || obj instanceof TLRPC.TL_photoSizeEmpty || obj instanceof TLRPC.TL_photoPathSize || ignoreStripped && obj instanceof TLRPC.TL_photoStrippedSize) { continue; } if (byMinSide) { int currentSide = Math.min(obj.h, obj.w); if ( closestObject == null || side > 100 && closestObject.location != null && closestObject.location.dc_id == Integer.MIN_VALUE || obj instanceof TLRPC.TL_photoCachedSize || side > lastSide && lastSide < currentSide ) { closestObject = obj; lastSide = currentSide; } } else { int currentSide = Math.max(obj.w, obj.h); 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; } } } return closestObject; } public static TLRPC.VideoSize getClosestVideoSizeWithSize(ArrayList<TLRPC.VideoSize> sizes, int side) { return getClosestVideoSizeWithSize(sizes, side, false); } public static TLRPC.VideoSize getClosestVideoSizeWithSize(ArrayList<TLRPC.VideoSize> sizes, int side, boolean byMinSide) { return getClosestVideoSizeWithSize(sizes, side, byMinSide, false); } public static TLRPC.VideoSize getClosestVideoSizeWithSize(ArrayList<TLRPC.VideoSize> sizes, int side, boolean byMinSide, boolean ignoreStripped) { if (sizes == null || sizes.isEmpty()) { return null; } int lastSide = 0; TLRPC.VideoSize closestObject = null; for (int a = 0; a < sizes.size(); a++) { TLRPC.VideoSize obj = sizes.get(a); if (obj == null || obj instanceof TLRPC.TL_videoSizeEmojiMarkup || obj instanceof TLRPC.TL_videoSizeStickerMarkup) { continue; } if (byMinSide) { int currentSide = Math.min(obj.h, obj.w); if (closestObject == null || side > 100 && closestObject.location != null && closestObject.location.dc_id == Integer.MIN_VALUE || side > lastSide && lastSide < currentSide) { closestObject = obj; lastSide = currentSide; } } else { int currentSide = Math.max(obj.w, obj.h); if ( closestObject == null || side > 100 && closestObject.location != null && closestObject.location.dc_id == Integer.MIN_VALUE || currentSide <= side && lastSide < currentSide ) { closestObject = obj; lastSide = currentSide; } } } return closestObject; } public static TLRPC.TL_photoPathSize getPathPhotoSize(ArrayList<TLRPC.PhotoSize> sizes) { if (sizes == null || sizes.isEmpty()) { return null; } for (int a = 0; a < sizes.size(); a++) { TLRPC.PhotoSize obj = sizes.get(a); if (obj instanceof TLRPC.TL_photoPathSize) { continue; } return (TLRPC.TL_photoPathSize) obj; } return null; } public static String getFileExtension(File file) { String name = file.getName(); try { return name.substring(name.lastIndexOf('.') + 1); } catch (Exception e) { return ""; } } public static String fixFileName(String fileName) { if (fileName != null) { fileName = fileName.replaceAll("[\u0001-\u001f<>\u202E:\"/\\\\|?*\u007f]+", "").trim(); } return fileName; } public static String getDocumentFileName(TLRPC.Document document) { if (document == null) { return null; } if (document.file_name_fixed != null) { return document.file_name_fixed; } String fileName = null; if (document != null) { if (document.file_name != null) { fileName = document.file_name; } else { for (int a = 0; a < document.attributes.size(); a++) { TLRPC.DocumentAttribute documentAttribute = document.attributes.get(a); if (documentAttribute instanceof TLRPC.TL_documentAttributeFilename) { fileName = documentAttribute.file_name; } } } } fileName = fixFileName(fileName); return fileName != null ? fileName : ""; } public static String getMimeTypePart(String mime) { int index; if ((index = mime.lastIndexOf('/')) != -1) { return mime.substring(index + 1); } return ""; } public static String getExtensionByMimeType(String mime) { if (mime != null) { switch (mime) { case "video/mp4": return ".mp4"; case "video/x-matroska": return ".mkv"; case "audio/ogg": return ".ogg"; } } return ""; } public static File getInternalCacheDir() { return ApplicationLoader.applicationContext.getCacheDir(); } public static String getDocumentExtension(TLRPC.Document document) { String fileName = getDocumentFileName(document); int idx = fileName.lastIndexOf('.'); String ext = null; if (idx != -1) { ext = fileName.substring(idx + 1); } if (ext == null || ext.length() == 0) { ext = document.mime_type; } if (ext == null) { ext = ""; } ext = ext.toUpperCase(); return ext; } public static String getAttachFileName(TLObject attach) { return getAttachFileName(attach, null); } public static String getAttachFileName(TLObject attach, String ext) { return getAttachFileName(attach, null, ext); } /** * file hash. contains docId, dcId, ext. */ public static String getAttachFileName(TLObject attach, String size, String ext) { if (attach instanceof TLRPC.Document) { TLRPC.Document document = (TLRPC.Document) attach; String docExt; docExt = getDocumentFileName(document); int idx; if ((idx = docExt.lastIndexOf('.')) == -1) { docExt = ""; } else { docExt = docExt.substring(idx); } if (docExt.length() <= 1) { docExt = getExtensionByMimeType(document.mime_type); } if (docExt.length() > 1) { return document.dc_id + "_" + document.id + docExt; } else { return document.dc_id + "_" + document.id; } } else if (attach instanceof SecureDocument) { SecureDocument secureDocument = (SecureDocument) attach; return secureDocument.secureFile.dc_id + "_" + secureDocument.secureFile.id + ".jpg"; } else if (attach instanceof TLRPC.TL_secureFile) { TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) attach; return secureFile.dc_id + "_" + secureFile.id + ".jpg"; } else if (attach instanceof WebFile) { WebFile document = (WebFile) attach; return Utilities.MD5(document.url) + "." + ImageLoader.getHttpUrlExtension(document.url, getMimeTypePart(document.mime_type)); } else if (attach instanceof TLRPC.PhotoSize) { TLRPC.PhotoSize photo = (TLRPC.PhotoSize) attach; if (photo.location == null || photo.location instanceof TLRPC.TL_fileLocationUnavailable) { return ""; } return photo.location.volume_id + "_" + photo.location.local_id + "." + (ext != null ? ext : "jpg"); } else if (attach instanceof TLRPC.TL_videoSize) { TLRPC.TL_videoSize video = (TLRPC.TL_videoSize) attach; if (video.location == null || video.location instanceof TLRPC.TL_fileLocationUnavailable) { return ""; } return video.location.volume_id + "_" + video.location.local_id + "." + (ext != null ? ext : "mp4"); } else if (attach instanceof TLRPC.FileLocation) { if (attach instanceof TLRPC.TL_fileLocationUnavailable) { return ""; } TLRPC.FileLocation location = (TLRPC.FileLocation) attach; return location.volume_id + "_" + location.local_id + "." + (ext != null ? ext : "jpg"); } else if (attach instanceof TLRPC.UserProfilePhoto) { if (size == null) { size = "s"; } TLRPC.UserProfilePhoto location = (TLRPC.UserProfilePhoto) attach; if (location.photo_small != null) { if ("s".equals(size)) { return getAttachFileName(location.photo_small, ext); } else { return getAttachFileName(location.photo_big, ext); } } else { return location.photo_id + "_" + size + "." + (ext != null ? ext : "jpg"); } } else if (attach instanceof TLRPC.ChatPhoto) { TLRPC.ChatPhoto location = (TLRPC.ChatPhoto) attach; if (location.photo_small != null) { if ("s".equals(size)) { return getAttachFileName(location.photo_small, ext); } else { return getAttachFileName(location.photo_big, ext); } } else { return location.photo_id + "_" + size + "." + (ext != null ? ext : "jpg"); } } return ""; } public void deleteFiles(final ArrayList<File> files, final int type) { if (files == null || files.isEmpty()) { return; } fileLoaderQueue.postRunnable(() -> { for (int a = 0; a < files.size(); a++) { File file = files.get(a); File encrypted = new File(file.getAbsolutePath() + ".enc"); if (encrypted.exists()) { try { if (!encrypted.delete()) { encrypted.deleteOnExit(); } } catch (Exception e) { FileLog.e(e); } try { File key = new File(FileLoader.getInternalCacheDir(), file.getName() + ".enc.key"); if (!key.delete()) { key.deleteOnExit(); } } catch (Exception e) { FileLog.e(e); } } else if (file.exists()) { try { if (!file.delete()) { file.deleteOnExit(); } } catch (Exception e) { FileLog.e(e); } } try { File qFile = new File(file.getParentFile(), "q_" + file.getName()); if (qFile.exists()) { if (!qFile.delete()) { qFile.deleteOnExit(); } } } catch (Exception e) { FileLog.e(e); } } if (type == 2) { ImageLoader.getInstance().clearMemory(); } }); } public static boolean isVideoMimeType(String mime) { return "video/mp4".equals(mime) || SharedConfig.streamMkv && "video/x-matroska".equals(mime); } public static boolean copyFile(InputStream sourceFile, File destFile) throws IOException { return copyFile(sourceFile, destFile, -1); } public static boolean copyFile(InputStream sourceFile, File destFile, int maxSize) throws IOException { FileOutputStream out = new FileOutputStream(destFile); byte[] buf = new byte[4096]; int len; int totalLen = 0; while ((len = sourceFile.read(buf)) > 0) { Thread.yield(); out.write(buf, 0, len); totalLen += len; if (maxSize > 0 && totalLen >= maxSize) { break; } } out.getFD().sync(); out.close(); return true; } public static boolean isSamePhoto(TLObject photo1, TLObject photo2) { if (photo1 == null && photo2 != null || photo1 != null && photo2 == null) { return false; } if (photo1 == null && photo2 == null) { return true; } if (photo1.getClass() != photo2.getClass()) { return false; } if (photo1 instanceof TLRPC.UserProfilePhoto) { TLRPC.UserProfilePhoto p1 = (TLRPC.UserProfilePhoto) photo1; TLRPC.UserProfilePhoto p2 = (TLRPC.UserProfilePhoto) photo2; return p1.photo_id == p2.photo_id; } else if (photo1 instanceof TLRPC.ChatPhoto) { TLRPC.ChatPhoto p1 = (TLRPC.ChatPhoto) photo1; TLRPC.ChatPhoto p2 = (TLRPC.ChatPhoto) photo2; return p1.photo_id == p2.photo_id; } return false; } public static boolean isSamePhoto(TLRPC.FileLocation location, TLRPC.Photo photo) { if (location == null || !(photo instanceof TLRPC.TL_photo)) { return false; } for (int b = 0, N = photo.sizes.size(); b < N; b++) { TLRPC.PhotoSize size = photo.sizes.get(b); if (size.location != null && size.location.local_id == location.local_id && size.location.volume_id == location.volume_id) { return true; } } if (-location.volume_id == photo.id) { return true; } return false; } public static long getPhotoId(TLObject object) { if (object instanceof TLRPC.Photo) { return ((TLRPC.Photo) object).id; } else if (object instanceof TLRPC.ChatPhoto) { return ((TLRPC.ChatPhoto) object).photo_id; } else if (object instanceof TLRPC.UserProfilePhoto) { return ((TLRPC.UserProfilePhoto) object).photo_id; } return 0; } public void getCurrentLoadingFiles(ArrayList<MessageObject> currentLoadingFiles) { currentLoadingFiles.clear(); currentLoadingFiles.addAll(getDownloadController().downloadingFiles); for (int i = 0; i < currentLoadingFiles.size(); i++) { currentLoadingFiles.get(i).isDownloadingFile = true; } } public void getRecentLoadingFiles(ArrayList<MessageObject> recentLoadingFiles) { recentLoadingFiles.clear(); recentLoadingFiles.addAll(getDownloadController().recentDownloadingFiles); for (int i = 0; i < recentLoadingFiles.size(); i++) { recentLoadingFiles.get(i).isDownloadingFile = true; } } public void checkCurrentDownloadsFiles() { ArrayList<MessageObject> messagesToRemove = new ArrayList<>(); ArrayList<MessageObject> messageObjects = new ArrayList<>(getDownloadController().recentDownloadingFiles); for (int i = 0; i < messageObjects.size(); i++) { messageObjects.get(i).checkMediaExistance(); if (messageObjects.get(i).mediaExists) { messagesToRemove.add(messageObjects.get(i)); } } if (!messagesToRemove.isEmpty()) { AndroidUtilities.runOnUIThread(() -> { getDownloadController().recentDownloadingFiles.removeAll(messagesToRemove); getNotificationCenter().postNotificationName(NotificationCenter.onDownloadingFilesChanged); }); } } /** * optimezed for bulk messages */ public void checkMediaExistance(ArrayList<MessageObject> messageObjects) { getFileDatabase().checkMediaExistance(messageObjects); } public interface FileResolver { File getFile(); } public void clearRecentDownloadedFiles() { getDownloadController().clearRecentDownloadedFiles(); } public void clearFilePaths() { filePathDatabase.clear(); } public static boolean checkUploadFileSize(int currentAccount, long length) { boolean premium = AccountInstance.getInstance(currentAccount).getUserConfig().isPremium(); if (length < DEFAULT_MAX_FILE_SIZE || (length < DEFAULT_MAX_FILE_SIZE_PREMIUM && premium)) { return true; } return false; } private static class LoadOperationUIObject { Runnable loadInternalRunnable; } public static byte[] longToBytes(long x) { ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); buffer.putLong(x); return buffer.array(); } public static long bytesToLong(byte[] bytes) { long l = 0; for (int i = 0; i < 8; i++) { l <<= 8; l ^= bytes[i] & 0xFF; } return l; } Runnable dumpFilesQueueRunnable = () -> { for (int i = 0; i < smallFilesQueue.length; i++) { if (smallFilesQueue[i].getCount() > 0 || largeFilesQueue[i].getCount() > 0) { FileLog.d("download queue: dc" + (i + 1) + " account=" + currentAccount + " small_operations=" + smallFilesQueue[i].getCount() + " large_operations=" + largeFilesQueue[i].getCount()); } } dumpFilesQueue(); }; public void dumpFilesQueue() { if (!BuildVars.LOGS_ENABLED) { return; } fileLoaderQueue.cancelRunnable(dumpFilesQueueRunnable); fileLoaderQueue.postRunnable(dumpFilesQueueRunnable, 10_000); } }
diskree/Telegram-Termux
TMessagesProj/src/main/java/org/telegram/messenger/FileLoader.java
41,693
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.grid.node.docker; import static org.openqa.selenium.grid.config.StandardGridRoles.NODE_ROLE; import com.beust.jcommander.Parameter; import com.google.auto.service.AutoService; import java.util.Collections; import java.util.List; import java.util.Set; import org.openqa.selenium.grid.config.ConfigValue; import org.openqa.selenium.grid.config.HasRoles; import org.openqa.selenium.grid.config.NonSplittingSplitter; import org.openqa.selenium.grid.config.Role; @SuppressWarnings("FieldMayBeFinal") @AutoService(HasRoles.class) public class DockerFlags implements HasRoles { @Parameter( names = {"--docker-url"}, description = "URL for connecting to the docker daemon") @ConfigValue( section = DockerOptions.DOCKER_SECTION, name = "url", example = "\"" + DockerOptions.DEFAULT_DOCKER_URL + "\"") private String dockerUrl; @Parameter( names = {"--docker-host"}, description = "Host name where the docker daemon is running") @ConfigValue(section = DockerOptions.DOCKER_SECTION, name = "host", example = "\"localhost\"") private String dockerHost; @Parameter( names = {"--docker-port"}, description = "Port where the docker daemon is running") @ConfigValue(section = DockerOptions.DOCKER_SECTION, name = "port", example = "2375") private Integer dockerPort; @Parameter( names = {"--docker", "-D"}, description = "Docker configs which map image name to stereotype capabilities (example: " + "-D selenium/standalone-firefox:latest '{\"browserName\": \"firefox\"}')", arity = 2, variableArity = true, splitter = NonSplittingSplitter.class) @ConfigValue( section = DockerOptions.DOCKER_SECTION, name = "configs", example = "[\"selenium/standalone-firefox:latest\", \"{\\\"browserName\\\": \\\"firefox\\\"}\"]") private List<String> images2Capabilities; @Parameter( names = {"--docker-host-config-keys"}, description = "Specify which docker host configuration keys should be passed to browser containers." + " Keys name can be found in the Docker API documentation, or by running `docker" + " inspect` the node-docker container.") @ConfigValue( section = DockerOptions.DOCKER_SECTION, name = "host-config-keys", example = "[\"Dns\", \"DnsOptions\", \"DnsSearch\", \"ExtraHosts\", \"Binds\"]") private List<String> hostConfigKeys; @Parameter( names = {"--docker-devices"}, description = "Exposes devices to a container. Each device mapping declaration must have at least the" + " path of the device in both host and container separated by a colon like in this" + " example: /device/path/in/host:/device/path/in/container", arity = 1, variableArity = true, splitter = NonSplittingSplitter.class) @ConfigValue( section = DockerOptions.DOCKER_SECTION, name = "devices", example = "[\"/dev/kvm:/dev/kvm\"]") private List<String> devices; @Parameter( names = {"--docker-video-image"}, description = "Docker image to be used when video recording is enabled") @ConfigValue( section = DockerOptions.DOCKER_SECTION, name = "video-image", example = DockerOptions.DEFAULT_VIDEO_IMAGE) private String videoImage = DockerOptions.DEFAULT_VIDEO_IMAGE; @Parameter( names = {"--docker-assets-path"}, description = "Absolute path where assets will be stored") @ConfigValue( section = DockerOptions.DOCKER_SECTION, name = "assets-path", example = "\"" + DockerOptions.DEFAULT_ASSETS_PATH + "\"") private String assetsPath; @Override public Set<Role> getRoles() { return Collections.singleton(NODE_ROLE); } }
SeleniumHQ/selenium
java/src/org/openqa/selenium/grid/node/docker/DockerFlags.java
41,694
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.ui.Components; import android.Manifest; import android.app.Activity; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import androidx.core.content.FileProvider; import androidx.exifinterface.media.ExifInterface; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.ImageLoader; import org.telegram.messenger.ImageLocation; import org.telegram.messenger.ImageReceiver; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MediaController; import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessagesController; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.SendMessagesHelper; import org.telegram.messenger.SharedConfig; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; import org.telegram.messenger.VideoEditedInfo; import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.BottomSheet; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.BasePermissionsActivity; import org.telegram.ui.LaunchActivity; import org.telegram.ui.PhotoAlbumPickerActivity; import org.telegram.ui.PhotoCropActivity; import org.telegram.ui.PhotoPickerActivity; import org.telegram.ui.PhotoViewer; import java.io.File; import java.util.ArrayList; import java.util.HashMap; public class ImageUpdater implements NotificationCenter.NotificationCenterDelegate, PhotoCropActivity.PhotoEditActivityDelegate { private final static int ID_TAKE_PHOTO = 0, ID_UPLOAD_FROM_GALLERY = 1, ID_SEARCH_WEB = 2, ID_REMOVE_PHOTO = 3, ID_RECORD_VIDEO = 4; public final static int FOR_TYPE_USER = 0; public final static int FOR_TYPE_CHANNEL = 1; public final static int FOR_TYPE_GROUP = 2; public BaseFragment parentFragment; private ImageUpdaterDelegate delegate; private ChatAttachAlert chatAttachAlert; private int currentAccount = UserConfig.selectedAccount; private ImageReceiver imageReceiver; public String currentPicturePath; private TLRPC.PhotoSize bigPhoto; private TLRPC.PhotoSize smallPhoto; private boolean isVideo; private String uploadingImage; private String uploadingVideo; private String videoPath; private MessageObject convertingVideo; private File picturePath = null; private String finalPath; private boolean clearAfterUpdate; private boolean useAttachMenu = true; private boolean openWithFrontfaceCamera; private boolean supportEmojiMarkup; private boolean searchAvailable = true; private boolean uploadAfterSelect = true; private TLRPC.User user; private boolean isUser; private TLRPC.InputFile uploadedPhoto; private TLRPC.InputFile uploadedVideo; private TLRPC.VideoSize vectorMarkup; private double videoTimestamp; private boolean canSelectVideo; private boolean forceDarkTheme; private boolean showingFromDialog; private boolean canceled; private boolean forUser; private final static int attach_photo = 0; public final static int TYPE_DEFAULT = 0; public final static int TYPE_SET_PHOTO_FOR_USER = 1; public final static int TYPE_SUGGEST_PHOTO_FOR_USER = 2; private int type; public final int setForType; public void processEntry(MediaController.PhotoEntry photoEntry) { String path = null; if (photoEntry.imagePath != null) { path = photoEntry.imagePath; } else { path = photoEntry.path; } MessageObject avatarObject = null; Bitmap bitmap; if (photoEntry.isVideo || photoEntry.editedInfo != null) { TLRPC.TL_message message = new TLRPC.TL_message(); message.id = 0; message.message = ""; message.media = new TLRPC.TL_messageMediaEmpty(); message.action = new TLRPC.TL_messageActionEmpty(); message.dialog_id = 0; avatarObject = new MessageObject(UserConfig.selectedAccount, message, false, false); avatarObject.messageOwner.attachPath = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE), SharedConfig.getLastLocalId() + "_avatar.mp4").getAbsolutePath(); avatarObject.videoEditedInfo = photoEntry.editedInfo; avatarObject.emojiMarkup = photoEntry.emojiMarkup; bitmap = ImageLoader.loadBitmap(photoEntry.thumbPath, null, 800, 800, true); } else { bitmap = ImageLoader.loadBitmap(path, null, 800, 800, true); } processBitmap(bitmap, avatarObject); } public void cancel() { canceled = true; if (uploadingImage != null) { FileLoader.getInstance(currentAccount).cancelFileUpload(uploadingImage, false); } if (uploadingVideo != null) { FileLoader.getInstance(currentAccount).cancelFileUpload(uploadingVideo, false); } if (delegate != null) { delegate.didUploadFailed(); } } public boolean isCanceled() { return canceled; } public void showAvatarConstructor(TLRPC.VideoSize emojiMarkup) { createChatAttachView(); chatAttachAlert.getPhotoLayout().showAvatarConstructorFragment(null, emojiMarkup); } public interface ImageUpdaterDelegate { void didUploadPhoto(TLRPC.InputFile photo, TLRPC.InputFile video, double videoStartTimestamp, String videoPath, TLRPC.PhotoSize bigSize, TLRPC.PhotoSize smallSize, boolean isVideo, TLRPC.VideoSize emojiMarkup); default String getInitialSearchString() { return null; } default void onUploadProgressChanged(float progress) { } default void didStartUpload(boolean isVideo) { } default void didUploadFailed() { } default boolean canFinishFragment() { return true; } } public boolean isUploadingImage() { return uploadingImage != null || uploadingVideo != null || convertingVideo != null; } public void clear() { canceled = false; if (uploadingImage != null || uploadingVideo != null || convertingVideo != null) { clearAfterUpdate = true; } else { parentFragment = null; delegate = null; } if (chatAttachAlert != null) { chatAttachAlert.dismissInternal(); chatAttachAlert.onDestroy(); } } public void setOpenWithFrontfaceCamera(boolean value) { openWithFrontfaceCamera = value; } public ImageUpdater(boolean allowVideo, int setForType, boolean supportEmojiMarkup) { imageReceiver = new ImageReceiver(null); canSelectVideo = allowVideo; this.supportEmojiMarkup = supportEmojiMarkup; this.setForType = setForType; } public void setCanSelectVideo(boolean canSelectVideo) { this.canSelectVideo = canSelectVideo; } public void setDelegate(ImageUpdaterDelegate imageUpdaterDelegate) { delegate = imageUpdaterDelegate; } public void openMenu(boolean hasAvatar, Runnable onDeleteAvatar, DialogInterface.OnDismissListener onDismiss, int type) { if (parentFragment == null || parentFragment.getParentActivity() == null) { return; } canceled = false; this.type = type; if (useAttachMenu) { openAttachMenu(onDismiss); return; } BottomSheet.Builder builder = new BottomSheet.Builder(parentFragment.getParentActivity()); if (type == TYPE_SET_PHOTO_FOR_USER) { builder.setTitle(LocaleController.formatString("SetPhotoFor", R.string.SetPhotoFor, user.first_name), true); } else if (type == TYPE_SUGGEST_PHOTO_FOR_USER) { builder.setTitle(LocaleController.formatString("SuggestPhotoFor", R.string.SuggestPhotoFor, user.first_name), true); } else { builder.setTitle(LocaleController.getString("ChoosePhoto", R.string.ChoosePhoto), true); } ArrayList<CharSequence> items = new ArrayList<>(); ArrayList<Integer> icons = new ArrayList<>(); ArrayList<Integer> ids = new ArrayList<>(); items.add(LocaleController.getString("ChooseTakePhoto", R.string.ChooseTakePhoto)); icons.add(R.drawable.msg_camera); ids.add(ID_TAKE_PHOTO); if (canSelectVideo) { items.add(LocaleController.getString("ChooseRecordVideo", R.string.ChooseRecordVideo)); icons.add(R.drawable.msg_video); ids.add(ID_RECORD_VIDEO); } items.add(LocaleController.getString("ChooseFromGallery", R.string.ChooseFromGallery)); icons.add(R.drawable.msg_photos); ids.add(ID_UPLOAD_FROM_GALLERY); if (searchAvailable) { items.add(LocaleController.getString("ChooseFromSearch", R.string.ChooseFromSearch)); icons.add(R.drawable.msg_search); ids.add(ID_SEARCH_WEB); } if (hasAvatar) { items.add(LocaleController.getString("DeletePhoto", R.string.DeletePhoto)); icons.add(R.drawable.msg_delete); ids.add(ID_REMOVE_PHOTO); } int[] iconsRes = new int[icons.size()]; for (int i = 0, N = icons.size(); i < N; i++) { iconsRes[i] = icons.get(i); } builder.setItems(items.toArray(new CharSequence[0]), iconsRes, (dialogInterface, i) -> { int id = ids.get(i); switch (id) { case ID_TAKE_PHOTO: openCamera(); break; case ID_UPLOAD_FROM_GALLERY: openGallery(); break; case ID_SEARCH_WEB: openSearch(); break; case ID_REMOVE_PHOTO: onDeleteAvatar.run(); break; case ID_RECORD_VIDEO: openVideoCamera(); break; } }); BottomSheet sheet = builder.create(); sheet.setOnHideListener(onDismiss); parentFragment.showDialog(sheet); if (hasAvatar) { sheet.setItemColor(items.size() - 1, Theme.getColor(Theme.key_dialogTextRed2), Theme.getColor(Theme.key_dialogRedIcon)); } } public void setSearchAvailable(boolean value) { useAttachMenu = searchAvailable = value; } public void setSearchAvailable(boolean value, boolean useAttachMenu) { this.useAttachMenu = useAttachMenu; searchAvailable = value; } public void setUploadAfterSelect(boolean value) { uploadAfterSelect = value; } public void onResume() { if (chatAttachAlert != null) { chatAttachAlert.onResume(); } } public void onPause() { if (chatAttachAlert != null) { chatAttachAlert.onPause(); } } public boolean dismissDialogOnPause(Dialog dialog) { return dialog != chatAttachAlert; } public boolean dismissCurrentDialog(Dialog dialog) { if (chatAttachAlert != null && dialog == chatAttachAlert) { chatAttachAlert.getPhotoLayout().closeCamera(false); chatAttachAlert.dismissInternal(); chatAttachAlert.getPhotoLayout().hideCamera(true); return true; } return false; } public void openSearch() { if (parentFragment == null) { return; } final HashMap<Object, Object> photos = new HashMap<>(); final ArrayList<Object> order = new ArrayList<>(); PhotoPickerActivity fragment = new PhotoPickerActivity(0, null, photos, order, 1, false, null, forceDarkTheme); fragment.setDelegate(new PhotoPickerActivity.PhotoPickerActivityDelegate() { private boolean sendPressed; @Override public void selectedPhotosChanged() { } private void sendSelectedPhotos(HashMap<Object, Object> photos, ArrayList<Object> order, boolean notify, int scheduleDate) { } @Override public void actionButtonPressed(boolean canceled, boolean notify, int scheduleDate) { if (photos.isEmpty() || delegate == null || sendPressed || canceled) { return; } sendPressed = true; ArrayList<SendMessagesHelper.SendingMediaInfo> media = new ArrayList<>(); for (int a = 0; a < order.size(); a++) { Object object = photos.get(order.get(a)); SendMessagesHelper.SendingMediaInfo info = new SendMessagesHelper.SendingMediaInfo(); media.add(info); if (object instanceof MediaController.SearchImage) { MediaController.SearchImage searchImage = (MediaController.SearchImage) object; if (searchImage.imagePath != null) { info.path = searchImage.imagePath; } else { info.searchImage = searchImage; } info.videoEditedInfo = searchImage.editedInfo; info.thumbPath = searchImage.thumbPath; info.caption = searchImage.caption != null ? searchImage.caption.toString() : null; info.entities = searchImage.entities; info.masks = searchImage.stickers; info.ttl = searchImage.ttl; } } didSelectPhotos(media); } @Override public void onCaptionChanged(CharSequence caption) { } @Override public boolean canFinishFragment() { return delegate.canFinishFragment(); } }); fragment.setMaxSelectedPhotos(1, false); fragment.setInitialSearchString(delegate.getInitialSearchString()); if (showingFromDialog) { parentFragment.showAsSheet(fragment); } else { parentFragment.presentFragment(fragment); } } private void openAttachMenu(DialogInterface.OnDismissListener onDismissListener) { if (parentFragment == null || parentFragment.getParentActivity() == null) { return; } createChatAttachView(); chatAttachAlert.setOpenWithFrontFaceCamera(openWithFrontfaceCamera); chatAttachAlert.setMaxSelectedPhotos(1, false); chatAttachAlert.getPhotoLayout().loadGalleryPhotos(); if (Build.VERSION.SDK_INT == 21 || Build.VERSION.SDK_INT == 22) { AndroidUtilities.hideKeyboard(parentFragment.getFragmentView().findFocus()); } chatAttachAlert.init(); chatAttachAlert.setOnHideListener(onDismissListener); if (type != 0) { chatAttachAlert.avatarFor(new AvatarFor(user, type)); } chatAttachAlert.forUser = forUser; parentFragment.showDialog(chatAttachAlert); } private void createChatAttachView() { if (parentFragment == null || parentFragment.getParentActivity() == null) { return; } if (chatAttachAlert == null) { chatAttachAlert = new ChatAttachAlert(parentFragment.getParentActivity(), parentFragment, forceDarkTheme, showingFromDialog); chatAttachAlert.setAvatarPicker(canSelectVideo ? 2 : 1, searchAvailable); chatAttachAlert.setDelegate(new ChatAttachAlert.ChatAttachViewDelegate() { @Override public void didPressedButton(int button, boolean arg, boolean notify, int scheduleDate, boolean forceDocument) { if (parentFragment == null || parentFragment.getParentActivity() == null || chatAttachAlert == null) { return; } if (button == 8 || button == 7) { HashMap<Object, Object> photos = chatAttachAlert.getPhotoLayout().getSelectedPhotos(); ArrayList<Object> order = chatAttachAlert.getPhotoLayout().getSelectedPhotosOrder(); ArrayList<SendMessagesHelper.SendingMediaInfo> media = new ArrayList<>(); for (int a = 0; a < order.size(); a++) { Object object = photos.get(order.get(a)); SendMessagesHelper.SendingMediaInfo info = new SendMessagesHelper.SendingMediaInfo(); media.add(info); if (object instanceof MediaController.PhotoEntry) { MediaController.PhotoEntry photoEntry = (MediaController.PhotoEntry) object; if (photoEntry.imagePath != null) { info.path = photoEntry.imagePath; } else { info.path = photoEntry.path; } info.thumbPath = photoEntry.thumbPath; info.videoEditedInfo = photoEntry.editedInfo; info.isVideo = photoEntry.isVideo; info.caption = photoEntry.caption != null ? photoEntry.caption.toString() : null; info.entities = photoEntry.entities; info.masks = photoEntry.stickers; info.ttl = photoEntry.ttl; info.emojiMarkup = photoEntry.emojiMarkup; } else if (object instanceof MediaController.SearchImage) { MediaController.SearchImage searchImage = (MediaController.SearchImage) object; if (searchImage.imagePath != null) { info.path = searchImage.imagePath; } else { info.searchImage = searchImage; } info.thumbPath = searchImage.thumbPath; info.videoEditedInfo = searchImage.editedInfo; info.caption = searchImage.caption != null ? searchImage.caption.toString() : null; info.entities = searchImage.entities; info.masks = searchImage.stickers; info.ttl = searchImage.ttl; if (searchImage.inlineResult != null && searchImage.type == 1) { info.inlineResult = searchImage.inlineResult; info.params = searchImage.params; } searchImage.date = (int) (System.currentTimeMillis() / 1000); } } didSelectPhotos(media); if (button != 8) { chatAttachAlert.dismiss(true); } return; } else { chatAttachAlert.dismissWithButtonClick(button); } processSelectedAttach(button); } @Override public View getRevealView() { return null; } @Override public void didSelectBot(TLRPC.User user) { } @Override public void onCameraOpened() { AndroidUtilities.hideKeyboard(parentFragment.getFragmentView().findFocus()); } @Override public boolean needEnterComment() { return false; } @Override public void doOnIdle(Runnable runnable) { runnable.run(); } private void processSelectedAttach(int which) { if (which == attach_photo) { openCamera(); } } @Override public void openAvatarsSearch() { openSearch(); } }); chatAttachAlert.setImageUpdater(this); } if (type == TYPE_SET_PHOTO_FOR_USER) { chatAttachAlert.getSelectedTextView().setText(LocaleController.formatString("SetPhotoFor", R.string.SetPhotoFor, user.first_name)); } else if (type == TYPE_SUGGEST_PHOTO_FOR_USER) { chatAttachAlert.getSelectedTextView().setText(LocaleController.formatString("SuggestPhotoFor", R.string.SuggestPhotoFor, user.first_name)); } } private void didSelectPhotos(ArrayList<SendMessagesHelper.SendingMediaInfo> photos) { if (!photos.isEmpty()) { SendMessagesHelper.SendingMediaInfo info = photos.get(0); Bitmap bitmap = null; MessageObject avatarObject = null; if (info.isVideo || info.videoEditedInfo != null) { TLRPC.TL_message message = new TLRPC.TL_message(); message.id = 0; message.message = ""; message.media = new TLRPC.TL_messageMediaEmpty(); message.action = new TLRPC.TL_messageActionEmpty(); message.dialog_id = 0; avatarObject = new MessageObject(UserConfig.selectedAccount, message, false, false); avatarObject.messageOwner.attachPath = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE), SharedConfig.getLastLocalId() + "_avatar.mp4").getAbsolutePath(); avatarObject.videoEditedInfo = info.videoEditedInfo; avatarObject.emojiMarkup = info.emojiMarkup; bitmap = ImageLoader.loadBitmap(info.thumbPath, null, 800, 800, true); } else if (info.path != null) { bitmap = ImageLoader.loadBitmap(info.path, null, 800, 800, true); } else if (info.searchImage != null) { if (info.searchImage.photo != null) { TLRPC.PhotoSize photoSize = FileLoader.getClosestPhotoSizeWithSize(info.searchImage.photo.sizes, AndroidUtilities.getPhotoSize()); if (photoSize != null) { File path = FileLoader.getInstance(currentAccount).getPathToAttach(photoSize, true); finalPath = path.getAbsolutePath(); if (!path.exists()) { path = FileLoader.getInstance(currentAccount).getPathToAttach(photoSize, false); if (!path.exists()) { path = null; } } if (path != null) { bitmap = ImageLoader.loadBitmap(path.getAbsolutePath(), null, 800, 800, true); } else { NotificationCenter.getInstance(currentAccount).addObserver(ImageUpdater.this, NotificationCenter.fileLoaded); NotificationCenter.getInstance(currentAccount).addObserver(ImageUpdater.this, NotificationCenter.fileLoadFailed); uploadingImage = FileLoader.getAttachFileName(photoSize.location); imageReceiver.setImage(ImageLocation.getForPhoto(photoSize, info.searchImage.photo), null, null, "jpg", null, 1); } } } else if (info.searchImage.imageUrl != null) { String md5 = Utilities.MD5(info.searchImage.imageUrl) + "." + ImageLoader.getHttpUrlExtension(info.searchImage.imageUrl, "jpg"); File cacheFile = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE), md5); finalPath = cacheFile.getAbsolutePath(); if (cacheFile.exists() && cacheFile.length() != 0) { bitmap = ImageLoader.loadBitmap(cacheFile.getAbsolutePath(), null, 800, 800, true); } else { uploadingImage = info.searchImage.imageUrl; NotificationCenter.getInstance(currentAccount).addObserver(ImageUpdater.this, NotificationCenter.httpFileDidLoad); NotificationCenter.getInstance(currentAccount).addObserver(ImageUpdater.this, NotificationCenter.httpFileDidFailedLoad); imageReceiver.setImage(info.searchImage.imageUrl, null, null, "jpg", 1); } } } processBitmap(bitmap, avatarObject); } } public void openCamera() { if (parentFragment == null || parentFragment.getParentActivity() == null) { return; } try { if (Build.VERSION.SDK_INT >= 23 && parentFragment.getParentActivity().checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { parentFragment.getParentActivity().requestPermissions(new String[]{Manifest.permission.CAMERA}, BasePermissionsActivity.REQUEST_CODE_OPEN_CAMERA); return; } Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File image = AndroidUtilities.generatePicturePath(); if (image != null) { if (Build.VERSION.SDK_INT >= 24) { takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(parentFragment.getParentActivity(), ApplicationLoader.getApplicationId() + ".provider", image)); takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } else { takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image)); } currentPicturePath = image.getAbsolutePath(); } parentFragment.startActivityForResult(takePictureIntent, 13); } catch (Exception e) { FileLog.e(e); } } public void openVideoCamera() { if (parentFragment == null || parentFragment.getParentActivity() == null) { return; } try { if (Build.VERSION.SDK_INT >= 23 && parentFragment.getParentActivity().checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { parentFragment.getParentActivity().requestPermissions(new String[]{Manifest.permission.CAMERA}, 19); return; } Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); File video = AndroidUtilities.generateVideoPath(); if (video != null) { if (Build.VERSION.SDK_INT >= 24) { takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(parentFragment.getParentActivity(), ApplicationLoader.getApplicationId() + ".provider", video)); takeVideoIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); takeVideoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } else if (Build.VERSION.SDK_INT >= 18) { takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(video)); } takeVideoIntent.putExtra("android.intent.extras.CAMERA_FACING", 1); takeVideoIntent.putExtra("android.intent.extras.LENS_FACING_FRONT", 1); takeVideoIntent.putExtra("android.intent.extra.USE_FRONT_CAMERA", true); takeVideoIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10); currentPicturePath = video.getAbsolutePath(); } parentFragment.startActivityForResult(takeVideoIntent, 15); } catch (Exception e) { FileLog.e(e); } } public void onRequestPermissionsResultFragment(int requestCode, String[] permissions, int[] grantResults) { if (chatAttachAlert != null) { if (requestCode == 17) { chatAttachAlert.getPhotoLayout().checkCamera(false); chatAttachAlert.getPhotoLayout().checkStorage(); } else if (requestCode == BasePermissionsActivity.REQUEST_CODE_EXTERNAL_STORAGE) { chatAttachAlert.getPhotoLayout().checkStorage(); } } } public void openGallery() { if (parentFragment == null) { return; } if (Build.VERSION.SDK_INT >= 23 && parentFragment.getParentActivity() != null) { if (parentFragment.getParentActivity().checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { parentFragment.getParentActivity().requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, BasePermissionsActivity.REQUEST_CODE_EXTERNAL_STORAGE_FOR_AVATAR); return; } } PhotoAlbumPickerActivity fragment = new PhotoAlbumPickerActivity(canSelectVideo ? PhotoAlbumPickerActivity.SELECT_TYPE_AVATAR_VIDEO : PhotoAlbumPickerActivity.SELECT_TYPE_AVATAR, false, false, null); fragment.setAllowSearchImages(searchAvailable); fragment.setDelegate(new PhotoAlbumPickerActivity.PhotoAlbumPickerActivityDelegate() { @Override public void didSelectPhotos(ArrayList<SendMessagesHelper.SendingMediaInfo> photos, boolean notify, int scheduleDate) { ImageUpdater.this.didSelectPhotos(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(e); } } }); parentFragment.presentFragment(fragment); } private void startCrop(String path, Uri uri) { AndroidUtilities.runOnUIThread(() -> { try { LaunchActivity activity = (LaunchActivity) parentFragment.getParentActivity(); if (activity == null) { return; } Bundle args = new Bundle(); if (path != null) { args.putString("photoPath", path); } else if (uri != null) { args.putParcelable("photoUri", uri); } PhotoCropActivity photoCropActivity = new PhotoCropActivity(args); photoCropActivity.setDelegate(this); activity.presentFragment(photoCropActivity); } catch (Exception e) { FileLog.e(e); Bitmap bitmap = ImageLoader.loadBitmap(path, uri, 800, 800, true); processBitmap(bitmap, null); } }); } public void openPhotoForEdit(String path, String thumb, int orientation, boolean isVideo) { final ArrayList<Object> arrayList = new ArrayList<>(); MediaController.PhotoEntry photoEntry = new MediaController.PhotoEntry(0, 0, 0, path, orientation, false, 0, 0, 0); photoEntry.isVideo = isVideo; photoEntry.thumbPath = thumb; arrayList.add(photoEntry); PhotoViewer.getInstance().setParentActivity(parentFragment); PhotoViewer.getInstance().openPhotoForSelect(arrayList, 0, PhotoViewer.SELECT_TYPE_AVATAR, false, new PhotoViewer.EmptyPhotoViewerProvider() { @Override public void sendButtonPressed(int index, VideoEditedInfo videoEditedInfo, boolean notify, int scheduleDate, boolean forceDocument) { MediaController.PhotoEntry photoEntry = (MediaController.PhotoEntry) arrayList.get(0); processEntry(photoEntry); } @Override public boolean allowCaption() { return false; } @Override public boolean canScrollAway() { return false; } }, null); } public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { if (requestCode == 0 || requestCode == 2) { createChatAttachView(); if (chatAttachAlert != null) { chatAttachAlert.onActivityResultFragment(requestCode, data, currentPicturePath); } currentPicturePath = null; } else if (requestCode == 13) { parentFragment.getParentActivity().overridePendingTransition(R.anim.alpha_in, R.anim.alpha_out); PhotoViewer.getInstance().setParentActivity(parentFragment); 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(e); } openPhotoForEdit(currentPicturePath, null, orientation, false); AndroidUtilities.addMediaToGallery(currentPicturePath); currentPicturePath = null; } else if (requestCode == 14) { if (data == null || data.getData() == null) { return; } startCrop(null, data.getData()); } else if (requestCode == 15) { openPhotoForEdit(currentPicturePath, null, 0, true); AndroidUtilities.addMediaToGallery(currentPicturePath); currentPicturePath = null; } } } private void processBitmap(Bitmap bitmap, MessageObject avatarObject) { if (bitmap == null) { return; } uploadedVideo = null; uploadedPhoto = null; convertingVideo = null; videoPath = null; vectorMarkup = avatarObject == null ? null : avatarObject.emojiMarkup; bigPhoto = ImageLoader.scaleAndSaveImage(bitmap, 800, 800, 80, false, 320, 320); smallPhoto = ImageLoader.scaleAndSaveImage(bitmap, 150, 150, 80, false, 150, 150); if (smallPhoto != null) { try { Bitmap b = BitmapFactory.decodeFile(FileLoader.getInstance(currentAccount).getPathToAttach(smallPhoto, true).getAbsolutePath()); String key = smallPhoto.location.volume_id + "_" + smallPhoto.location.local_id + "@50_50"; ImageLoader.getInstance().putImageToCache(new BitmapDrawable(b), key, true); } catch (Throwable ignore) { } } bitmap.recycle(); if (bigPhoto != null) { UserConfig.getInstance(currentAccount).saveConfig(false); uploadingImage = FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE) + "/" + bigPhoto.location.volume_id + "_" + bigPhoto.location.local_id + ".jpg"; if (uploadAfterSelect) { if (avatarObject != null && avatarObject.videoEditedInfo != null) { if (supportEmojiMarkup && !MessagesController.getInstance(currentAccount).uploadMarkupVideo) { if (delegate != null) { delegate.didStartUpload(true); } if (delegate != null) { //skip upload step delegate.didUploadPhoto(null, null, 0, null, bigPhoto, smallPhoto, isVideo, null); delegate.didUploadPhoto(null, null, videoTimestamp, videoPath, bigPhoto, smallPhoto, isVideo, vectorMarkup); cleanup(); } return; } convertingVideo = avatarObject; long startTime = avatarObject.videoEditedInfo.startTime < 0 ? 0 : avatarObject.videoEditedInfo.startTime; videoTimestamp = (avatarObject.videoEditedInfo.avatarStartTime - startTime) / 1000000.0; avatarObject.videoEditedInfo.shouldLimitFps = false; NotificationCenter.getInstance(currentAccount).addObserver(ImageUpdater.this, NotificationCenter.filePreparingStarted); NotificationCenter.getInstance(currentAccount).addObserver(ImageUpdater.this, NotificationCenter.filePreparingFailed); NotificationCenter.getInstance(currentAccount).addObserver(ImageUpdater.this, NotificationCenter.fileNewChunkAvailable); MediaController.getInstance().scheduleVideoConvert(avatarObject, true); uploadingImage = null; if (delegate != null) { delegate.didStartUpload(true); } isVideo = true; } else { if (delegate != null) { delegate.didStartUpload(false); } isVideo = false; } NotificationCenter.getInstance(currentAccount).addObserver(ImageUpdater.this, NotificationCenter.fileUploaded); NotificationCenter.getInstance(currentAccount).addObserver(ImageUpdater.this, NotificationCenter.fileUploadProgressChanged); NotificationCenter.getInstance(currentAccount).addObserver(ImageUpdater.this, NotificationCenter.fileUploadFailed); if (uploadingImage != null) { FileLoader.getInstance(currentAccount).uploadFile(uploadingImage, false, true, ConnectionsManager.FileTypePhoto); } } if (delegate != null) { delegate.didUploadPhoto(null, null, 0, null, bigPhoto, smallPhoto, isVideo, null); } } } @Override public void didFinishEdit(Bitmap bitmap) { processBitmap(bitmap, null); } private void cleanup() { uploadingImage = null; uploadingVideo = null; videoPath = null; convertingVideo = null; if (clearAfterUpdate) { imageReceiver.setImageBitmap((Drawable) null); parentFragment = null; delegate = null; } } private float currentImageProgress; @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.fileUploaded || id == NotificationCenter.fileUploadFailed) { String location = (String) args[0]; if (location.equals(uploadingImage)) { uploadingImage = null; if (id == NotificationCenter.fileUploaded) { uploadedPhoto = (TLRPC.InputFile) args[1]; } } else if (location.equals(uploadingVideo)) { uploadingVideo = null; if (id == NotificationCenter.fileUploaded) { uploadedVideo = (TLRPC.InputFile) args[1]; } } else { return; } if (uploadingImage == null && uploadingVideo == null && convertingVideo == null) { NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.fileUploaded); NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.fileUploadProgressChanged); NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.fileUploadFailed); if (id == NotificationCenter.fileUploaded) { if (delegate != null) { delegate.didUploadPhoto(uploadedPhoto, uploadedVideo, videoTimestamp, videoPath, bigPhoto, smallPhoto, isVideo, vectorMarkup); } } cleanup(); } } else if (id == NotificationCenter.fileUploadProgressChanged) { String location = (String) args[0]; String path = convertingVideo != null ? uploadingVideo : uploadingImage; if (delegate != null && location.equals(path)) { Long loadedSize = (Long) args[1]; Long totalSize = (Long) args[2]; float progress = Math.min(1f, loadedSize / (float) totalSize); delegate.onUploadProgressChanged(currentImageProgress = progress); } } else if (id == NotificationCenter.fileLoaded || id == NotificationCenter.fileLoadFailed || id == NotificationCenter.httpFileDidLoad || id == NotificationCenter.httpFileDidFailedLoad) { String path = (String) args[0]; currentImageProgress = 1f; if (path.equals(uploadingImage)) { NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.fileLoaded); NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.fileLoadFailed); NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.httpFileDidLoad); NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.httpFileDidFailedLoad); uploadingImage = null; if (id == NotificationCenter.fileLoaded || id == NotificationCenter.httpFileDidLoad) { Bitmap bitmap = ImageLoader.loadBitmap(finalPath, null, 800, 800, true); processBitmap(bitmap, null); } else { imageReceiver.setImageBitmap((Drawable) null); if (delegate != null) { delegate.didUploadFailed(); } } } } else if (id == NotificationCenter.filePreparingFailed) { MessageObject messageObject = (MessageObject) args[0]; if (messageObject != convertingVideo || parentFragment == null) { return; } parentFragment.getSendMessagesHelper().stopVideoService(messageObject.messageOwner.attachPath); NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.filePreparingStarted); NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.filePreparingFailed); NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.fileNewChunkAvailable); cleanup(); } else if (id == NotificationCenter.fileNewChunkAvailable) { MessageObject messageObject = (MessageObject) args[0]; if (messageObject != convertingVideo || parentFragment == null) { return; } String finalPath = (String) args[1]; long availableSize = (Long) args[2]; long finalSize = (Long) args[3]; parentFragment.getFileLoader().checkUploadNewDataAvailable(finalPath, false, availableSize, finalSize); if (finalSize != 0) { double lastFrameTimestamp = ((Long) args[5]) / 1000000.0; if (videoTimestamp > lastFrameTimestamp) { videoTimestamp = lastFrameTimestamp; } Bitmap bitmap = SendMessagesHelper.createVideoThumbnailAtTime(finalPath, (long) (videoTimestamp * 1000), null, true); if (bitmap != null) { File path = FileLoader.getInstance(currentAccount).getPathToAttach(smallPhoto, true); if (path != null) { path.delete(); } path = FileLoader.getInstance(currentAccount).getPathToAttach(bigPhoto, true); if (path != null) { path.delete(); } bigPhoto = ImageLoader.scaleAndSaveImage(bitmap, 800, 800, 80, false, 320, 320); smallPhoto = ImageLoader.scaleAndSaveImage(bitmap, 150, 150, 80, false, 150, 150); if (smallPhoto != null) { try { Bitmap b = BitmapFactory.decodeFile(FileLoader.getInstance(currentAccount).getPathToAttach(smallPhoto, true).getAbsolutePath()); String key = smallPhoto.location.volume_id + "_" + smallPhoto.location.local_id + "@50_50"; ImageLoader.getInstance().putImageToCache(new BitmapDrawable(b), key, true); } catch (Throwable ignore) { } } } NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.filePreparingStarted); NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.filePreparingFailed); NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.fileNewChunkAvailable); parentFragment.getSendMessagesHelper().stopVideoService(messageObject.messageOwner.attachPath); uploadingVideo = videoPath = finalPath; convertingVideo = null; } } else if (id == NotificationCenter.filePreparingStarted) { MessageObject messageObject = (MessageObject) args[0]; if (messageObject != convertingVideo || parentFragment == null) { return; } uploadingVideo = (String) args[1]; parentFragment.getFileLoader().uploadFile(uploadingVideo, false, false, (int) convertingVideo.videoEditedInfo.estimatedSize, ConnectionsManager.FileTypeVideo, false); } } public void setForceDarkTheme(boolean forceDarkTheme) { this.forceDarkTheme = forceDarkTheme; } public void setShowingFromDialog(boolean b) { showingFromDialog = b; } public void setUser(TLRPC.User user) { this.user = user; } public float getCurrentImageProgress() { return currentImageProgress; } public static class AvatarFor { public final TLObject object; public TLRPC.User fromObject; public final int type; public boolean self; public boolean isVideo; public AvatarFor(TLObject object, int type) { this.object = object; this.type = type; self = object instanceof TLRPC.User && ((TLRPC.User) object).self; } } }
dawitys/Telegram
TMessagesProj/src/main/java/org/telegram/ui/Components/ImageUpdater.java
41,695
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.messenger; import android.text.TextUtils; import android.util.SparseArray; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import org.telegram.ui.LaunchActivity; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.regex.Matcher; import java.util.regex.Pattern; public class FileLoader extends BaseController { private static final int PRIORITY_STREAM = 4; public static final int PRIORITY_HIGH = 3; public static final int PRIORITY_NORMAL_UP = 2; public static final int PRIORITY_NORMAL = 1; public static final int PRIORITY_LOW = 0; private int priorityIncreasePointer; private static Pattern sentPattern; public static FilePathDatabase.FileMeta getFileMetadataFromParent(int currentAccount, Object parentObject) { if (parentObject instanceof String) { String str = (String) parentObject; if (str.startsWith("sent_")) { if (sentPattern == null) { sentPattern = Pattern.compile("sent_.*_([0-9]+)_([0-9]+)_([0-9]+)_([0-9]+)"); } try { Matcher matcher = sentPattern.matcher(str); if (matcher.matches()) { FilePathDatabase.FileMeta fileMeta = new FilePathDatabase.FileMeta(); fileMeta.messageId = Integer.parseInt(matcher.group(1)); fileMeta.dialogId = Long.parseLong(matcher.group(2)); fileMeta.messageType = Integer.parseInt(matcher.group(3)); fileMeta.messageSize = Long.parseLong(matcher.group(4)); return fileMeta; } } catch (Exception e) { FileLog.e(e); } } } else if (parentObject instanceof MessageObject) { MessageObject messageObject = (MessageObject) parentObject; FilePathDatabase.FileMeta fileMeta = new FilePathDatabase.FileMeta(); fileMeta.messageId = messageObject.getId(); fileMeta.dialogId = messageObject.getDialogId(); fileMeta.messageType = messageObject.type; fileMeta.messageSize = messageObject.getSize(); return fileMeta; } return null; } public static TLRPC.VideoSize getVectorMarkupVideoSize(TLRPC.Photo photo) { if (photo == null || photo.video_sizes == null) { return null; } for (int i = 0; i < photo.video_sizes.size(); i++) { TLRPC.VideoSize videoSize = photo.video_sizes.get(i); if (videoSize instanceof TLRPC.TL_videoSizeEmojiMarkup || videoSize instanceof TLRPC.TL_videoSizeStickerMarkup) { return videoSize; } } return null; } public static TLRPC.VideoSize getEmojiMarkup(ArrayList<TLRPC.VideoSize> video_sizes) { for (int i = 0; i < video_sizes.size(); i++) { if (video_sizes.get(i) instanceof TLRPC.TL_videoSizeEmojiMarkup || video_sizes.get(i) instanceof TLRPC.TL_videoSizeStickerMarkup) { return video_sizes.get(i); } } return null; } private int getPriorityValue(int priorityType) { if (priorityType == PRIORITY_STREAM) { return Integer.MAX_VALUE; } else if (priorityType == PRIORITY_HIGH) { priorityIncreasePointer++; return (1 << 20) + priorityIncreasePointer; } else if (priorityType == PRIORITY_NORMAL_UP) { priorityIncreasePointer++; return (1 << 16) + priorityIncreasePointer; } else if (priorityType == PRIORITY_NORMAL) { return 1 << 16; } else { return 0; } } public DispatchQueue getFileLoaderQueue() { return fileLoaderQueue; } public interface FileLoaderDelegate { void fileUploadProgressChanged(FileUploadOperation operation, String location, long uploadedSize, long totalSize, boolean isEncrypted); void fileDidUploaded(String location, TLRPC.InputFile inputFile, TLRPC.InputEncryptedFile inputEncryptedFile, byte[] key, byte[] iv, long totalFileSize); void fileDidFailedUpload(String location, boolean isEncrypted); void fileDidLoaded(String location, File finalFile, Object parentObject, int type); void fileDidFailedLoad(String location, int state); void fileLoadProgressChanged(FileLoadOperation operation, String location, long uploadedSize, long totalSize); } public static final int MEDIA_DIR_IMAGE = 0; public static final int MEDIA_DIR_AUDIO = 1; public static final int MEDIA_DIR_VIDEO = 2; public static final int MEDIA_DIR_DOCUMENT = 3; public static final int MEDIA_DIR_CACHE = 4; public static final int MEDIA_DIR_FILES = 5; public static final int MEDIA_DIR_IMAGE_PUBLIC = 100; public static final int MEDIA_DIR_VIDEO_PUBLIC = 101; public static final int IMAGE_TYPE_LOTTIE = 1; public static final int IMAGE_TYPE_ANIMATION = 2; public static final int IMAGE_TYPE_SVG = 3; public static final int IMAGE_TYPE_SVG_WHITE = 4; public static final int IMAGE_TYPE_THEME_PREVIEW = 5; private final FileLoaderPriorityQueue largeFilesQueue = new FileLoaderPriorityQueue("large files queue", 2); private final FileLoaderPriorityQueue filesQueue = new FileLoaderPriorityQueue("files queue", 3); private final FileLoaderPriorityQueue imagesQueue = new FileLoaderPriorityQueue("imagesQueue queue", 6); private final FileLoaderPriorityQueue audioQueue = new FileLoaderPriorityQueue("audioQueue queue", 3); public final static long DEFAULT_MAX_FILE_SIZE = 1024L * 1024L * 2000L; public final static long DEFAULT_MAX_FILE_SIZE_PREMIUM = DEFAULT_MAX_FILE_SIZE * 2L; public final static int PRELOAD_CACHE_TYPE = 11; private volatile static DispatchQueue fileLoaderQueue = new DispatchQueue("fileUploadQueue"); private final FilePathDatabase filePathDatabase; private LinkedList<FileUploadOperation> uploadOperationQueue = new LinkedList<>(); private LinkedList<FileUploadOperation> uploadSmallOperationQueue = new LinkedList<>(); private ConcurrentHashMap<String, FileUploadOperation> uploadOperationPaths = new ConcurrentHashMap<>(); private ConcurrentHashMap<String, FileUploadOperation> uploadOperationPathsEnc = new ConcurrentHashMap<>(); private int currentUploadOperationsCount = 0; private int currentUploadSmallOperationsCount = 0; private ConcurrentHashMap<String, FileLoadOperation> loadOperationPaths = new ConcurrentHashMap<>(); private ConcurrentHashMap<String, LoadOperationUIObject> loadOperationPathsUI = new ConcurrentHashMap<>(10, 1, 2); private HashMap<String, Long> uploadSizes = new HashMap<>(); private HashMap<String, Boolean> loadingVideos = new HashMap<>(); private String forceLoadingFile; private static SparseArray<File> mediaDirs = null; private FileLoaderDelegate delegate = null; private int lastReferenceId; private ConcurrentHashMap<Integer, Object> parentObjectReferences = new ConcurrentHashMap<>(); private static final FileLoader[] Instance = new FileLoader[UserConfig.MAX_ACCOUNT_COUNT]; public static FileLoader getInstance(int num) { FileLoader localInstance = Instance[num]; if (localInstance == null) { synchronized (FileLoader.class) { localInstance = Instance[num]; if (localInstance == null) { Instance[num] = localInstance = new FileLoader(num); } } } return localInstance; } public FileLoader(int instance) { super(instance); filePathDatabase = new FilePathDatabase(instance); } public static void setMediaDirs(SparseArray<File> dirs) { mediaDirs = dirs; } public static File checkDirectory(int type) { return mediaDirs.get(type); } public static File getDirectory(int type) { File dir = mediaDirs.get(type); if (dir == null && type != FileLoader.MEDIA_DIR_CACHE) { dir = mediaDirs.get(FileLoader.MEDIA_DIR_CACHE); } try { if (dir != null && !dir.isDirectory()) { dir.mkdirs(); } } catch (Exception e) { //don't promt } return dir; } public int getFileReference(Object parentObject) { int reference = lastReferenceId++; parentObjectReferences.put(reference, parentObject); return reference; } public Object getParentObject(int reference) { return parentObjectReferences.get(reference); } public void setLoadingVideoInternal(TLRPC.Document document, boolean player) { String key = getAttachFileName(document); String dKey = key + (player ? "p" : ""); loadingVideos.put(dKey, true); getNotificationCenter().postNotificationName(NotificationCenter.videoLoadingStateChanged, key); } public void setLoadingVideo(TLRPC.Document document, boolean player, boolean schedule) { if (document == null) { return; } if (schedule) { AndroidUtilities.runOnUIThread(() -> setLoadingVideoInternal(document, player)); } else { setLoadingVideoInternal(document, player); } } public void setLoadingVideoForPlayer(TLRPC.Document document, boolean player) { if (document == null) { return; } String key = getAttachFileName(document); if (loadingVideos.containsKey(key + (player ? "" : "p"))) { loadingVideos.put(key + (player ? "p" : ""), true); } } private void removeLoadingVideoInternal(TLRPC.Document document, boolean player) { String key = getAttachFileName(document); String dKey = key + (player ? "p" : ""); if (loadingVideos.remove(dKey) != null) { getNotificationCenter().postNotificationName(NotificationCenter.videoLoadingStateChanged, key); } } public void removeLoadingVideo(TLRPC.Document document, boolean player, boolean schedule) { if (document == null) { return; } if (schedule) { AndroidUtilities.runOnUIThread(() -> removeLoadingVideoInternal(document, player)); } else { removeLoadingVideoInternal(document, player); } } public boolean isLoadingVideo(TLRPC.Document document, boolean player) { return document != null && loadingVideos.containsKey(getAttachFileName(document) + (player ? "p" : "")); } public boolean isLoadingVideoAny(TLRPC.Document document) { return isLoadingVideo(document, false) || isLoadingVideo(document, true); } public void cancelFileUpload(final String location, final boolean enc) { fileLoaderQueue.postRunnable(() -> { FileUploadOperation operation; if (!enc) { operation = uploadOperationPaths.get(location); } else { operation = uploadOperationPathsEnc.get(location); } uploadSizes.remove(location); if (operation != null) { uploadOperationPathsEnc.remove(location); uploadOperationQueue.remove(operation); uploadSmallOperationQueue.remove(operation); operation.cancel(); } }); } public void checkUploadNewDataAvailable(final String location, final boolean encrypted, final long newAvailableSize, final long finalSize) { fileLoaderQueue.postRunnable(() -> { FileUploadOperation operation; if (encrypted) { operation = uploadOperationPathsEnc.get(location); } else { operation = uploadOperationPaths.get(location); } if (operation != null) { operation.checkNewDataAvailable(newAvailableSize, finalSize); } else if (finalSize != 0) { uploadSizes.put(location, finalSize); } }); } public void onNetworkChanged(final boolean slow) { fileLoaderQueue.postRunnable(() -> { for (ConcurrentHashMap.Entry<String, FileUploadOperation> entry : uploadOperationPaths.entrySet()) { entry.getValue().onNetworkChanged(slow); } for (ConcurrentHashMap.Entry<String, FileUploadOperation> entry : uploadOperationPathsEnc.entrySet()) { entry.getValue().onNetworkChanged(slow); } }); } public void uploadFile(final String location, final boolean encrypted, final boolean small, final int type) { uploadFile(location, encrypted, small, 0, type, false); } public void uploadFile(final String location, final boolean encrypted, final boolean small, final long estimatedSize, final int type, boolean forceSmallFile) { if (location == null) { return; } fileLoaderQueue.postRunnable(() -> { if (encrypted) { if (uploadOperationPathsEnc.containsKey(location)) { return; } } else { if (uploadOperationPaths.containsKey(location)) { return; } } long esimated = estimatedSize; if (esimated != 0) { Long finalSize = uploadSizes.get(location); if (finalSize != null) { esimated = 0; uploadSizes.remove(location); } } FileUploadOperation operation = new FileUploadOperation(currentAccount, location, encrypted, esimated, type); if (delegate != null && estimatedSize != 0) { delegate.fileUploadProgressChanged(operation, location, 0, estimatedSize, encrypted); } if (encrypted) { uploadOperationPathsEnc.put(location, operation); } else { uploadOperationPaths.put(location, operation); } if (forceSmallFile) { operation.setForceSmallFile(); } operation.setDelegate(new FileUploadOperation.FileUploadOperationDelegate() { @Override public void didFinishUploadingFile(final FileUploadOperation operation, final TLRPC.InputFile inputFile, final TLRPC.InputEncryptedFile inputEncryptedFile, final byte[] key, final byte[] iv) { fileLoaderQueue.postRunnable(() -> { if (encrypted) { uploadOperationPathsEnc.remove(location); } else { uploadOperationPaths.remove(location); } if (small) { currentUploadSmallOperationsCount--; if (currentUploadSmallOperationsCount < 1) { FileUploadOperation operation12 = uploadSmallOperationQueue.poll(); if (operation12 != null) { currentUploadSmallOperationsCount++; operation12.start(); } } } else { currentUploadOperationsCount--; if (currentUploadOperationsCount < 1) { FileUploadOperation operation12 = uploadOperationQueue.poll(); if (operation12 != null) { currentUploadOperationsCount++; operation12.start(); } } } if (delegate != null) { delegate.fileDidUploaded(location, inputFile, inputEncryptedFile, key, iv, operation.getTotalFileSize()); } }); } @Override public void didFailedUploadingFile(final FileUploadOperation operation) { fileLoaderQueue.postRunnable(() -> { if (encrypted) { uploadOperationPathsEnc.remove(location); } else { uploadOperationPaths.remove(location); } if (delegate != null) { delegate.fileDidFailedUpload(location, encrypted); } if (small) { currentUploadSmallOperationsCount--; if (currentUploadSmallOperationsCount < 1) { FileUploadOperation operation1 = uploadSmallOperationQueue.poll(); if (operation1 != null) { currentUploadSmallOperationsCount++; operation1.start(); } } } else { currentUploadOperationsCount--; if (currentUploadOperationsCount < 1) { FileUploadOperation operation1 = uploadOperationQueue.poll(); if (operation1 != null) { currentUploadOperationsCount++; operation1.start(); } } } }); } @Override public void didChangedUploadProgress(FileUploadOperation operation, long uploadedSize, long totalSize) { if (delegate != null) { delegate.fileUploadProgressChanged(operation, location, uploadedSize, totalSize, encrypted); } } }); if (small) { if (currentUploadSmallOperationsCount < 1) { currentUploadSmallOperationsCount++; operation.start(); } else { uploadSmallOperationQueue.add(operation); } } else { if (currentUploadOperationsCount < 1) { currentUploadOperationsCount++; operation.start(); } else { uploadOperationQueue.add(operation); } } }); } public void setForceStreamLoadingFile(TLRPC.FileLocation location, String ext) { if (location == null) { return; } fileLoaderQueue.postRunnable(() -> { forceLoadingFile = getAttachFileName(location, ext); FileLoadOperation operation = loadOperationPaths.get(forceLoadingFile); if (operation != null) { if (operation.isPreloadVideoOperation()) { operation.setIsPreloadVideoOperation(false); } operation.setForceRequest(true); operation.setPriority(getPriorityValue(PRIORITY_STREAM)); operation.getQueue().add(operation); operation.getQueue().checkLoadingOperations(); } }); } public void cancelLoadFile(TLRPC.Document document) { cancelLoadFile(document, false); } public void cancelLoadFile(TLRPC.Document document, boolean deleteFile) { cancelLoadFile(document, null, null, null, null, null, deleteFile); } public void cancelLoadFile(SecureDocument document) { cancelLoadFile(null, document, null, null, null, null, false); } public void cancelLoadFile(WebFile document) { cancelLoadFile(null, null, document, null, null, null, false); } public void cancelLoadFile(TLRPC.PhotoSize photo) { cancelLoadFile(photo, false); } public void cancelLoadFile(TLRPC.PhotoSize photo, boolean deleteFile) { cancelLoadFile(null, null, null, photo.location, null, null, deleteFile); } public void cancelLoadFile(TLRPC.FileLocation location, String ext) { cancelLoadFile(location, ext, false); } public void cancelLoadFile(TLRPC.FileLocation location, String ext, boolean deleteFile) { cancelLoadFile(null, null, null, location, ext, null, deleteFile); } public void cancelLoadFile(String fileName) { cancelLoadFile(null, null, null, null, null, fileName, true); } public void cancelLoadFiles(ArrayList<String> fileNames) { for (int a = 0, N = fileNames.size(); a < N; a++) { cancelLoadFile(null, null, null, null, null, fileNames.get(a), true); } } private void cancelLoadFile(final TLRPC.Document document, final SecureDocument secureDocument, final WebFile webDocument, final TLRPC.FileLocation location, final String locationExt, String name, boolean deleteFile) { if (location == null && document == null && webDocument == null && secureDocument == null && TextUtils.isEmpty(name)) { return; } final String fileName; if (location != null) { fileName = getAttachFileName(location, locationExt); } else if (document != null) { fileName = getAttachFileName(document); } else if (secureDocument != null) { fileName = getAttachFileName(secureDocument); } else if (webDocument != null) { fileName = getAttachFileName(webDocument); } else { fileName = name; } LoadOperationUIObject uiObject = loadOperationPathsUI.remove(fileName); Runnable runnable = uiObject != null ? uiObject.loadInternalRunnable : null; boolean removed = uiObject != null; if (runnable != null) { fileLoaderQueue.cancelRunnable(runnable); } fileLoaderQueue.postRunnable(() -> { FileLoadOperation operation = loadOperationPaths.remove(fileName); if (operation != null) { FileLoaderPriorityQueue queue = operation.getQueue(); queue.cancel(operation); } }); if (removed && document != null) { AndroidUtilities.runOnUIThread(() -> { getNotificationCenter().postNotificationName(NotificationCenter.onDownloadingFilesChanged); }); } } public void cancelLoadAllFiles() { for (String fileName : loadOperationPathsUI.keySet()) { LoadOperationUIObject uiObject = loadOperationPathsUI.get(fileName); Runnable runnable = uiObject != null ? uiObject.loadInternalRunnable : null; boolean removed = uiObject != null; if (runnable != null) { fileLoaderQueue.cancelRunnable(runnable); } fileLoaderQueue.postRunnable(() -> { FileLoadOperation operation = loadOperationPaths.remove(fileName); if (operation != null) { FileLoaderPriorityQueue queue = operation.getQueue(); queue.cancel(operation); } }); // if (removed && document != null) { // AndroidUtilities.runOnUIThread(() -> { // getNotificationCenter().postNotificationName(NotificationCenter.onDownloadingFilesChanged); // }); // } } } public boolean isLoadingFile(final String fileName) { return fileName != null && loadOperationPathsUI.containsKey(fileName); } public float getBufferedProgressFromPosition(final float position, final String fileName) { if (TextUtils.isEmpty(fileName)) { return 0; } FileLoadOperation loadOperation = loadOperationPaths.get(fileName); if (loadOperation != null) { return loadOperation.getDownloadedLengthFromOffset(position); } else { return 0.0f; } } public void loadFile(ImageLocation imageLocation, Object parentObject, String ext, int priority, int cacheType) { if (imageLocation == null) { return; } if (cacheType == 0 && (imageLocation.isEncrypted() || imageLocation.photoSize != null && imageLocation.getSize() == 0)) { cacheType = 1; } loadFile(imageLocation.document, imageLocation.secureDocument, imageLocation.webFile, imageLocation.location, imageLocation, parentObject, ext, imageLocation.getSize(), priority, cacheType); } public void loadFile(SecureDocument secureDocument, int priority) { if (secureDocument == null) { return; } loadFile(null, secureDocument, null, null, null, null, null, 0, priority, 1); } public void loadFile(TLRPC.Document document, Object parentObject, int priority, int cacheType) { if (document == null) { return; } if (cacheType == 0 && document.key != null) { cacheType = 1; } loadFile(document, null, null, null, null, parentObject, null, 0, priority, cacheType); } public void loadFile(WebFile document, int priority, int cacheType) { loadFile(null, null, document, null, null, null, null, 0, priority, cacheType); } private FileLoadOperation loadFileInternal(final TLRPC.Document document, final SecureDocument secureDocument, final WebFile webDocument, TLRPC.TL_fileLocationToBeDeprecated location, final ImageLocation imageLocation, Object parentObject, final String locationExt, final long locationSize, int priority, final FileLoadOperationStream stream, final long streamOffset, boolean streamPriority, final int cacheType) { String fileName; if (location != null) { fileName = getAttachFileName(location, locationExt); } else if (secureDocument != null) { fileName = getAttachFileName(secureDocument); } else if (document != null) { fileName = getAttachFileName(document); } else if (webDocument != null) { fileName = getAttachFileName(webDocument); } else { fileName = null; } if (fileName == null || fileName.contains("" + Integer.MIN_VALUE)) { return null; } if (cacheType != 10 && !TextUtils.isEmpty(fileName) && !fileName.contains("" + Integer.MIN_VALUE)) { loadOperationPathsUI.put(fileName, new LoadOperationUIObject()); } if (document != null && parentObject instanceof MessageObject && ((MessageObject) parentObject).putInDownloadsStore && !((MessageObject) parentObject).isAnyKindOfSticker()) { getDownloadController().startDownloadFile(document, (MessageObject) parentObject); } FileLoadOperation operation = loadOperationPaths.get(fileName); if (BuildVars.LOGS_ENABLED) { FileLog.d("checkFile operation fileName=" + fileName + " documentName=" + getDocumentFileName(document) + " operation=" + operation + " priority=" + priority); } priority = getPriorityValue(priority); if (operation != null) { if (cacheType != 10 && operation.isPreloadVideoOperation()) { operation.setIsPreloadVideoOperation(false); } operation.setForceRequest(priority > 0); operation.setPriority(priority); operation.setStream(stream, streamPriority, streamOffset); operation.getQueue().add(operation); operation.updateProgress(); operation.getQueue().checkLoadingOperations(); return operation; } File tempDir = getDirectory(MEDIA_DIR_CACHE); File storeDir = tempDir; int type = MEDIA_DIR_CACHE; long documentId = 0; int dcId = 0; if (secureDocument != null) { operation = new FileLoadOperation(secureDocument); type = MEDIA_DIR_DOCUMENT; } else if (location != null) { documentId = location.volume_id; dcId = location.dc_id; operation = new FileLoadOperation(imageLocation, parentObject, locationExt, locationSize); type = MEDIA_DIR_IMAGE; } else if (document != null) { operation = new FileLoadOperation(document, parentObject); if (MessageObject.isVoiceDocument(document)) { type = MEDIA_DIR_AUDIO; } else if (MessageObject.isVideoDocument(document)) { type = MEDIA_DIR_VIDEO; documentId = document.id; dcId = document.dc_id; } else { type = MEDIA_DIR_DOCUMENT; documentId = document.id; dcId = document.dc_id; } if (MessageObject.isRoundVideoDocument(document)) { documentId = 0; dcId = 0; } } else if (webDocument != null) { operation = new FileLoadOperation(currentAccount, webDocument); if (webDocument.location != null) { type = MEDIA_DIR_CACHE; } else if (MessageObject.isVoiceWebDocument(webDocument)) { type = MEDIA_DIR_AUDIO; } else if (MessageObject.isVideoWebDocument(webDocument)) { type = MEDIA_DIR_VIDEO; } else if (MessageObject.isImageWebDocument(webDocument)) { type = MEDIA_DIR_IMAGE; } else { type = MEDIA_DIR_DOCUMENT; } } FileLoaderPriorityQueue loaderQueue; if (type == MEDIA_DIR_AUDIO) { loaderQueue = audioQueue; } else if (secureDocument != null || location != null && (imageLocation == null || imageLocation.imageType != IMAGE_TYPE_ANIMATION) || MessageObject.isImageWebDocument(webDocument) || MessageObject.isStickerDocument(document) || MessageObject.isAnimatedStickerDocument(document, true) || MessageObject.isVideoStickerDocument(document)) { loaderQueue = imagesQueue; } else { if (document == null || document.size > 20 * 1024 * 1024) { loaderQueue = largeFilesQueue; } else { loaderQueue = filesQueue; } } String storeFileName = fileName; if (cacheType == 0 || cacheType == 10) { if (documentId != 0) { String path = getFileDatabase().getPath(documentId, dcId, type, true); boolean customPath = false; if (path != null) { File file = new File(path); if (file.exists()) { customPath = true; storeFileName = file.getName(); storeDir = file.getParentFile(); } } if (!customPath) { storeFileName = fileName; storeDir = getDirectory(type); boolean saveCustomPath = false; if ((type == MEDIA_DIR_IMAGE || type == MEDIA_DIR_VIDEO) && canSaveToPublicStorage(parentObject)) { File newDir; if (type == MEDIA_DIR_IMAGE) { newDir = getDirectory(MEDIA_DIR_IMAGE_PUBLIC); } else { newDir = getDirectory(MEDIA_DIR_VIDEO_PUBLIC); } if (newDir != null) { storeDir = newDir; saveCustomPath = true; } } else if (!TextUtils.isEmpty(getDocumentFileName(document)) && canSaveAsFile(parentObject)) { storeFileName = getDocumentFileName(document); File newDir = getDirectory(MEDIA_DIR_FILES); if (newDir != null) { storeDir = newDir; saveCustomPath = true; } } if (saveCustomPath) { operation.pathSaveData = new FilePathDatabase.PathData(documentId, dcId, type); } } } else { storeDir = getDirectory(type); } } else if (cacheType == 2) { operation.setEncryptFile(true); } operation.setPaths(currentAccount, fileName, loaderQueue, storeDir, tempDir, storeFileName); if (cacheType == 10) { operation.setIsPreloadVideoOperation(true); } final int finalType = type; FileLoadOperation.FileLoadOperationDelegate fileLoadOperationDelegate = new FileLoadOperation.FileLoadOperationDelegate() { @Override public void didFinishLoadingFile(FileLoadOperation operation, File finalFile) { if (!operation.isPreloadVideoOperation() && operation.isPreloadFinished()) { return; } FilePathDatabase.FileMeta fileMeta = getFileMetadataFromParent(currentAccount, parentObject); if (fileMeta != null) { getFileLoader().getFileDatabase().saveFileDialogId(finalFile, fileMeta); } if (parentObject instanceof MessageObject) { MessageObject messageObject = (MessageObject) parentObject; if (document != null && messageObject.putInDownloadsStore) { getDownloadController().onDownloadComplete(messageObject); } } if (!operation.isPreloadVideoOperation()) { loadOperationPathsUI.remove(fileName); if (delegate != null) { delegate.fileDidLoaded(fileName, finalFile, parentObject, finalType); } } checkDownloadQueue(operation.getQueue(), fileName); } @Override public void didFailedLoadingFile(FileLoadOperation operation, int reason) { loadOperationPathsUI.remove(fileName); checkDownloadQueue(operation.getQueue(), fileName); if (delegate != null) { delegate.fileDidFailedLoad(fileName, reason); } if (document != null && parentObject instanceof MessageObject && reason == 0) { getDownloadController().onDownloadFail((MessageObject) parentObject, reason); } else if (reason == -1) { LaunchActivity.checkFreeDiscSpaceStatic(2); } } @Override public void didChangedLoadProgress(FileLoadOperation operation, long uploadedSize, long totalSize) { if (delegate != null) { delegate.fileLoadProgressChanged(operation, fileName, uploadedSize, totalSize); } } @Override public void saveFilePath(FilePathDatabase.PathData pathSaveData, File cacheFileFinal) { getFileDatabase().putPath(pathSaveData.id, pathSaveData.dc, pathSaveData.type, cacheFileFinal != null ? cacheFileFinal.toString() : null); } @Override public boolean hasAnotherRefOnFile(String path) { return getFileDatabase().hasAnotherRefOnFile(path); } }; operation.setDelegate(fileLoadOperationDelegate); loadOperationPaths.put(fileName, operation); operation.setPriority(priority); operation.setStream(stream, streamPriority, streamOffset); if (BuildVars.LOGS_ENABLED) { FileLog.d("loadFileInternal fileName=" + fileName + " documentName=" + getDocumentFileName(document)); } loaderQueue.add(operation); loaderQueue.checkLoadingOperations(); return operation; } private boolean canSaveAsFile(Object parentObject) { if (parentObject instanceof MessageObject) { MessageObject messageObject = (MessageObject) parentObject; if (!messageObject.isDocument()) { return false; } return true; } return false; } private boolean canSaveToPublicStorage(Object parentObject) { if (BuildVars.NO_SCOPED_STORAGE) { return false; } FilePathDatabase.FileMeta metadata = getFileMetadataFromParent(currentAccount, parentObject); MessageObject messageObject = null; if (metadata != null) { int flag; long dialogId = metadata.dialogId; if (getMessagesController().isChatNoForwards(getMessagesController().getChat(-dialogId)) || DialogObject.isEncryptedDialog(dialogId)) { return false; } if (parentObject instanceof MessageObject) { messageObject = (MessageObject) parentObject; if (messageObject.isRoundVideo() || messageObject.isVoice() || messageObject.isAnyKindOfSticker() || messageObject.messageOwner.noforwards) { return false; } } else { if (metadata.messageType == MessageObject.TYPE_ROUND_VIDEO || metadata.messageType == MessageObject.TYPE_STICKER || metadata.messageType == MessageObject.TYPE_VOICE) { return false; } } if (dialogId >= 0) { flag = SharedConfig.SAVE_TO_GALLERY_FLAG_PEER; } else { if (ChatObject.isChannelAndNotMegaGroup(getMessagesController().getChat(-dialogId))) { flag = SharedConfig.SAVE_TO_GALLERY_FLAG_CHANNELS; } else { flag = SharedConfig.SAVE_TO_GALLERY_FLAG_GROUP; } } if (SaveToGallerySettingsHelper.needSave(flag, metadata, messageObject, currentAccount)) { return true; } } return false; } private void addOperationToQueue(FileLoadOperation operation, LinkedList<FileLoadOperation> queue) { int priority = operation.getPriority(); if (priority > 0) { int index = queue.size(); for (int a = 0, size = queue.size(); a < size; a++) { FileLoadOperation queuedOperation = queue.get(a); if (queuedOperation.getPriority() < priority) { index = a; break; } } queue.add(index, operation); } else { queue.add(operation); } } private void loadFile(final TLRPC.Document document, final SecureDocument secureDocument, final WebFile webDocument, TLRPC.TL_fileLocationToBeDeprecated location, final ImageLocation imageLocation, final Object parentObject, final String locationExt, final long locationSize, final int priority, final int cacheType) { String fileName; if (location != null) { fileName = getAttachFileName(location, locationExt); } else if (document != null) { fileName = getAttachFileName(document); } else if (webDocument != null) { fileName = getAttachFileName(webDocument); } else { fileName = null; } Runnable runnable = () -> loadFileInternal(document, secureDocument, webDocument, location, imageLocation, parentObject, locationExt, locationSize, priority, null, 0, false, cacheType); if (cacheType != 10 && !TextUtils.isEmpty(fileName) && !fileName.contains("" + Integer.MIN_VALUE)) { LoadOperationUIObject uiObject = new FileLoader.LoadOperationUIObject(); uiObject.loadInternalRunnable = runnable; loadOperationPathsUI.put(fileName, uiObject); } fileLoaderQueue.postRunnable(runnable); } protected FileLoadOperation loadStreamFile(final FileLoadOperationStream stream, final TLRPC.Document document, final ImageLocation location, final Object parentObject, final long offset, final boolean priority, int loadingPriority) { final CountDownLatch semaphore = new CountDownLatch(1); final FileLoadOperation[] result = new FileLoadOperation[1]; fileLoaderQueue.postRunnable(() -> { result[0] = loadFileInternal(document, null, null, document == null && location != null ? location.location : null, location, parentObject, document == null && location != null ? "mp4" : null, document == null && location != null ? location.currentSize : 0, loadingPriority, stream, offset, priority, document == null ? 1 : 0); semaphore.countDown(); }); try { semaphore.await(); } catch (Exception e) { FileLog.e(e, false); } return result[0]; } private void checkDownloadQueue(FileLoaderPriorityQueue queue, String fileName) { fileLoaderQueue.postRunnable(() -> { FileLoadOperation operation = loadOperationPaths.remove(fileName); queue.remove(operation); queue.checkLoadingOperations(); }); } public void setDelegate(FileLoaderDelegate fileLoaderDelegate) { delegate = fileLoaderDelegate; } public static String getMessageFileName(TLRPC.Message message) { if (message == null) { return ""; } if (message instanceof TLRPC.TL_messageService) { if (message.action.photo != null) { ArrayList<TLRPC.PhotoSize> sizes = message.action.photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize()); if (sizeFull != null) { return getAttachFileName(sizeFull); } } } } else { if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaDocument) { return getAttachFileName(MessageObject.getMedia(message).document); } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaPhoto) { ArrayList<TLRPC.PhotoSize> sizes = MessageObject.getMedia(message).photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize(), false, null, true); if (sizeFull != null) { return getAttachFileName(sizeFull); } } } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaWebPage) { if (MessageObject.getMedia(message).webpage.document != null) { return getAttachFileName(MessageObject.getMedia(message).webpage.document); } else if (MessageObject.getMedia(message).webpage.photo != null) { ArrayList<TLRPC.PhotoSize> sizes = MessageObject.getMedia(message).webpage.photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize()); if (sizeFull != null) { return getAttachFileName(sizeFull); } } } } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaInvoice) { TLRPC.WebDocument document = ((TLRPC.TL_messageMediaInvoice) MessageObject.getMedia(message)).webPhoto; if (document != null) { return Utilities.MD5(document.url) + "." + ImageLoader.getHttpUrlExtension(document.url, getMimeTypePart(document.mime_type)); } } } return ""; } public File getPathToMessage(TLRPC.Message message) { return getPathToMessage(message, true); } public File getPathToMessage(TLRPC.Message message, boolean useFileDatabaseQueue) { if (message == null) { return new File(""); } if (message instanceof TLRPC.TL_messageService) { if (message.action.photo != null) { ArrayList<TLRPC.PhotoSize> sizes = message.action.photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize()); if (sizeFull != null) { return getPathToAttach(sizeFull, null, false, useFileDatabaseQueue); } } } } else { if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaDocument) { return getPathToAttach(MessageObject.getMedia(message).document, null, MessageObject.getMedia(message).ttl_seconds != 0, useFileDatabaseQueue); } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaPhoto) { ArrayList<TLRPC.PhotoSize> sizes = MessageObject.getMedia(message).photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize(), false, null, true); if (sizeFull != null) { return getPathToAttach(sizeFull, null, MessageObject.getMedia(message).ttl_seconds != 0, useFileDatabaseQueue); } } } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaWebPage) { if (MessageObject.getMedia(message).webpage.document != null) { return getPathToAttach(MessageObject.getMedia(message).webpage.document, null, false, useFileDatabaseQueue); } else if (MessageObject.getMedia(message).webpage.photo != null) { ArrayList<TLRPC.PhotoSize> sizes = MessageObject.getMedia(message).webpage.photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize()); if (sizeFull != null) { return getPathToAttach(sizeFull, null, false, useFileDatabaseQueue); } } } } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaInvoice) { return getPathToAttach(((TLRPC.TL_messageMediaInvoice) MessageObject.getMedia(message)).photo, null, true, useFileDatabaseQueue); } } return new File(""); } public File getPathToAttach(TLObject attach) { return getPathToAttach(attach, null, false); } public File getPathToAttach(TLObject attach, boolean forceCache) { return getPathToAttach(attach, null, forceCache); } public File getPathToAttach(TLObject attach, String ext, boolean forceCache) { return getPathToAttach(attach, null, ext, forceCache, true); } public File getPathToAttach(TLObject attach, String ext, boolean forceCache, boolean useFileDatabaseQueue) { return getPathToAttach(attach, null, ext, forceCache, useFileDatabaseQueue); } /** * Return real file name. Used before file.exist() */ public File getPathToAttach(TLObject attach, String size, String ext, boolean forceCache, boolean useFileDatabaseQueue) { File dir = null; long documentId = 0; int dcId = 0; int type = 0; if (forceCache) { dir = getDirectory(MEDIA_DIR_CACHE); } else { if (attach instanceof TLRPC.Document) { TLRPC.Document document = (TLRPC.Document) attach; if (!TextUtils.isEmpty(document.localPath)) { return new File(document.localPath); } if (document.key != null) { type = MEDIA_DIR_CACHE; } else { if (MessageObject.isVoiceDocument(document)) { type = MEDIA_DIR_AUDIO; } else if (MessageObject.isVideoDocument(document)) { type = MEDIA_DIR_VIDEO; } else { type = MEDIA_DIR_DOCUMENT; } } documentId = document.id; dcId = document.dc_id; dir = getDirectory(type); } else if (attach instanceof TLRPC.Photo) { TLRPC.PhotoSize photoSize = getClosestPhotoSizeWithSize(((TLRPC.Photo) attach).sizes, AndroidUtilities.getPhotoSize()); return getPathToAttach(photoSize, ext, false, useFileDatabaseQueue); } else if (attach instanceof TLRPC.PhotoSize) { TLRPC.PhotoSize photoSize = (TLRPC.PhotoSize) attach; if (photoSize instanceof TLRPC.TL_photoStrippedSize || photoSize instanceof TLRPC.TL_photoPathSize) { dir = null; } else if (photoSize.location == null || photoSize.location.key != null || photoSize.location.volume_id == Integer.MIN_VALUE && photoSize.location.local_id < 0 || photoSize.size < 0) { dir = getDirectory(type = MEDIA_DIR_CACHE); } else { dir = getDirectory(type = MEDIA_DIR_IMAGE); } documentId = photoSize.location.volume_id; dcId = photoSize.location.dc_id; } else if (attach instanceof TLRPC.TL_videoSize) { TLRPC.TL_videoSize videoSize = (TLRPC.TL_videoSize) attach; if (videoSize.location == null || videoSize.location.key != null || videoSize.location.volume_id == Integer.MIN_VALUE && videoSize.location.local_id < 0 || videoSize.size < 0) { dir = getDirectory(type = MEDIA_DIR_CACHE); } else { dir = getDirectory(type = MEDIA_DIR_IMAGE); } documentId = videoSize.location.volume_id; dcId = videoSize.location.dc_id; } else if (attach instanceof TLRPC.FileLocation) { TLRPC.FileLocation fileLocation = (TLRPC.FileLocation) attach; if (fileLocation.key != null || fileLocation.volume_id == Integer.MIN_VALUE && fileLocation.local_id < 0) { dir = getDirectory(MEDIA_DIR_CACHE); } else { documentId = fileLocation.volume_id; dcId = fileLocation.dc_id; dir = getDirectory(type = MEDIA_DIR_IMAGE); } } else if (attach instanceof TLRPC.UserProfilePhoto || attach instanceof TLRPC.ChatPhoto) { if (size == null) { size = "s"; } if ("s".equals(size)) { dir = getDirectory(MEDIA_DIR_CACHE); } else { dir = getDirectory(MEDIA_DIR_IMAGE); } } else if (attach instanceof WebFile) { WebFile document = (WebFile) attach; if (document.mime_type.startsWith("image/")) { dir = getDirectory(MEDIA_DIR_IMAGE); } else if (document.mime_type.startsWith("audio/")) { dir = getDirectory(MEDIA_DIR_AUDIO); } else if (document.mime_type.startsWith("video/")) { dir = getDirectory(MEDIA_DIR_VIDEO); } else { dir = getDirectory(MEDIA_DIR_DOCUMENT); } } else if (attach instanceof TLRPC.TL_secureFile || attach instanceof SecureDocument) { dir = getDirectory(MEDIA_DIR_CACHE); } } if (dir == null) { return new File(""); } if (documentId != 0) { String path = getInstance(UserConfig.selectedAccount).getFileDatabase().getPath(documentId, dcId, type, useFileDatabaseQueue); if (path != null) { return new File(path); } } return new File(dir, getAttachFileName(attach, ext)); } public FilePathDatabase getFileDatabase() { return filePathDatabase; } public static TLRPC.PhotoSize getClosestPhotoSizeWithSize(ArrayList<TLRPC.PhotoSize> sizes, int side) { return getClosestPhotoSizeWithSize(sizes, side, false); } public static TLRPC.PhotoSize getClosestPhotoSizeWithSize(ArrayList<TLRPC.PhotoSize> sizes, int side, boolean byMinSide) { return getClosestPhotoSizeWithSize(sizes, side, byMinSide, null, false); } public static TLRPC.PhotoSize getClosestPhotoSizeWithSize(ArrayList<TLRPC.PhotoSize> sizes, int side, boolean byMinSide, TLRPC.PhotoSize toIgnore, boolean ignoreStripped) { if (sizes == null || sizes.isEmpty()) { return null; } int lastSide = 0; TLRPC.PhotoSize closestObject = null; for (int a = 0; a < sizes.size(); a++) { TLRPC.PhotoSize obj = sizes.get(a); if (obj == null || obj == toIgnore || obj instanceof TLRPC.TL_photoSizeEmpty || obj instanceof TLRPC.TL_photoPathSize || ignoreStripped && obj instanceof TLRPC.TL_photoStrippedSize) { continue; } if (byMinSide) { int currentSide = Math.min(obj.h, obj.w); if ( closestObject == null || side > 100 && closestObject.location != null && closestObject.location.dc_id == Integer.MIN_VALUE || obj instanceof TLRPC.TL_photoCachedSize || side > lastSide && lastSide < currentSide ) { closestObject = obj; lastSide = currentSide; } } else { int currentSide = Math.max(obj.w, obj.h); 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; } } } return closestObject; } public static TLRPC.VideoSize getClosestVideoSizeWithSize(ArrayList<TLRPC.VideoSize> sizes, int side) { return getClosestVideoSizeWithSize(sizes, side, false); } public static TLRPC.VideoSize getClosestVideoSizeWithSize(ArrayList<TLRPC.VideoSize> sizes, int side, boolean byMinSide) { return getClosestVideoSizeWithSize(sizes, side, byMinSide, false); } public static TLRPC.VideoSize getClosestVideoSizeWithSize(ArrayList<TLRPC.VideoSize> sizes, int side, boolean byMinSide, boolean ignoreStripped) { if (sizes == null || sizes.isEmpty()) { return null; } int lastSide = 0; TLRPC.VideoSize closestObject = null; for (int a = 0; a < sizes.size(); a++) { TLRPC.VideoSize obj = sizes.get(a); if (obj == null || obj instanceof TLRPC.TL_videoSizeEmojiMarkup || obj instanceof TLRPC.TL_videoSizeStickerMarkup) { continue; } if (byMinSide) { int currentSide = Math.min(obj.h, obj.w); if (closestObject == null || side > 100 && closestObject.location != null && closestObject.location.dc_id == Integer.MIN_VALUE || side > lastSide && lastSide < currentSide) { closestObject = obj; lastSide = currentSide; } } else { int currentSide = Math.max(obj.w, obj.h); if ( closestObject == null || side > 100 && closestObject.location != null && closestObject.location.dc_id == Integer.MIN_VALUE || currentSide <= side && lastSide < currentSide ) { closestObject = obj; lastSide = currentSide; } } } return closestObject; } public static TLRPC.TL_photoPathSize getPathPhotoSize(ArrayList<TLRPC.PhotoSize> sizes) { if (sizes == null || sizes.isEmpty()) { return null; } for (int a = 0; a < sizes.size(); a++) { TLRPC.PhotoSize obj = sizes.get(a); if (obj instanceof TLRPC.TL_photoPathSize) { continue; } return (TLRPC.TL_photoPathSize) obj; } return null; } public static String getFileExtension(File file) { String name = file.getName(); try { return name.substring(name.lastIndexOf('.') + 1); } catch (Exception e) { return ""; } } public static String fixFileName(String fileName) { if (fileName != null) { fileName = fileName.replaceAll("[\u0001-\u001f<>\u202E:\"/\\\\|?*\u007f]+", "").trim(); } return fileName; } public static String getDocumentFileName(TLRPC.Document document) { if (document == null) { return null; } if (document.file_name_fixed != null) { return document.file_name_fixed; } String fileName = null; if (document != null) { if (document.file_name != null) { fileName = document.file_name; } else { for (int a = 0; a < document.attributes.size(); a++) { TLRPC.DocumentAttribute documentAttribute = document.attributes.get(a); if (documentAttribute instanceof TLRPC.TL_documentAttributeFilename) { fileName = documentAttribute.file_name; } } } } fileName = fixFileName(fileName); return fileName != null ? fileName : ""; } public static String getMimeTypePart(String mime) { int index; if ((index = mime.lastIndexOf('/')) != -1) { return mime.substring(index + 1); } return ""; } public static String getExtensionByMimeType(String mime) { if (mime != null) { switch (mime) { case "video/mp4": return ".mp4"; case "video/x-matroska": return ".mkv"; case "audio/ogg": return ".ogg"; } } return ""; } public static File getInternalCacheDir() { return ApplicationLoader.applicationContext.getCacheDir(); } public static String getDocumentExtension(TLRPC.Document document) { String fileName = getDocumentFileName(document); int idx = fileName.lastIndexOf('.'); String ext = null; if (idx != -1) { ext = fileName.substring(idx + 1); } if (ext == null || ext.length() == 0) { ext = document.mime_type; } if (ext == null) { ext = ""; } ext = ext.toUpperCase(); return ext; } public static String getAttachFileName(TLObject attach) { return getAttachFileName(attach, null); } public static String getAttachFileName(TLObject attach, String ext) { return getAttachFileName(attach, null, ext); } /** * file hash. contains docId, dcId, ext. */ public static String getAttachFileName(TLObject attach, String size, String ext) { if (attach instanceof TLRPC.Document) { TLRPC.Document document = (TLRPC.Document) attach; String docExt; docExt = getDocumentFileName(document); int idx; if ((idx = docExt.lastIndexOf('.')) == -1) { docExt = ""; } else { docExt = docExt.substring(idx); } if (docExt.length() <= 1) { docExt = getExtensionByMimeType(document.mime_type); } if (docExt.length() > 1) { return document.dc_id + "_" + document.id + docExt; } else { return document.dc_id + "_" + document.id; } } else if (attach instanceof SecureDocument) { SecureDocument secureDocument = (SecureDocument) attach; return secureDocument.secureFile.dc_id + "_" + secureDocument.secureFile.id + ".jpg"; } else if (attach instanceof TLRPC.TL_secureFile) { TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) attach; return secureFile.dc_id + "_" + secureFile.id + ".jpg"; } else if (attach instanceof WebFile) { WebFile document = (WebFile) attach; return Utilities.MD5(document.url) + "." + ImageLoader.getHttpUrlExtension(document.url, getMimeTypePart(document.mime_type)); } else if (attach instanceof TLRPC.PhotoSize) { TLRPC.PhotoSize photo = (TLRPC.PhotoSize) attach; if (photo.location == null || photo.location instanceof TLRPC.TL_fileLocationUnavailable) { return ""; } return photo.location.volume_id + "_" + photo.location.local_id + "." + (ext != null ? ext : "jpg"); } else if (attach instanceof TLRPC.TL_videoSize) { TLRPC.TL_videoSize video = (TLRPC.TL_videoSize) attach; if (video.location == null || video.location instanceof TLRPC.TL_fileLocationUnavailable) { return ""; } return video.location.volume_id + "_" + video.location.local_id + "." + (ext != null ? ext : "mp4"); } else if (attach instanceof TLRPC.FileLocation) { if (attach instanceof TLRPC.TL_fileLocationUnavailable) { return ""; } TLRPC.FileLocation location = (TLRPC.FileLocation) attach; return location.volume_id + "_" + location.local_id + "." + (ext != null ? ext : "jpg"); } else if (attach instanceof TLRPC.UserProfilePhoto) { if (size == null) { size = "s"; } TLRPC.UserProfilePhoto location = (TLRPC.UserProfilePhoto) attach; if (location.photo_small != null) { if ("s".equals(size)) { return getAttachFileName(location.photo_small, ext); } else { return getAttachFileName(location.photo_big, ext); } } else { return location.photo_id + "_" + size + "." + (ext != null ? ext : "jpg"); } } else if (attach instanceof TLRPC.ChatPhoto) { TLRPC.ChatPhoto location = (TLRPC.ChatPhoto) attach; if (location.photo_small != null) { if ("s".equals(size)) { return getAttachFileName(location.photo_small, ext); } else { return getAttachFileName(location.photo_big, ext); } } else { return location.photo_id + "_" + size + "." + (ext != null ? ext : "jpg"); } } return ""; } public void deleteFiles(final ArrayList<File> files, final int type) { if (files == null || files.isEmpty()) { return; } fileLoaderQueue.postRunnable(() -> { for (int a = 0; a < files.size(); a++) { File file = files.get(a); File encrypted = new File(file.getAbsolutePath() + ".enc"); if (encrypted.exists()) { try { if (!encrypted.delete()) { encrypted.deleteOnExit(); } } catch (Exception e) { FileLog.e(e); } try { File key = new File(FileLoader.getInternalCacheDir(), file.getName() + ".enc.key"); if (!key.delete()) { key.deleteOnExit(); } } catch (Exception e) { FileLog.e(e); } } else if (file.exists()) { try { if (!file.delete()) { file.deleteOnExit(); } } catch (Exception e) { FileLog.e(e); } } try { File qFile = new File(file.getParentFile(), "q_" + file.getName()); if (qFile.exists()) { if (!qFile.delete()) { qFile.deleteOnExit(); } } } catch (Exception e) { FileLog.e(e); } } if (type == 2) { ImageLoader.getInstance().clearMemory(); } }); } public static boolean isVideoMimeType(String mime) { return "video/mp4".equals(mime) || SharedConfig.streamMkv && "video/x-matroska".equals(mime); } public static boolean copyFile(InputStream sourceFile, File destFile) throws IOException { return copyFile(sourceFile, destFile, -1); } public static boolean copyFile(InputStream sourceFile, File destFile, int maxSize) throws IOException { FileOutputStream out = new FileOutputStream(destFile); byte[] buf = new byte[4096]; int len; int totalLen = 0; while ((len = sourceFile.read(buf)) > 0) { Thread.yield(); out.write(buf, 0, len); totalLen += len; if (maxSize > 0 && totalLen >= maxSize) { break; } } out.getFD().sync(); out.close(); return true; } public static boolean isSamePhoto(TLObject photo1, TLObject photo2) { if (photo1 == null && photo2 != null || photo1 != null && photo2 == null) { return false; } if (photo1 == null && photo2 == null) { return true; } if (photo1.getClass() != photo2.getClass()) { return false; } if (photo1 instanceof TLRPC.UserProfilePhoto) { TLRPC.UserProfilePhoto p1 = (TLRPC.UserProfilePhoto) photo1; TLRPC.UserProfilePhoto p2 = (TLRPC.UserProfilePhoto) photo2; return p1.photo_id == p2.photo_id; } else if (photo1 instanceof TLRPC.ChatPhoto) { TLRPC.ChatPhoto p1 = (TLRPC.ChatPhoto) photo1; TLRPC.ChatPhoto p2 = (TLRPC.ChatPhoto) photo2; return p1.photo_id == p2.photo_id; } return false; } public static boolean isSamePhoto(TLRPC.FileLocation location, TLRPC.Photo photo) { if (location == null || !(photo instanceof TLRPC.TL_photo)) { return false; } for (int b = 0, N = photo.sizes.size(); b < N; b++) { TLRPC.PhotoSize size = photo.sizes.get(b); if (size.location != null && size.location.local_id == location.local_id && size.location.volume_id == location.volume_id) { return true; } } if (-location.volume_id == photo.id) { return true; } return false; } public static long getPhotoId(TLObject object) { if (object instanceof TLRPC.Photo) { return ((TLRPC.Photo) object).id; } else if (object instanceof TLRPC.ChatPhoto) { return ((TLRPC.ChatPhoto) object).photo_id; } else if (object instanceof TLRPC.UserProfilePhoto) { return ((TLRPC.UserProfilePhoto) object).photo_id; } return 0; } public void getCurrentLoadingFiles(ArrayList<MessageObject> currentLoadingFiles) { currentLoadingFiles.clear(); currentLoadingFiles.addAll(getDownloadController().downloadingFiles); for (int i = 0; i < currentLoadingFiles.size(); i++) { currentLoadingFiles.get(i).isDownloadingFile = true; } } public void getRecentLoadingFiles(ArrayList<MessageObject> recentLoadingFiles) { recentLoadingFiles.clear(); recentLoadingFiles.addAll(getDownloadController().recentDownloadingFiles); for (int i = 0; i < recentLoadingFiles.size(); i++) { recentLoadingFiles.get(i).isDownloadingFile = true; } } public void checkCurrentDownloadsFiles() { ArrayList<MessageObject> messagesToRemove = new ArrayList<>(); ArrayList<MessageObject> messageObjects = new ArrayList<>(getDownloadController().recentDownloadingFiles); for (int i = 0; i < messageObjects.size(); i++) { messageObjects.get(i).checkMediaExistance(); if (messageObjects.get(i).mediaExists) { messagesToRemove.add(messageObjects.get(i)); } } if (!messagesToRemove.isEmpty()) { AndroidUtilities.runOnUIThread(() -> { getDownloadController().recentDownloadingFiles.removeAll(messagesToRemove); getNotificationCenter().postNotificationName(NotificationCenter.onDownloadingFilesChanged); }); } } /** * optimezed for bulk messages */ public void checkMediaExistance(ArrayList<MessageObject> messageObjects) { getFileDatabase().checkMediaExistance(messageObjects); } public interface FileResolver { File getFile(); } public void clearRecentDownloadedFiles() { getDownloadController().clearRecentDownloadedFiles(); } public void clearFilePaths() { filePathDatabase.clear(); } public static boolean checkUploadFileSize(int currentAccount, long length) { boolean premium = AccountInstance.getInstance(currentAccount).getUserConfig().isPremium(); if (length < DEFAULT_MAX_FILE_SIZE || (length < DEFAULT_MAX_FILE_SIZE_PREMIUM && premium)) { return true; } return false; } private static class LoadOperationUIObject { Runnable loadInternalRunnable; } public static byte[] longToBytes(long x) { ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); buffer.putLong(x); return buffer.array(); } public static long bytesToLong(byte[] bytes) { long l = 0; for (int i = 0; i < 8; i++) { l <<= 8; l ^= bytes[i] & 0xFF; } return l; } }
dawitys/Telegram
TMessagesProj/src/main/java/org/telegram/messenger/FileLoader.java
41,696
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.ui.Components; import static com.google.android.exoplayer2.C.TRACK_TYPE_AUDIO; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.SurfaceTexture; import android.media.AudioManager; import android.media.MediaFormat; import android.net.Uri; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.view.Surface; import android.view.SurfaceView; import android.view.TextureView; import android.view.ViewGroup; import androidx.annotation.Nullable; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.DefaultLoadControl; import com.google.android.exoplayer2.DefaultRenderersFactory; import com.google.android.exoplayer2.ExoPlayer; import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.MediaItem; import com.google.android.exoplayer2.MediaMetadata; import com.google.android.exoplayer2.PlaybackException; import com.google.android.exoplayer2.PlaybackParameters; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.SeekParameters; import com.google.android.exoplayer2.analytics.AnalyticsListener; import com.google.android.exoplayer2.audio.AudioAttributes; import com.google.android.exoplayer2.audio.AudioCapabilities; import com.google.android.exoplayer2.audio.AudioProcessor; import com.google.android.exoplayer2.audio.AudioSink; import com.google.android.exoplayer2.audio.DefaultAudioSink; import com.google.android.exoplayer2.audio.TeeAudioProcessor; import com.google.android.exoplayer2.mediacodec.MediaCodecRenderer; import com.google.android.exoplayer2.source.LoopingMediaSource; import com.google.android.exoplayer2.source.MediaSource; import com.google.android.exoplayer2.source.ProgressiveMediaSource; import com.google.android.exoplayer2.source.dash.DashMediaSource; import com.google.android.exoplayer2.source.hls.HlsMediaSource; import com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource; import com.google.android.exoplayer2.trackselection.DefaultTrackSelector; import com.google.android.exoplayer2.trackselection.MappingTrackSelector; import com.google.android.exoplayer2.upstream.DataSource; import com.google.android.exoplayer2.upstream.DefaultAllocator; import com.google.android.exoplayer2.util.Log; import com.google.android.exoplayer2.video.SurfaceNotValidException; import com.google.android.exoplayer2.video.VideoListener; import com.google.android.exoplayer2.video.VideoSize; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.DispatchQueue; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FourierTransform; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.secretmedia.ExtendedDefaultDataSourceFactory; import org.telegram.ui.Stories.recorder.StoryEntry; import java.nio.ByteBuffer; import java.nio.ByteOrder; @SuppressLint("NewApi") public class VideoPlayer implements Player.Listener, VideoListener, AnalyticsListener, NotificationCenter.NotificationCenterDelegate { private DispatchQueue workerQueue; private boolean isStory; public boolean createdWithAudioTrack() { return !audioDisabled; } public interface VideoPlayerDelegate { void onStateChanged(boolean playWhenReady, int playbackState); void onError(VideoPlayer player, Exception e); void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio); void onRenderedFirstFrame(); void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture); boolean onSurfaceDestroyed(SurfaceTexture surfaceTexture); default void onRenderedFirstFrame(EventTime eventTime) { } default void onSeekStarted(EventTime eventTime) { } default void onSeekFinished(EventTime eventTime) { } } public interface AudioVisualizerDelegate { void onVisualizerUpdate(boolean playing, boolean animate, float[] values); boolean needUpdate(); } public ExoPlayer player; private ExoPlayer audioPlayer; private MappingTrackSelector trackSelector; private DataSource.Factory mediaDataSourceFactory; private TextureView textureView; private SurfaceView surfaceView; private Surface surface; private boolean isStreaming; private boolean autoplay; private boolean mixedAudio; public boolean allowMultipleInstances; private boolean triedReinit; private Uri currentUri; private boolean videoPlayerReady; private boolean audioPlayerReady; private boolean mixedPlayWhenReady; private VideoPlayerDelegate delegate; private AudioVisualizerDelegate audioVisualizerDelegate; private int lastReportedPlaybackState; private boolean lastReportedPlayWhenReady; private Uri videoUri, audioUri; private String videoType, audioType; private boolean loopingMediaSource; private boolean looping; private int repeatCount; private boolean shouldPauseOther; MediaSource.Factory dashMediaSourceFactory; HlsMediaSource.Factory hlsMediaSourceFactory; SsMediaSource.Factory ssMediaSourceFactory; ProgressiveMediaSource.Factory progressiveMediaSourceFactory; Handler audioUpdateHandler = new Handler(Looper.getMainLooper()); boolean audioDisabled; public VideoPlayer() { this(true, false); } static int playerCounter = 0; public VideoPlayer(boolean pauseOther, boolean audioDisabled) { this.audioDisabled = audioDisabled; mediaDataSourceFactory = new ExtendedDefaultDataSourceFactory(ApplicationLoader.applicationContext, "Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20150101 Firefox/47.0 (Chrome)"); trackSelector = new DefaultTrackSelector(ApplicationLoader.applicationContext); if (audioDisabled) { trackSelector.setParameters(trackSelector.getParameters().buildUpon().setTrackTypeDisabled(TRACK_TYPE_AUDIO, true).build()); } lastReportedPlaybackState = ExoPlayer.STATE_IDLE; shouldPauseOther = pauseOther; if (pauseOther) { NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.playerDidStartPlaying); } playerCounter++; } @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.playerDidStartPlaying) { VideoPlayer p = (VideoPlayer) args[0]; if (p != this && isPlaying() && !allowMultipleInstances) { pause(); } } } private void ensurePlayerCreated() { DefaultLoadControl loadControl; if (isStory) { loadControl = new DefaultLoadControl( new DefaultAllocator(true, C.DEFAULT_BUFFER_SEGMENT_SIZE), DefaultLoadControl.DEFAULT_MIN_BUFFER_MS, DefaultLoadControl.DEFAULT_MAX_BUFFER_MS, 1000, 1000, DefaultLoadControl.DEFAULT_TARGET_BUFFER_BYTES, DefaultLoadControl.DEFAULT_PRIORITIZE_TIME_OVER_SIZE_THRESHOLDS, DefaultLoadControl.DEFAULT_BACK_BUFFER_DURATION_MS, DefaultLoadControl.DEFAULT_RETAIN_BACK_BUFFER_FROM_KEYFRAME); } else { loadControl = new DefaultLoadControl( new DefaultAllocator(true, C.DEFAULT_BUFFER_SEGMENT_SIZE), DefaultLoadControl.DEFAULT_MIN_BUFFER_MS, DefaultLoadControl.DEFAULT_MAX_BUFFER_MS, 100, DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS, DefaultLoadControl.DEFAULT_TARGET_BUFFER_BYTES, DefaultLoadControl.DEFAULT_PRIORITIZE_TIME_OVER_SIZE_THRESHOLDS, DefaultLoadControl.DEFAULT_BACK_BUFFER_DURATION_MS, DefaultLoadControl.DEFAULT_RETAIN_BACK_BUFFER_FROM_KEYFRAME); } if (player == null) { DefaultRenderersFactory factory; if (audioVisualizerDelegate != null) { factory = new AudioVisualizerRenderersFactory(ApplicationLoader.applicationContext); } else { factory = new DefaultRenderersFactory(ApplicationLoader.applicationContext); } factory.setExtensionRendererMode(DefaultRenderersFactory.EXTENSION_RENDERER_MODE_PREFER); player = new ExoPlayer.Builder(ApplicationLoader.applicationContext).setRenderersFactory(factory) .setTrackSelector(trackSelector) .setLoadControl(loadControl).build(); player.addAnalyticsListener(this); player.addListener(this); player.addVideoListener(this); if (textureView != null) { player.setVideoTextureView(textureView); } else if (surface != null) { player.setVideoSurface(surface); } else if (surfaceView != null) { player.setVideoSurfaceView(surfaceView); } player.setPlayWhenReady(autoplay); player.setRepeatMode(looping ? ExoPlayer.REPEAT_MODE_ALL : ExoPlayer.REPEAT_MODE_OFF); } if (mixedAudio) { if (audioPlayer == null) { audioPlayer = new ExoPlayer.Builder(ApplicationLoader.applicationContext) .setTrackSelector(trackSelector) .setLoadControl(loadControl).buildSimpleExoPlayer(); audioPlayer.addListener(new Player.Listener() { @Override public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { if (!audioPlayerReady && playbackState == Player.STATE_READY) { audioPlayerReady = true; checkPlayersReady(); } } }); audioPlayer.setPlayWhenReady(autoplay); } } } public void preparePlayerLoop(Uri videoUri, String videoType, Uri audioUri, String audioType) { this.videoUri = videoUri; this.audioUri = audioUri; this.videoType = videoType; this.audioType = audioType; this.loopingMediaSource = true; mixedAudio = true; audioPlayerReady = false; videoPlayerReady = false; ensurePlayerCreated(); MediaSource mediaSource1 = null, mediaSource2 = null; for (int a = 0; a < 2; a++) { MediaSource mediaSource; String type; Uri uri; if (a == 0) { type = videoType; uri = videoUri; } else { type = audioType; uri = audioUri; } mediaSource = mediaSourceFromUri(uri, type); mediaSource = new LoopingMediaSource(mediaSource); if (a == 0) { mediaSource1 = mediaSource; } else { mediaSource2 = mediaSource; } } player.setMediaSource(mediaSource1, true); player.prepare(); audioPlayer.setMediaSource(mediaSource2, true); audioPlayer.prepare(); } private MediaSource mediaSourceFromUri(Uri uri, String type) { MediaItem mediaItem = new MediaItem.Builder().setUri(uri).build(); switch (type) { case "dash": if (dashMediaSourceFactory == null) { dashMediaSourceFactory = new DashMediaSource.Factory(mediaDataSourceFactory); } return dashMediaSourceFactory.createMediaSource(mediaItem); case "hls": if (hlsMediaSourceFactory == null) { hlsMediaSourceFactory = new HlsMediaSource.Factory(mediaDataSourceFactory); } return hlsMediaSourceFactory.createMediaSource(mediaItem); case "ss": if (ssMediaSourceFactory == null) { ssMediaSourceFactory = new SsMediaSource.Factory(mediaDataSourceFactory); } return ssMediaSourceFactory.createMediaSource(mediaItem); default: if (progressiveMediaSourceFactory == null) { progressiveMediaSourceFactory = new ProgressiveMediaSource.Factory(mediaDataSourceFactory); } return progressiveMediaSourceFactory.createMediaSource(mediaItem); } } public void preparePlayer(Uri uri, String type) { preparePlayer(uri, type, FileLoader.PRIORITY_HIGH); } public void preparePlayer(Uri uri, String type, int priority) { this.videoUri = uri; this.videoType = type; this.audioUri = null; this.audioType = null; this.loopingMediaSource = false; videoPlayerReady = false; mixedAudio = false; currentUri = uri; String scheme = uri != null ? uri.getScheme() : null; isStreaming = scheme != null && !scheme.startsWith("file"); ensurePlayerCreated(); MediaSource mediaSource = mediaSourceFromUri(uri, type); player.setMediaSource(mediaSource, true); player.prepare(); } public boolean isPlayerPrepared() { return player != null; } public void releasePlayer(boolean async) { if (player != null) { player.release(); player = null; } if (audioPlayer != null) { audioPlayer.release(); audioPlayer = null; } if (shouldPauseOther) { NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.playerDidStartPlaying); } playerCounter--; } @Override public void onSeekStarted(EventTime eventTime) { if (delegate != null) { delegate.onSeekStarted(eventTime); } } @Override public void onSeekProcessed(EventTime eventTime) { if (delegate != null) { delegate.onSeekFinished(eventTime); } } @Override public void onRenderedFirstFrame(EventTime eventTime, Object output, long renderTimeMs) { if (delegate != null) { delegate.onRenderedFirstFrame(eventTime); } } public void setTextureView(TextureView texture) { if (textureView == texture) { return; } textureView = texture; if (player == null) { return; } player.setVideoTextureView(textureView); } public void setSurfaceView(SurfaceView surfaceView) { if (this.surfaceView == surfaceView) { return; } this.surfaceView = surfaceView; if (player == null) { return; } player.setVideoSurfaceView(surfaceView); } public void setSurface(Surface s) { if (surface == s) { return; } surface = s; if (player == null) { return; } player.setVideoSurface(surface); } public boolean getPlayWhenReady() { return player.getPlayWhenReady(); } public int getPlaybackState() { return player.getPlaybackState(); } public Uri getCurrentUri() { return currentUri; } public void play() { mixedPlayWhenReady = true; if (mixedAudio) { if (!audioPlayerReady || !videoPlayerReady) { if (player != null) { player.setPlayWhenReady(false); } if (audioPlayer != null) { audioPlayer.setPlayWhenReady(false); } return; } } if (player != null) { player.setPlayWhenReady(true); } if (audioPlayer != null) { audioPlayer.setPlayWhenReady(true); } } public void pause() { mixedPlayWhenReady = false; if (player != null) { player.setPlayWhenReady(false); } if (audioPlayer != null) { audioPlayer.setPlayWhenReady(false); } if (audioVisualizerDelegate != null) { audioUpdateHandler.removeCallbacksAndMessages(null); audioVisualizerDelegate.onVisualizerUpdate(false, true, null); } } public void setPlaybackSpeed(float speed) { if (player != null) { player.setPlaybackParameters(new PlaybackParameters(speed, speed > 1.0f ? 0.98f : 1.0f)); } } public void setPlayWhenReady(boolean playWhenReady) { mixedPlayWhenReady = playWhenReady; if (playWhenReady && mixedAudio) { if (!audioPlayerReady || !videoPlayerReady) { if (player != null) { player.setPlayWhenReady(false); } if (audioPlayer != null) { audioPlayer.setPlayWhenReady(false); } return; } } autoplay = playWhenReady; if (player != null) { player.setPlayWhenReady(playWhenReady); } if (audioPlayer != null) { audioPlayer.setPlayWhenReady(playWhenReady); } } public long getDuration() { return player != null ? player.getDuration() : 0; } public long getCurrentPosition() { return player != null ? player.getCurrentPosition() : 0; } public boolean isMuted() { return player != null && player.getVolume() == 0.0f; } public void setMute(boolean value) { if (player != null) { player.setVolume(value ? 0.0f : 1.0f); } if (audioPlayer != null) { audioPlayer.setVolume(value ? 0.0f : 1.0f); } } @Override public void onRepeatModeChanged(int repeatMode) { } @Override public void onSurfaceSizeChanged(int width, int height) { } public void setVolume(float volume) { if (player != null) { player.setVolume(volume); } if (audioPlayer != null) { audioPlayer.setVolume(volume); } } public void seekTo(long positionMs) { seekTo(positionMs, false); } public void seekTo(long positionMs, boolean fast) { if (player != null) { player.setSeekParameters(fast ? SeekParameters.CLOSEST_SYNC : SeekParameters.EXACT); player.seekTo(positionMs); } } public void setDelegate(VideoPlayerDelegate videoPlayerDelegate) { delegate = videoPlayerDelegate; } public void setAudioVisualizerDelegate(AudioVisualizerDelegate audioVisualizerDelegate) { this.audioVisualizerDelegate = audioVisualizerDelegate; } public int getBufferedPercentage() { return isStreaming ? (player != null ? player.getBufferedPercentage() : 0) : 100; } public long getBufferedPosition() { return player != null ? (isStreaming ? player.getBufferedPosition() : player.getDuration()) : 0; } public boolean isStreaming() { return isStreaming; } public boolean isPlaying() { return mixedAudio && mixedPlayWhenReady || player != null && player.getPlayWhenReady(); } public boolean isBuffering() { return player != null && lastReportedPlaybackState == ExoPlayer.STATE_BUFFERING; } private boolean handleAudioFocus = false; public void handleAudioFocus(boolean handleAudioFocus) { this.handleAudioFocus = handleAudioFocus; if (player != null) { player.setAudioAttributes(player.getAudioAttributes(), handleAudioFocus); } } public void setStreamType(int type) { if (player != null) { player.setAudioAttributes(new AudioAttributes.Builder() .setUsage(type == AudioManager.STREAM_VOICE_CALL ? C.USAGE_VOICE_COMMUNICATION : C.USAGE_MEDIA) .build(), handleAudioFocus); } if (audioPlayer != null) { audioPlayer.setAudioAttributes(new AudioAttributes.Builder() .setUsage(type == AudioManager.STREAM_VOICE_CALL ? C.USAGE_VOICE_COMMUNICATION : C.USAGE_MEDIA) .build(), true); } } public void setLooping(boolean looping) { if (this.looping != looping) { this.looping = looping; if (player != null) { player.setRepeatMode(looping ? ExoPlayer.REPEAT_MODE_ALL : ExoPlayer.REPEAT_MODE_OFF); } } } public boolean isLooping() { return looping; } private void checkPlayersReady() { if (audioPlayerReady && videoPlayerReady && mixedPlayWhenReady) { play(); } } @Override public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { maybeReportPlayerState(); if (playWhenReady && playbackState == Player.STATE_READY && !isMuted() && shouldPauseOther) { NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.playerDidStartPlaying, this); } if (!videoPlayerReady && playbackState == Player.STATE_READY) { videoPlayerReady = true; checkPlayersReady(); } if (playbackState != Player.STATE_READY) { audioUpdateHandler.removeCallbacksAndMessages(null); if (audioVisualizerDelegate != null) { audioVisualizerDelegate.onVisualizerUpdate(false, true, null); } } } @Override public void onPositionDiscontinuity(Player.PositionInfo oldPosition, Player.PositionInfo newPosition, @Player.DiscontinuityReason int reason) { if (reason == Player.DISCONTINUITY_REASON_AUTO_TRANSITION) { repeatCount++; } } @Override public void onPlayerError(PlaybackException error) { AndroidUtilities.runOnUIThread(() -> { Throwable cause = error.getCause(); if (textureView != null && (!triedReinit && cause instanceof MediaCodecRenderer.DecoderInitializationException || cause instanceof SurfaceNotValidException)) { triedReinit = true; if (player != null) { ViewGroup parent = (ViewGroup) textureView.getParent(); if (parent != null) { int i = parent.indexOfChild(textureView); parent.removeView(textureView); parent.addView(textureView, i); } if (workerQueue != null) { workerQueue.postRunnable(() -> { if (player != null) { player.clearVideoTextureView(textureView); player.setVideoTextureView(textureView); if (loopingMediaSource) { preparePlayerLoop(videoUri, videoType, audioUri, audioType); } else { preparePlayer(videoUri, videoType); } play(); } }); } else { player.clearVideoTextureView(textureView); player.setVideoTextureView(textureView); if (loopingMediaSource) { preparePlayerLoop(videoUri, videoType, audioUri, audioType); } else { preparePlayer(videoUri, videoType); } play(); } } } else { delegate.onError(this, error); } }); } public VideoSize getVideoSize() { return player != null ? player.getVideoSize() : null; } @Override public void onVideoSizeChanged(VideoSize videoSize) { delegate.onVideoSizeChanged(videoSize.width, videoSize.height, videoSize.unappliedRotationDegrees, videoSize.pixelWidthHeightRatio); Player.Listener.super.onVideoSizeChanged(videoSize); } @Override public void onRenderedFirstFrame() { delegate.onRenderedFirstFrame(); } @Override public boolean onSurfaceDestroyed(SurfaceTexture surfaceTexture) { return delegate.onSurfaceDestroyed(surfaceTexture); } @Override public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) { delegate.onSurfaceTextureUpdated(surfaceTexture); } @Override public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) { } private void maybeReportPlayerState() { if (player == null) { return; } boolean playWhenReady = player.getPlayWhenReady(); int playbackState = player.getPlaybackState(); if (lastReportedPlayWhenReady != playWhenReady || lastReportedPlaybackState != playbackState) { delegate.onStateChanged(playWhenReady, playbackState); lastReportedPlayWhenReady = playWhenReady; lastReportedPlaybackState = playbackState; } } public int getRepeatCount() { return repeatCount; } private class AudioVisualizerRenderersFactory extends DefaultRenderersFactory { public AudioVisualizerRenderersFactory(Context context) { super(context); } @Nullable @Override protected AudioSink buildAudioSink(Context context, boolean enableFloatOutput, boolean enableAudioTrackPlaybackParams, boolean enableOffload) { return new DefaultAudioSink.Builder() .setAudioCapabilities(AudioCapabilities.getCapabilities(context)) .setEnableFloatOutput(enableFloatOutput) .setEnableAudioTrackPlaybackParams(enableAudioTrackPlaybackParams) .setAudioProcessors(new AudioProcessor[] {new TeeAudioProcessor(new VisualizerBufferSink())}) .setOffloadMode( enableOffload ? DefaultAudioSink.OFFLOAD_MODE_ENABLED_GAPLESS_REQUIRED : DefaultAudioSink.OFFLOAD_MODE_DISABLED) .build(); } } private class VisualizerBufferSink implements TeeAudioProcessor.AudioBufferSink { private final int BUFFER_SIZE = 1024; private final int MAX_BUFFER_SIZE = BUFFER_SIZE * 8; FourierTransform.FFT fft = new FourierTransform.FFT(BUFFER_SIZE, 48000); float[] real = new float[BUFFER_SIZE]; ByteBuffer byteBuffer; int position = 0; public VisualizerBufferSink() { byteBuffer = ByteBuffer.allocateDirect(MAX_BUFFER_SIZE); byteBuffer.position(0); } @Override public void flush(int sampleRateHz, int channelCount, int encoding) { } long lastUpdateTime; @Override public void handleBuffer(ByteBuffer buffer) { if (audioVisualizerDelegate == null) { return; } if (buffer == AudioProcessor.EMPTY_BUFFER || !mixedPlayWhenReady) { audioUpdateHandler.postDelayed(() -> { audioUpdateHandler.removeCallbacksAndMessages(null); audioVisualizerDelegate.onVisualizerUpdate(false, true, null); }, 80); return; } if (!audioVisualizerDelegate.needUpdate()) { return; } int len = buffer.limit(); if (len > MAX_BUFFER_SIZE) { audioUpdateHandler.removeCallbacksAndMessages(null); audioVisualizerDelegate.onVisualizerUpdate(false, true, null); return; // len = MAX_BUFFER_SIZE; // byte[] bytes = new byte[BUFFER_SIZE]; // buffer.get(bytes); // byteBuffer.put(bytes, 0, BUFFER_SIZE); } else { byteBuffer.put(buffer); } position += len; if (position >= BUFFER_SIZE) { len = BUFFER_SIZE; byteBuffer.position(0); for (int i = 0; i < len; i++) { real[i] = (byteBuffer.getShort()) / 32768.0F; } byteBuffer.rewind(); position = 0; fft.forward(real); float sum = 0; for (int i = 0; i < len; i++) { float r = fft.getSpectrumReal()[i]; float img = fft.getSpectrumImaginary()[i]; float peak = (float) Math.sqrt(r * r + img * img) / 30f; if (peak > 1f) { peak = 1f; } else if (peak < 0) { peak = 0; } sum += peak * peak; } float amplitude = (float) (Math.sqrt(sum / len)); float[] partsAmplitude = new float[7]; partsAmplitude[6] = amplitude; if (amplitude < 0.4f) { for (int k = 0; k < 7; k++) { partsAmplitude[k] = 0; } } else { int part = len / 6; for (int k = 0; k < 6; k++) { int start = part * k; float r = fft.getSpectrumReal()[start]; float img = fft.getSpectrumImaginary()[start]; partsAmplitude[k] = (float) (Math.sqrt(r * r + img * img) / 30f); if (partsAmplitude[k] > 1f) { partsAmplitude[k] = 1f; } else if (partsAmplitude[k] < 0) { partsAmplitude[k] = 0; } } } int updateInterval = 64; if (System.currentTimeMillis() - lastUpdateTime < updateInterval) { return; } lastUpdateTime = System.currentTimeMillis(); audioUpdateHandler.postDelayed(() -> audioVisualizerDelegate.onVisualizerUpdate(true, true, partsAmplitude), 130); } } } public boolean isHDR() { if (player == null) { return false; } try { Format format = player.getVideoFormat(); if (format == null || format.colorInfo == null) { return false; } return ( format.colorInfo.colorTransfer == C.COLOR_TRANSFER_ST2084 || format.colorInfo.colorTransfer == C.COLOR_TRANSFER_HLG ); } catch (Exception ignore) {} return false; } public StoryEntry.HDRInfo getHDRStaticInfo(StoryEntry.HDRInfo hdrInfo) { if (hdrInfo == null) { hdrInfo = new StoryEntry.HDRInfo(); } try { MediaFormat mediaFormat = ((MediaCodecRenderer) player.getRenderer(0)).codecOutputMediaFormat; ByteBuffer byteBuffer = mediaFormat.getByteBuffer(MediaFormat.KEY_HDR_STATIC_INFO); byteBuffer.order(ByteOrder.LITTLE_ENDIAN); if (byteBuffer.get() == 0) { hdrInfo.maxlum = byteBuffer.getShort(17); hdrInfo.minlum = byteBuffer.getShort(19) * 0.0001f; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { if (mediaFormat.containsKey(MediaFormat.KEY_COLOR_TRANSFER)) { hdrInfo.colorTransfer = mediaFormat.getInteger(MediaFormat.KEY_COLOR_TRANSFER); } if (mediaFormat.containsKey(MediaFormat.KEY_COLOR_STANDARD)) { hdrInfo.colorStandard = mediaFormat.getInteger(MediaFormat.KEY_COLOR_STANDARD); } if (mediaFormat.containsKey(MediaFormat.KEY_COLOR_RANGE)) { hdrInfo.colorRange = mediaFormat.getInteger(MediaFormat.KEY_COLOR_RANGE); } } } catch (Exception ignore) { hdrInfo.maxlum = hdrInfo.minlum = 0; } return hdrInfo; } public void setWorkerQueue(DispatchQueue dispatchQueue) { workerQueue = dispatchQueue; player.setWorkerQueue(dispatchQueue); } public void setIsStory() { isStory = true; } }
Telegram-FOSS-Team/Telegram-FOSS
TMessagesProj/src/main/java/org/telegram/ui/Components/VideoPlayer.java
41,697
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.grid.node.docker; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.openqa.selenium.Capabilities; import org.openqa.selenium.docker.Container; import org.openqa.selenium.grid.node.DefaultActiveSession; import org.openqa.selenium.internal.Require; import org.openqa.selenium.remote.Dialect; import org.openqa.selenium.remote.SessionId; import org.openqa.selenium.remote.http.HttpClient; import org.openqa.selenium.remote.tracing.Tracer; public class DockerSession extends DefaultActiveSession { private static final Logger LOG = Logger.getLogger(DockerSession.class.getName()); private final Container container; private final Container videoContainer; private final DockerAssetsPath assetsPath; DockerSession( Container container, Container videoContainer, Tracer tracer, HttpClient client, SessionId id, URL url, Capabilities stereotype, Capabilities capabilities, Dialect downstream, Dialect upstream, Instant startTime, DockerAssetsPath assetsPath) { super(tracer, client, id, url, downstream, upstream, stereotype, capabilities, startTime); this.container = Require.nonNull("Container", container); this.videoContainer = videoContainer; this.assetsPath = Require.nonNull("Assets path", assetsPath); } @Override public void stop() { if (videoContainer != null) { videoContainer.stop(Duration.ofSeconds(10)); } saveLogs(); container.stop(Duration.ofMinutes(1)); } private void saveLogs() { String sessionAssetsPath = assetsPath.getContainerPath(getId()); String seleniumServerLog = String.format("%s/selenium-server.log", sessionAssetsPath); try { List<String> logs = container.getLogs().getLogLines(); Files.write(Paths.get(seleniumServerLog), logs); } catch (Exception e) { LOG.log(Level.WARNING, "Error saving logs", e); } } }
SeleniumHQ/selenium
java/src/org/openqa/selenium/grid/node/docker/DockerSession.java
41,698
package org.telegram.ui.Stories; import static android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PixelFormat; import android.graphics.RectF; import android.media.AudioManager; import android.net.Uri; import android.os.Build; import android.util.Log; import android.util.LongSparseArray; import android.util.SparseArray; import android.view.GestureDetector; import android.view.Gravity; import android.view.HapticFeedbackConstants; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SurfaceView; import android.view.TextureView; import android.view.View; import android.view.ViewGroup; import android.view.WindowInsets; import android.view.WindowManager; import android.widget.FrameLayout; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.graphics.ColorUtils; import androidx.core.math.MathUtils; import androidx.viewpager.widget.ViewPager; import com.google.android.exoplayer2.ExoPlayer; import com.google.android.exoplayer2.ui.AspectRatioFrameLayout; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AnimationNotificationsLocker; import org.telegram.messenger.BotWebViewVibrationEffect; import org.telegram.messenger.BuildVars; import org.telegram.messenger.ChatObject; import org.telegram.messenger.DialogObject; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.FileStreamLoadOperation; import org.telegram.messenger.ImageReceiver; import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessagesController; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.SharedConfig; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; import org.telegram.messenger.support.LongSparseIntArray; import org.telegram.messenger.video.VideoPlayerHolderBase; import org.telegram.tgnet.TLRPC; import org.telegram.tgnet.tl.TL_stories; import org.telegram.ui.ActionBar.AdjustPanLayoutHelper; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ArticleViewer; import org.telegram.ui.Cells.ChatActionCell; import org.telegram.ui.Components.Bulletin; import org.telegram.ui.Components.CubicBezierInterpolator; import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.RadialProgress; import org.telegram.ui.Components.RecyclerListView; import org.telegram.ui.Components.SizeNotifierFrameLayout; import org.telegram.ui.LaunchActivity; import java.util.ArrayList; import java.util.Objects; public class StoryViewer implements NotificationCenter.NotificationCenterDelegate { public static boolean animationInProgress; public boolean USE_SURFACE_VIEW = SharedConfig.useSurfaceInStories; public boolean ATTACH_TO_FRAGMENT = true; public boolean foundViewToClose = false; public int allowScreenshotsCounter; public boolean allowScreenshots = true; public static ArrayList<StoryViewer> globalInstances = new ArrayList<>(); BaseFragment fragment; public int currentAccount; WindowManager windowManager; WindowManager.LayoutParams windowLayoutParams; public SizeNotifierFrameLayout windowView; HwFrameLayout containerView; SelfStoryViewsView selfStoryViewsView; Paint inputBackgroundPaint; boolean keyboardVisible; private static TL_stories.StoryItem lastStoryItem; Theme.ResourcesProvider resourcesProvider = new DarkThemeResourceProvider(); private boolean opening; ValueAnimator openCloseAnimator; ValueAnimator swipeToDissmissBackAnimator; ValueAnimator swipeToReplyBackAnimator; long lastDialogId; int lastPosition; float fromXCell; float fromYCell; StoriesListPlaceProvider.AvatarOverlaysView animateFromCell; float fromX; float fromY; float clipTop; float clipBottom; float fromWidth; float fromHeight; RectF avatarRectTmp = new RectF(); float progressToOpen; float progressToDismiss; float swipeToDismissOffset; float swipeToDismissHorizontalOffset; float swipeToDismissHorizontalDirection; float swipeToReplyOffset; boolean swipeToReplyWaitingKeyboard; float fromDismissOffset; boolean allowSelfStoriesView; float swipeToReplyProgress; float progressToSelfStoryViewsViews; float selfStoriesViewsOffset; boolean allowIntercept; boolean verticalScrollDetected; boolean allowSwipeToDissmiss; GestureDetector gestureDetector; boolean inSwipeToDissmissMode; boolean inSeekingMode; boolean allowSwipeToReply; boolean isShowing; public StoriesViewPager storiesViewPager; float pointPosition[] = new float[2]; private int realKeyboardHeight; private boolean isInTouchMode; private float hideEnterViewProgress; public final TransitionViewHolder transitionViewHolder = new TransitionViewHolder(); public PlaceProvider placeProvider; Dialog currentDialog; private boolean allowTouchesByViewpager = false; boolean openedFromLightNavigationBar; ArrayList<Runnable> doOnAnimationReadyRunnables = new ArrayList<>(); // to prevent attach/detach textureView in view pager and // ensure that player is singleton // create and attach texture view in contentView // draw it in page AspectRatioFrameLayout aspectRatioFrameLayout; VideoPlayerHolder playerHolder; private TextureView textureView; private SurfaceView surfaceView; Uri lastUri; PeerStoriesView.VideoPlayerSharedScope currentPlayerScope; private boolean isClosed = true; private boolean isRecording; AnimationNotificationsLocker locker = new AnimationNotificationsLocker(); private boolean isWaiting; private boolean fullyVisible; private boolean isCaption; LaunchActivity parentActivity; ArrayList<VideoPlayerHolder> preparedPlayers = new ArrayList<>(); boolean isSingleStory; StoriesController.StoriesList storiesList; public int dayStoryId; TL_stories.PeerStories overrideUserStories; boolean reversed; TL_stories.StoryItem singleStory; private int messageId; private boolean animateAvatar; private int fromRadius; private static boolean runOpenAnimationAfterLayout; private boolean isPopupVisible; private boolean isBulletinVisible; public boolean isTranslating = false; public static float currentSpeed = 1f; public boolean isLongpressed; Runnable longPressRunnable = () -> setLongPressed(true); public boolean unreadStateChanged; private StoriesVolumeControl volumeControl; private static boolean checkSilentMode = true; private static boolean isInSilentMode; public LongSparseIntArray savedPositions = new LongSparseIntArray(); private boolean isInPinchToZoom; private boolean flingCalled; private boolean invalidateOutRect; private boolean isHintVisible; private boolean isInTextSelectionMode; private boolean isOverlayVisible; Bitmap playerStubBitmap; public Paint playerStubPaint; private boolean isSwiping; private boolean isCaptionPartVisible; private Runnable delayedTapRunnable; private Runnable onCloseListener; private boolean isLikesReactions; private float lastStoryContainerHeight; private static final LongSparseArray<CharSequence> replyDrafts = new LongSparseArray<>(); public boolean fromBottomSheet; private boolean paused; private long playerSavedPosition; private StoriesIntro storiesIntro; public static boolean isShowingImage(MessageObject messageObject) { if (lastStoryItem == null || messageObject.type != MessageObject.TYPE_STORY && !messageObject.isWebpage() || runOpenAnimationAfterLayout) { return false; } return lastStoryItem.messageId == messageObject.getId() && lastStoryItem.messageType != 3; } public static void closeGlobalInstances() { for (int i = 0; i < globalInstances.size(); i++) { globalInstances.get(i).close(false); } globalInstances.clear(); } private void setLongPressed(boolean b) { if (isLongpressed != b) { isLongpressed = b; if (b && !isInPinchToZoom) { PeerStoriesView peerView = storiesViewPager.getCurrentPeerView(); if (peerView != null && peerView.currentStory != null && peerView.currentStory.uploadingStory == null) { if (!inSeekingMode && !inSwipeToDissmissMode && currentPlayerScope != null && currentPlayerScope.player != null) { peerView.storyContainer.invalidate(); BotWebViewVibrationEffect.IMPACT_LIGHT.vibrate(); } if (currentPlayerScope != null && currentPlayerScope.player != null && !inSeekingMode) { currentPlayerScope.player.setSeeking(true); } inSeekingMode = true; } } updatePlayingMode(); if (storiesViewPager != null) { PeerStoriesView peerStoriesView = storiesViewPager.getCurrentPeerView(); if (peerStoriesView != null) { peerStoriesView.setLongpressed(isLongpressed); } } } } public StoryViewer(BaseFragment fragment) { inputBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG); this.fragment = fragment; } public void setSpeed(float speed) { currentSpeed = speed; if (playerHolder != null) { playerHolder.setSpeed(speed); // TODO: storyViewerStack // StoryViewer otherStoryViewer = null; // if (fragment != null) { // if (fragment.overlayStoryViewer != this) { // otherStoryViewer = fragment.overlayStoryViewer; // } else if (fragment.storyViewer != this) { // otherStoryViewer = fragment.storyViewer; // } // } // if (otherStoryViewer != null && otherStoryViewer.playerHolder != null) { // otherStoryViewer.playerHolder.setSpeed(speed); // } } } public void open(Context context, TL_stories.StoryItem storyItem, PlaceProvider placeProvider) { if (storyItem == null) { return; } currentAccount = UserConfig.selectedAccount; if (storyItem.dialogId > 0 && MessagesController.getInstance(currentAccount).getUser(storyItem.dialogId) == null) { return; } if (storyItem.dialogId < 0 && MessagesController.getInstance(currentAccount).getChat(-storyItem.dialogId) == null) { return; } ArrayList<Long> peerIds = new ArrayList<>(); peerIds.add(storyItem.dialogId); open(context, storyItem, peerIds, 0, null, null, placeProvider, false); } public void open(Context context, long dialogId, PlaceProvider placeProvider) { currentAccount = UserConfig.selectedAccount; int position = 0; ArrayList<Long> peerIds = new ArrayList<>(); peerIds.add(dialogId); MessagesController.getInstance(currentAccount).getStoriesController().checkExpiredStories(dialogId); open(context, null, peerIds, position, null, null, placeProvider, false); } public void open(Context context, int startStoryId, StoriesController.StoriesList storiesList, PlaceProvider placeProvider) { currentAccount = UserConfig.selectedAccount; ArrayList<Long> peerIds = new ArrayList<>(); peerIds.add(storiesList.dialogId); dayStoryId = startStoryId; open(context, null, peerIds, 0, storiesList, null, placeProvider, false); } public void open(Context context, TL_stories.PeerStories userStories, PlaceProvider placeProvider) { if (userStories == null || userStories.stories == null || userStories.stories.isEmpty()) { doOnAnimationReadyRunnables.clear(); return; } currentAccount = UserConfig.selectedAccount; ArrayList<Long> peerIds = new ArrayList<>(); peerIds.add(DialogObject.getPeerDialogId(userStories.peer)); open(context, userStories.stories.get(0), peerIds, 0, null, userStories, placeProvider, false); } public void open(Context context, TL_stories.StoryItem storyItem, int startStoryId, StoriesController.StoriesList storiesList, boolean reversed, PlaceProvider placeProvider) { currentAccount = UserConfig.selectedAccount; ArrayList<Long> peerIds = new ArrayList<>(); peerIds.add(storiesList.dialogId); dayStoryId = startStoryId; open(context, storyItem, peerIds, 0, storiesList, null, placeProvider, reversed); } @SuppressLint("WrongConstant") public void open(Context context, TL_stories.StoryItem storyItem, ArrayList<Long> peerIds, int position, StoriesController.StoriesList storiesList, TL_stories.PeerStories userStories, PlaceProvider placeProvider, boolean reversed) { if (context == null) { doOnAnimationReadyRunnables.clear(); return; } if (openCloseAnimator != null) { openCloseAnimator.cancel(); openCloseAnimator = null; } if (isShowing) { doOnAnimationReadyRunnables.clear(); return; } setSpeed(1f); ATTACH_TO_FRAGMENT = !AndroidUtilities.isTablet() && !fromBottomSheet; USE_SURFACE_VIEW = SharedConfig.useSurfaceInStories && ATTACH_TO_FRAGMENT; messageId = storyItem == null ? 0 : storyItem.messageId; isSingleStory = storyItem != null && storiesList == null && userStories == null; if (storyItem != null) { singleStory = storyItem; lastStoryItem = storyItem; } this.storiesList = storiesList; overrideUserStories = userStories; this.placeProvider = placeProvider; this.reversed = reversed; currentAccount = UserConfig.selectedAccount; swipeToDismissOffset = 0; swipeToDismissHorizontalOffset = 0; if (storiesViewPager != null) { storiesViewPager.setHorizontalProgressToDismiss(0); storiesViewPager.currentState = ViewPager.SCROLL_STATE_IDLE; } swipeToReplyProgress = 0; swipeToReplyOffset = 0; allowSwipeToReply = false; progressToDismiss = 0; isShowing = true; isLongpressed = false; isTranslating = false; savedPositions.clear(); AndroidUtilities.cancelRunOnUIThread(longPressRunnable); windowLayoutParams = new WindowManager.LayoutParams(); windowLayoutParams.height = WindowManager.LayoutParams.MATCH_PARENT; windowLayoutParams.format = PixelFormat.TRANSLUCENT; windowLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; windowLayoutParams.gravity = Gravity.TOP | Gravity.LEFT; windowLayoutParams.type = WindowManager.LayoutParams.LAST_APPLICATION_WINDOW; windowLayoutParams.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE; if (Build.VERSION.SDK_INT >= 28) { windowLayoutParams.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES; } if (Build.VERSION.SDK_INT >= 21) { windowLayoutParams.flags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR | WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; } isClosed = false; unreadStateChanged = false; BaseFragment fragment = LaunchActivity.getLastFragment(); if (windowView == null) { gestureDetector = new GestureDetector(new GestureDetector.OnGestureListener() { @Override public boolean onDown(@NonNull MotionEvent e) { flingCalled = false; if (findClickableView(windowView, e.getX(), e.getY(), false)) { return false; } return true; } @Override public void onShowPress(@NonNull MotionEvent e) { } @Override public boolean onSingleTapUp(@NonNull MotionEvent e) { if (selfStoriesViewsOffset != 0) { return false; } if (allowIntercept) { if (keyboardVisible || isCaption || isCaptionPartVisible || isHintVisible || isInTextSelectionMode) { closeKeyboardOrEmoji(); } else { switchByTap(e.getX() > containerView.getMeasuredWidth() * 0.33f); } } return false; } @Override public boolean onScroll(@NonNull MotionEvent e1, @NonNull MotionEvent e2, float distanceX, float distanceY) { if (inSwipeToDissmissMode) { if (allowSwipeToReply) { swipeToReplyOffset += distanceY; int maxOffset = AndroidUtilities.dp(200); if (swipeToReplyOffset > maxOffset && !swipeToReplyWaitingKeyboard) { swipeToReplyWaitingKeyboard = true; showKeyboard(); windowView.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP); } swipeToReplyProgress = Utilities.clamp(swipeToReplyOffset / maxOffset, 1f, 0); if (storiesViewPager.getCurrentPeerView() != null) { storiesViewPager.getCurrentPeerView().invalidate(); } if (swipeToReplyOffset < 0) { swipeToReplyOffset = 0; allowSwipeToReply = false; } else { return true; } } if (allowSelfStoriesView) { if (selfStoriesViewsOffset > selfStoryViewsView.maxSelfStoriesViewsOffset && distanceY > 0) { selfStoriesViewsOffset += distanceY * 0.05f; } else { selfStoriesViewsOffset += distanceY; } Bulletin.hideVisible(windowView); if (storiesViewPager.getCurrentPeerView() != null) { storiesViewPager.getCurrentPeerView().invalidate(); } containerView.invalidate(); if (selfStoriesViewsOffset < 0) { selfStoriesViewsOffset = 0; allowSelfStoriesView = false; } else { return true; } } float k = 0.6f; if (progressToDismiss > 0.8f && ((-distanceY > 0 && swipeToDismissOffset > 0) || (-distanceY < 0 && swipeToDismissOffset < 0))) { k = 0.3f; } swipeToDismissOffset -= distanceY * k; Bulletin.hideVisible(windowView); updateProgressToDismiss(); return true; } return false; } @Override public void onLongPress(@NonNull MotionEvent e) { } @Override public boolean onFling(@NonNull MotionEvent e1, @NonNull MotionEvent e2, float velocityX, float velocityY) { if (swipeToReplyOffset != 0 && storiesIntro == null) { if (velocityY < -1000 && !swipeToReplyWaitingKeyboard) { swipeToReplyWaitingKeyboard = true; windowView.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP); showKeyboard(); } } if (selfStoriesViewsOffset != 0) { if (velocityY < -1000) { cancelSwipeToViews(true); } else { if (velocityY > 1000) { cancelSwipeToViews(false); } else { cancelSwipeToViews(selfStoryViewsView.progressToOpen > 0.5f); } } } flingCalled = true; return false; } }); windowView = new SizeNotifierFrameLayout(context) { float startX, startY; float lastTouchX; final Path path = new Path(); final RectF rect1 = new RectF(); final RectF rect2 = new RectF(); final RectF rect3 = new RectF(); final RectF outFromRectAvatar = new RectF(); final RectF outFromRectContainer = new RectF(); @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { if (child == aspectRatioFrameLayout) { return false; } return super.drawChild(canvas, child, drawingTime); } @Override protected void dispatchDraw(Canvas canvas) { float blackoutAlpha = getBlackoutAlpha(); canvas.drawColor(ColorUtils.setAlphaComponent(Color.BLACK, (int) (255 * blackoutAlpha))); if (ATTACH_TO_FRAGMENT) { boolean localFullyVisible = progressToOpen * (1f - progressToDismiss) == 1f; if (fullyVisible != localFullyVisible) { fullyVisible = localFullyVisible; if (fragment.getLayoutContainer() != null) { fragment.getLayoutContainer().invalidate(); } } } PeerStoriesView currentView = storiesViewPager.getCurrentPeerView(); PeerStoriesView.PeerHeaderView headerView = null; if (currentView != null) { headerView = currentView.headerView; if (animateAvatar) { headerView.backupImageView.getImageReceiver().setVisible(progressToOpen == 1f, true); } else { headerView.backupImageView.getImageReceiver().setVisible(true, false); } if (invalidateOutRect) { invalidateOutRect = false; View child = headerView.backupImageView; float toX = 0, toY = 0; while (child != this) { if (child.getParent() == this) { toX += child.getLeft(); toY += child.getTop(); } else if (child.getParent() != storiesViewPager) { toX += child.getX(); toY += child.getY(); } child = (View) child.getParent(); } outFromRectAvatar.set(toX, toY, toX + headerView.backupImageView.getMeasuredWidth(), toY + headerView.backupImageView.getMeasuredHeight()); outFromRectContainer.set(0, currentView.getTop() + currentView.storyContainer.getTop(), containerView.getMeasuredWidth(), containerView.getMeasuredHeight()); containerView.getMatrix().mapRect(outFromRectAvatar); containerView.getMatrix().mapRect(outFromRectContainer); //outFromRectContainer.offset(containerView.getX(), containerView.getY()); // outFromRect.offset(-containerView.getTranslationX(), -containerView.getTranslationY()); } } volumeControl.setAlpha(1f - progressToDismiss); float dismissScaleProgress = 1f; if (swipeToDismissHorizontalOffset == 0) { dismissScaleProgress = 1f - Utilities.clamp(Math.abs(swipeToDismissOffset / getMeasuredHeight()), 1f, 0); } storiesViewPager.setHorizontalProgressToDismiss((swipeToDismissHorizontalOffset / (float) containerView.getMeasuredWidth()) * progressToOpen); if ((fromX == 0 && fromY == 0) || progressToOpen == 1f) { containerView.setAlpha(progressToOpen); float scale = 0.75f + 0.1f * progressToOpen + 0.15f * dismissScaleProgress; containerView.setScaleX(scale); containerView.setScaleY(scale); containerView.setTranslationY(swipeToDismissOffset); containerView.setTranslationX(swipeToDismissHorizontalOffset); super.dispatchDraw(canvas); } else { float progress2 = progressToOpen; float progressToCircle = progressToOpen; if (isClosed && animateAvatar) { // progress2 = 1f - Utilities.clamp((1f - progressToOpen) / 0.8f, 1f, 0); progress2 = progressToOpen; progressToCircle = progressToOpen;//(float) Math.pow(progressToOpen, 1.4f);//progressToOpen;//1f - Utilities.clamp((1f - progressToOpen) / 0.85f, 1f, 0); float startAlpha = 0.8f; float endAlpha = startAlpha + 0.1f; float alpha = 1f - Utilities.clamp(((1f - progressToOpen) - startAlpha) / (endAlpha - startAlpha), 1f, 0f); progressToCircle = Utilities.clamp(progressToCircle - 0.05f * (1f - alpha), 1f, 0); containerView.setAlpha(alpha); } else { containerView.setAlpha(1f); } if (isClosed && transitionViewHolder != null && transitionViewHolder.storyImage != null) { containerView.setAlpha(containerView.getAlpha() * (float) Math.pow(progress2, .2f)); } else if (isClosed) { // containerView.setAlpha(Utilities.clamp(progressToOpen / 0.7f, 1f, 0)); } containerView.setTranslationX((fromX - containerView.getLeft() - containerView.getMeasuredWidth() / 2f) * (1f - progressToOpen) + swipeToDismissHorizontalOffset * progressToOpen); containerView.setTranslationY((fromY - containerView.getTop() - containerView.getMeasuredHeight() / 2f) * (1f - progressToOpen) + swipeToDismissOffset * progressToOpen); float s1 = 0.85f + 0.15f * dismissScaleProgress; float scale = AndroidUtilities.lerp(fromWidth / (float) containerView.getMeasuredWidth(), s1, progressToCircle); containerView.setScaleX(scale); containerView.setScaleY(scale); path.rewind(); rect1.set( fromX - fromWidth / 2f, fromY - fromHeight / 2f, fromX + fromWidth / 2f, fromY + fromHeight / 2f ); if (isClosed && animateAvatar) { rect2.set(outFromRectContainer); } else if (currentView != null) { rect2.set(0, currentView.storyContainer.getTop() + fromDismissOffset, getMeasuredWidth(), getMeasuredHeight() + fromDismissOffset); } else { rect2.set(0, 0, getMeasuredWidth(), getMeasuredHeight()); } if (isClosed && animateAvatar) { rect1.inset(AndroidUtilities.dp(12), AndroidUtilities.dp(12)); } float cx = AndroidUtilities.lerp(rect1.centerX(), rect2.centerX(), progressToOpen); float cy = AndroidUtilities.lerp(rect1.centerY(), rect2.centerY(), progressToOpen); float rectHeight = AndroidUtilities.lerp(rect1.height(), rect2.height(), progressToCircle); float rectWidth = AndroidUtilities.lerp(rect1.width(), rect2.width(), progressToCircle); if (isClosed && animateAvatar) { rect1.inset(-AndroidUtilities.dp(12), -AndroidUtilities.dp(12)); } AndroidUtilities.rectTmp.set(cx - rectWidth / 2f, cy - rectHeight / 2f, cx + rectWidth / 2f, cy + rectHeight / 2f); float rad; if (animateAvatar) { rad = AndroidUtilities.lerp(fromWidth / 2f, 0, progressToCircle); } else { rad = AndroidUtilities.lerp((float) fromRadius, 0, progress2); } path.addRoundRect( AndroidUtilities.rectTmp, rad, rad, Path.Direction.CCW ); canvas.save(); if (clipTop != 0 && clipBottom != 0) { canvas.clipRect( 0, AndroidUtilities.lerp(0, clipTop, (float) Math.pow(1f - progressToOpen, .4f)), getMeasuredWidth(), AndroidUtilities.lerp(getMeasuredHeight(), clipBottom, (1f - progressToOpen)) ); } canvas.save(); canvas.clipPath(path); super.dispatchDraw(canvas); if (transitionViewHolder != null && transitionViewHolder.storyImage != null) { PeerStoriesView page = storiesViewPager.getCurrentPeerView(); if (page != null && page.storyContainer != null) { boolean wasVisible = transitionViewHolder.storyImage.getVisible(); rect2.set( swipeToDismissHorizontalOffset + containerView.getLeft() + page.getX() + page.storyContainer.getX(), swipeToDismissOffset + containerView.getTop() + page.getY() + page.storyContainer.getY(), swipeToDismissHorizontalOffset + containerView.getRight() - (containerView.getWidth() - page.getRight()) - (page.getWidth() - page.storyContainer.getRight()), swipeToDismissOffset + containerView.getBottom() - (containerView.getHeight() - page.getBottom()) - (page.getHeight() - page.storyContainer.getBottom()) ); AndroidUtilities.lerp(rect1, rect2, progress2, rect3); float x = transitionViewHolder.storyImage.getImageX(); float y = transitionViewHolder.storyImage.getImageY(); float w = transitionViewHolder.storyImage.getImageWidth(); float h = transitionViewHolder.storyImage.getImageHeight(); transitionViewHolder.storyImage.setImageCoords(rect3); transitionViewHolder.storyImage.setAlpha(1f - progress2); transitionViewHolder.storyImage.setVisible(true, false); int r = canvas.getSaveCount(); if (transitionViewHolder.drawClip != null) { transitionViewHolder.drawClip.clip(canvas, rect3, 1f - progress2, opening); } transitionViewHolder.storyImage.draw(canvas); if (transitionViewHolder.drawAbove != null) { transitionViewHolder.drawAbove.draw(canvas, rect3, 1f - progress2, opening); } transitionViewHolder.storyImage.setVisible(wasVisible, false); transitionViewHolder.storyImage.setImageCoords(x, y, w, h); canvas.restoreToCount(r); } } canvas.restore(); if (headerView != null) { float toX = swipeToDismissHorizontalOffset, toY = swipeToDismissOffset; View child = headerView.backupImageView; if (isClosed && animateAvatar) { rect2.set(outFromRectAvatar); } else { while (child != this) { if (child.getParent() == this) { toX += child.getLeft(); toY += child.getTop(); } else if (child.getParent() != storiesViewPager) { toX += child.getX(); toY += child.getY(); } child = (View) child.getParent(); } rect2.set(toX, toY, toX + headerView.backupImageView.getMeasuredWidth(), toY + headerView.backupImageView.getMeasuredHeight()); } AndroidUtilities.lerp(rect1, rect2, progressToOpen, rect3); int r = canvas.getSaveCount(); if (transitionViewHolder != null && transitionViewHolder.drawClip != null) { transitionViewHolder.drawClip.clip(canvas, rect3, 1f - progress2, opening); } if (animateAvatar) { boolean crossfade = transitionViewHolder != null && transitionViewHolder.crossfadeToAvatarImage != null; if (!crossfade || progressToOpen != 0) { headerView.backupImageView.getImageReceiver().setImageCoords(rect3); Integer cellAvatarImageRadius = transitionViewHolder != null ? transitionViewHolder.getAvatarImageRoundRadius() : null; int newRoundRadius = (int) (AndroidUtilities.lerp(rect3.width() / 2f, cellAvatarImageRadius != null ? cellAvatarImageRadius : rect3.width() / 2f, 1f - progressToOpen)); headerView.backupImageView.getImageReceiver().setRoundRadius(newRoundRadius); headerView.backupImageView.getImageReceiver().setVisible(true, false); final float alpha = crossfade ? progressToOpen : 1f; float thisAlpha = alpha; if (transitionViewHolder != null && transitionViewHolder.alpha < 1 && transitionViewHolder.bgPaint != null) { transitionViewHolder.bgPaint.setAlpha((int) (0xFF * (1f - progress2))); canvas.drawCircle(rect3.centerX(), rect3.centerY(), rect3.width() / 2f, transitionViewHolder.bgPaint); thisAlpha = AndroidUtilities.lerp(transitionViewHolder.alpha, thisAlpha, progress2); } headerView.backupImageView.getImageReceiver().setAlpha(thisAlpha); headerView.drawUploadingProgress(canvas, rect3, !runOpenAnimationAfterLayout, progressToOpen); headerView.backupImageView.getImageReceiver().draw(canvas); headerView.backupImageView.getImageReceiver().setAlpha(alpha); headerView.backupImageView.getImageReceiver().setVisible(false, false); } if (progressToOpen != 1f && crossfade) { avatarRectTmp.set( transitionViewHolder.crossfadeToAvatarImage.getImageX(), transitionViewHolder.crossfadeToAvatarImage.getImageY(), transitionViewHolder.crossfadeToAvatarImage.getImageX2(), transitionViewHolder.crossfadeToAvatarImage.getImageY2() ); int oldRadius = transitionViewHolder.crossfadeToAvatarImage.getRoundRadius()[0]; boolean isVisible = transitionViewHolder.crossfadeToAvatarImage.getVisible(); transitionViewHolder.crossfadeToAvatarImage.setImageCoords(rect3); transitionViewHolder.crossfadeToAvatarImage.setRoundRadius((int) (rect3.width() / 2f)); transitionViewHolder.crossfadeToAvatarImage.setVisible(true, false); canvas.saveLayerAlpha(rect3, (int) (255 * (1f - progressToOpen)), Canvas.ALL_SAVE_FLAG); transitionViewHolder.crossfadeToAvatarImage.draw(canvas); canvas.restore(); transitionViewHolder.crossfadeToAvatarImage.setVisible(isVisible, false); transitionViewHolder.crossfadeToAvatarImage.setImageCoords(avatarRectTmp); transitionViewHolder.crossfadeToAvatarImage.setRoundRadius(oldRadius); // transitionViewHolder.crossfadeToAvatarImage.setVisible(false, false); } if (transitionViewHolder != null && transitionViewHolder.drawAbove != null) { transitionViewHolder.drawAbove.draw(canvas, rect3, 1f - progress2, opening); } } canvas.restoreToCount(r); } if (animateFromCell != null) { float progressHalf = Utilities.clamp(progressToOpen / 0.4f, 1f, 0); if (progressHalf != 1) { AndroidUtilities.rectTmp.set(fromX, fromY, fromX + fromWidth, fromY + fromHeight); AndroidUtilities.rectTmp.inset(-AndroidUtilities.dp(16), -AndroidUtilities.dp(16)); if (progressHalf != 0) { canvas.saveLayerAlpha(AndroidUtilities.rectTmp, (int) (255 * (1f - progressHalf)), Canvas.ALL_SAVE_FLAG); } else { canvas.save(); } canvas.translate(fromXCell, fromYCell); animateFromCell.drawAvatarOverlays(canvas); canvas.restore(); } } canvas.restore(); } if (runOpenAnimationAfterLayout) { startOpenAnimation(); runOpenAnimationAfterLayout = false; } } @Override public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { super.requestDisallowInterceptTouchEvent(disallowIntercept); allowIntercept = false; } SparseArray<Float> lastX = new SparseArray<>(); @Override public boolean dispatchTouchEvent(MotionEvent ev) { boolean swipeToReplyCancelled = false; PeerStoriesView peerStoriesView = storiesViewPager.getCurrentPeerView(); if (peerStoriesView != null && peerStoriesView.checkTextSelectionEvent(ev)) { return true; } if (isLikesReactions) { if (peerStoriesView != null && peerStoriesView.checkReactionEvent(ev)) { return true; } } if (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL) { inSwipeToDissmissMode = false; AndroidUtilities.cancelRunOnUIThread(longPressRunnable); if (swipeToDismissHorizontalOffset != 0) { swipeToDissmissBackAnimator = ValueAnimator.ofFloat(swipeToDismissHorizontalOffset, 0); swipeToDissmissBackAnimator.addUpdateListener(animation -> { swipeToDismissHorizontalOffset = (float) animation.getAnimatedValue(); updateProgressToDismiss(); }); swipeToDissmissBackAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { swipeToDismissHorizontalOffset = 0; updateProgressToDismiss(); } }); swipeToDissmissBackAnimator.setDuration(250); swipeToDissmissBackAnimator.setInterpolator(CubicBezierInterpolator.DEFAULT); swipeToDissmissBackAnimator.start(); } swipeToReplyCancelled = true; if (progressToDismiss >= 0.3f) { close(true); } setInTouchMode(false); setLongPressed(false); } if (ev.getAction() == MotionEvent.ACTION_DOWN) { swipeToReplyWaitingKeyboard = false; if (peerStoriesView != null) { peerStoriesView.onActionDown(ev); } storiesViewPager.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0, 0, 0)); } boolean override = false; boolean enableTouch = !keyboardVisible && !isClosed && !isRecording; if (selfStoriesViewsOffset == 0 && !inSwipeToDissmissMode && storiesViewPager.currentState == ViewPager.SCROLL_STATE_DRAGGING && ev.getAction() == MotionEvent.ACTION_MOVE && enableTouch) { float dx = lastX.get(ev.getPointerId(0), 0f) - ev.getX(0); if (dx != 0 && !storiesViewPager.canScroll(dx) || swipeToDismissHorizontalOffset != 0) { if (swipeToDismissHorizontalOffset == 0) { swipeToDismissHorizontalDirection = -dx; } if (dx < 0 && swipeToDismissHorizontalDirection > 0 || dx > 0 && swipeToDismissHorizontalDirection < 0) { dx *= 0.2f; } swipeToDismissHorizontalOffset -= dx; updateProgressToDismiss(); if (swipeToDismissHorizontalOffset > 0 && swipeToDismissHorizontalDirection < 0 || swipeToDismissHorizontalOffset < 0 && swipeToDismissHorizontalDirection > 0) { swipeToDismissHorizontalOffset = 0; } override = true; } } if (peerStoriesView != null && selfStoriesViewsOffset == 0 && !inSwipeToDissmissMode && !isCaption && !isRecording && storiesViewPager.currentState != ViewPager.SCROLL_STATE_DRAGGING) { AndroidUtilities.getViewPositionInParent(peerStoriesView.storyContainer, this, pointPosition); ev.offsetLocation(-pointPosition[0], -pointPosition[1]); storiesViewPager.getCurrentPeerView().checkPinchToZoom(ev); ev.offsetLocation(pointPosition[0], pointPosition[1]); } if (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL) { lastX.clear(); } else { for (int i = 0; i < ev.getPointerCount(); i++) { lastX.put(ev.getPointerId(i), ev.getX(i)); } } if (override) { return true; } boolean rezult = super.dispatchTouchEvent(ev); if (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL) { if (selfStoriesViewsOffset != 0 && !flingCalled && realKeyboardHeight < AndroidUtilities.dp(20)) { cancelSwipeToViews(selfStoryViewsView.progressToOpen > 0.5f); } PeerStoriesView peerView = getCurrentPeerView(); if (peerView != null) { peerView.cancelTouch(); } } if (swipeToReplyCancelled && !swipeToReplyWaitingKeyboard) { cancelSwipeToReply(); } return rezult || animationInProgress && isInTouchMode; } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN && progressToOpen == 1f) { startX = lastTouchX = ev.getX(); startY = ev.getY(); verticalScrollDetected = false; allowIntercept = !isRecording && !findClickableView(windowView, ev.getX(), ev.getY(), false); allowSwipeToDissmiss = !isRecording && !findClickableView(windowView, ev.getX(), ev.getY(), true); setInTouchMode(allowIntercept && !isCaptionPartVisible); if (allowIntercept && !isRecording && isCaptionPartVisible) { delayedTapRunnable = () -> setInTouchMode(true); AndroidUtilities.runOnUIThread(delayedTapRunnable, 150); } if (allowIntercept && !keyboardVisible && !isRecording && !isInTextSelectionMode) { AndroidUtilities.runOnUIThread(longPressRunnable, 400); } } else if (ev.getAction() == MotionEvent.ACTION_MOVE) { float dy = Math.abs(startY - ev.getY()); float dx = Math.abs(startX - ev.getX()); if (isLongpressed && inSeekingMode && !isInPinchToZoom && !inSwipeToDissmissMode && currentPlayerScope != null && currentPlayerScope.player != null) { PeerStoriesView peerView = storiesViewPager.getCurrentPeerView(); if (peerView != null && peerView.currentStory != null && peerView.currentStory.uploadingStory == null && peerView.currentStory.isVideo()) { long videoDuration = peerView.videoDuration; if (videoDuration <= 0 && peerView.currentStory.storyItem != null && peerView.currentStory.storyItem.media != null && peerView.currentStory.storyItem.media.document != null) { videoDuration = (long) (MessageObject.getDocumentDuration(peerView.currentStory.storyItem.media.document) * 1000L); } if (videoDuration > 0) { final float x = ev.getX(); final float wasSeek = currentPlayerScope.player.currentSeek; final float nowSeek = currentPlayerScope.player.seek((x - lastTouchX) / AndroidUtilities.dp(220), videoDuration); if ((int) (nowSeek * 10) != (int) (wasSeek * 10)) { try { peerView.performHapticFeedback(9, HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING); } catch (Exception ignore) { } } peerView.storyContainer.invalidate(); lastTouchX = x; } } } if (dy > dx && !inSeekingMode && !verticalScrollDetected && dy > AndroidUtilities.touchSlop * 2) { verticalScrollDetected = true; } if (!inSwipeToDissmissMode && !inSeekingMode && !keyboardVisible && allowSwipeToDissmiss) { if (dy > dx && dy > AndroidUtilities.touchSlop * 2) { inSwipeToDissmissMode = true; PeerStoriesView peerView = storiesViewPager.getCurrentPeerView(); if (peerView != null) { peerView.cancelTextSelection(); } boolean viewsAllowed = peerView != null && peerView.viewsAllowed(); allowSwipeToReply = !viewsAllowed && peerView != null && !peerView.isChannel && !peerView.isPremiumBlocked && storiesIntro == null; allowSelfStoriesView = viewsAllowed && !peerView.unsupported && peerView.currentStory.storyItem != null && storiesIntro == null; if (allowSelfStoriesView && keyboardHeight != 0) { allowSelfStoriesView = false; } if (allowSelfStoriesView) { checkSelfStoriesView(); } swipeToReplyOffset = 0; if (delayedTapRunnable != null) { AndroidUtilities.cancelRunOnUIThread(delayedTapRunnable); delayedTapRunnable.run(); delayedTapRunnable = null; } AndroidUtilities.cancelRunOnUIThread(longPressRunnable); } layoutAndFindView(); } } else if (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL) { AndroidUtilities.cancelRunOnUIThread(longPressRunnable); if (delayedTapRunnable != null) { AndroidUtilities.cancelRunOnUIThread(delayedTapRunnable); delayedTapRunnable = null; } setInTouchMode(false); verticalScrollDetected = false; inSeekingMode = false; if (currentPlayerScope != null && currentPlayerScope.player != null) { currentPlayerScope.player.setSeeking(false); } } boolean selfViewsViewVisible = selfStoryViewsView != null && selfStoryViewsView.progressToOpen == 1f; if (!inSwipeToDissmissMode && !selfViewsViewVisible) { gestureDetector.onTouchEvent(ev); } return inSwipeToDissmissMode || super.onInterceptTouchEvent(ev); } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) { inSwipeToDissmissMode = false; setInTouchMode(false); if (progressToDismiss >= 1f) { close(true); } else if (!isClosed) { swipeToDissmissBackAnimator = ValueAnimator.ofFloat(swipeToDismissOffset, 0); swipeToDissmissBackAnimator.addUpdateListener(animation -> { swipeToDismissOffset = (float) animation.getAnimatedValue(); updateProgressToDismiss(); }); swipeToDissmissBackAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { swipeToDismissOffset = 0; swipeToReplyOffset = 0; updateProgressToDismiss(); } }); swipeToDissmissBackAnimator.setDuration(150); swipeToDissmissBackAnimator.setInterpolator(CubicBezierInterpolator.DEFAULT); swipeToDissmissBackAnimator.start(); } } if (inSwipeToDissmissMode || keyboardVisible || swipeToReplyOffset != 0 || (selfStoriesViewsOffset != 0 && (allowIntercept || verticalScrollDetected)) || isInTextSelectionMode) { gestureDetector.onTouchEvent(event); return true; } else { return false; } } @Override public boolean dispatchKeyEventPreIme(KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP || event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) { dispatchVolumeEvent(event); return true; } if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) { onBackPressed(); return true; } return super.dispatchKeyEventPreIme(event); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (ATTACH_TO_FRAGMENT) { AndroidUtilities.requestAdjustResize(fragment.getParentActivity(), fragment.getClassGuid()); } Bulletin.addDelegate(this, new Bulletin.Delegate() { float[] position = new float[2]; @Override public int getBottomOffset(int tag) { PeerStoriesView child = getCurrentPeerView(); if (child == null) { return 0; } AndroidUtilities.getViewPositionInParent(child.storyContainer, windowView, position); return (int) (getMeasuredHeight() - (position[1] + child.storyContainer.getMeasuredHeight())); } }); NotificationCenter.getInstance(currentAccount).addObserver(StoryViewer.this, NotificationCenter.storiesListUpdated); NotificationCenter.getInstance(currentAccount).addObserver(StoryViewer.this, NotificationCenter.storiesUpdated); NotificationCenter.getInstance(currentAccount).addObserver(StoryViewer.this, NotificationCenter.articleClosed); NotificationCenter.getInstance(currentAccount).addObserver(StoryViewer.this, NotificationCenter.openArticle); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); Bulletin.removeDelegate(this); NotificationCenter.getInstance(currentAccount).removeObserver(StoryViewer.this, NotificationCenter.storiesListUpdated); NotificationCenter.getInstance(currentAccount).removeObserver(StoryViewer.this, NotificationCenter.storiesUpdated); NotificationCenter.getInstance(currentAccount).removeObserver(StoryViewer.this, NotificationCenter.articleClosed); NotificationCenter.getInstance(currentAccount).removeObserver(StoryViewer.this, NotificationCenter.openArticle); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { ((LayoutParams) volumeControl.getLayoutParams()).topMargin = AndroidUtilities.statusBarHeight - AndroidUtilities.dp(2); volumeControl.getLayoutParams().height = AndroidUtilities.dp(2); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } }; } if (containerView == null) { containerView = new HwFrameLayout(context) { public int measureKeyboardHeight() { View rootView = getRootView(); getWindowVisibleDisplayFrame(AndroidUtilities.rectTmp2); if (AndroidUtilities.rectTmp2.bottom == 0 && AndroidUtilities.rectTmp2.top == 0) { return 0; } int usableViewHeight = rootView.getHeight() - (AndroidUtilities.rectTmp2.top != 0 ? AndroidUtilities.statusBarHeight : 0) - AndroidUtilities.getViewInset(rootView); return Math.max(0, usableViewHeight - (AndroidUtilities.rectTmp2.bottom - AndroidUtilities.rectTmp2.top)); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int heightWithKeyboard = MeasureSpec.getSize(heightMeasureSpec); if (!ATTACH_TO_FRAGMENT) { setKeyboardHeightFromParent(measureKeyboardHeight()); heightWithKeyboard += realKeyboardHeight; } int width = MeasureSpec.getSize(widthMeasureSpec); int viewPagerHeight; if (heightWithKeyboard > (int) (16f * width / 9f)) { viewPagerHeight = (int) (16f * width / 9f); storiesViewPager.getLayoutParams().width = LayoutParams.MATCH_PARENT; } else { viewPagerHeight = heightWithKeyboard; width = storiesViewPager.getLayoutParams().width = (int) (heightWithKeyboard / 16f * 9f); } aspectRatioFrameLayout.getLayoutParams().height = viewPagerHeight + 1; aspectRatioFrameLayout.getLayoutParams().width = width; FrameLayout.LayoutParams layoutParams = (LayoutParams) aspectRatioFrameLayout.getLayoutParams(); layoutParams.topMargin = AndroidUtilities.statusBarHeight; super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override protected void dispatchDraw(Canvas canvas) { PeerStoriesView peerStoriesView = storiesViewPager.getCurrentPeerView(); float pivotY = 0; if (selfStoryViewsView != null && peerStoriesView != null) { selfStoryViewsView.setOffset(selfStoriesViewsOffset); if (selfStoryViewsView.progressToOpen == 1f) { storiesViewPager.setVisibility(View.INVISIBLE); } else { storiesViewPager.setVisibility(View.VISIBLE); } storiesViewPager.checkPageVisibility(); pivotY = peerStoriesView.getTop() + peerStoriesView.storyContainer.getTop(); float progressHalf = selfStoryViewsView.progressToOpen;//Utilities.clamp((selfStoryViewsView.progressToOpen - 0.8f) / 0.2f, 1f, 0); float fromScale = (getMeasuredHeight() - selfStoriesViewsOffset) / getMeasuredHeight(); if (peerStoriesView.storyContainer.getMeasuredHeight() > 0) { lastStoryContainerHeight = peerStoriesView.storyContainer.getMeasuredHeight(); } float toScale = selfStoryViewsView.toHeight / lastStoryContainerHeight; float s = AndroidUtilities.lerp(1f, toScale, progressHalf); storiesViewPager.setPivotY(pivotY); storiesViewPager.setPivotX(getMeasuredWidth() / 2f); storiesViewPager.setScaleX(s); storiesViewPager.setScaleY(s); peerStoriesView.forceUpdateOffsets = true; if (selfStoriesViewsOffset == 0) { peerStoriesView.setViewsThumbImageReceiver(0, 0, 0, null); } else { peerStoriesView.setViewsThumbImageReceiver(progressHalf, s, pivotY, selfStoryViewsView.getCrossfadeToImage()); } peerStoriesView.invalidate(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { peerStoriesView.outlineProvider.radiusInDp = (int) AndroidUtilities.lerp(10f, 6f / toScale, selfStoryViewsView.progressToOpen); peerStoriesView.storyContainer.invalidateOutline(); } storiesViewPager.setTranslationY((selfStoryViewsView.toY - pivotY) * progressHalf); } if (peerStoriesView != null) { volumeControl.setTranslationY(peerStoriesView.storyContainer.getY() - AndroidUtilities.dp(4)); } super.dispatchDraw(canvas); // canvas.drawRect(0, pivotY, getMeasuredWidth(), pivotY + 1, Theme.DEBUG_RED); } }; storiesViewPager = new HwStoriesViewPager(context, this, resourcesProvider) { @Override public void onStateChanged() { if (storiesViewPager.currentState == ViewPager.SCROLL_STATE_DRAGGING) { AndroidUtilities.cancelRunOnUIThread(longPressRunnable); } } }; storiesViewPager.setDelegate(new PeerStoriesView.Delegate() { @Override public void onPeerSelected(long dialogId, int position) { if (lastPosition != position || lastDialogId != dialogId) { lastDialogId = dialogId; lastPosition = position; } } @Override public void onCloseClick() { close(true); } @Override public void onCloseLongClick() { } @Override public void onEnterViewClick() { } @Override public void shouldSwitchToNext() { PeerStoriesView peerView = storiesViewPager.getCurrentPeerView(); if (!peerView.switchToNext(true)) { if (!storiesViewPager.switchToNext(true)) { close(true); } } } @Override public void switchToNextAndRemoveCurrentPeer() { if (storiesList != null) { if (storiesViewPager.days == null) { return; } ArrayList<ArrayList<Integer>> newDays = new ArrayList<>(storiesViewPager.days); int index = storiesViewPager.getCurrentPeerView() == null ? -1 : newDays.indexOf(storiesViewPager.getCurrentPeerView().getCurrentDay()); if (index >= 0) { newDays.remove(index); } else { close(false); return; } if (!storiesViewPager.switchToNext(true)) { close(false); } else { storiesViewPager.onNextIdle(() -> { storiesViewPager.setDays(storiesList.dialogId, newDays, currentAccount); }); } } else { ArrayList<Long> newPeers = new ArrayList<>(peerIds); int index = newPeers.indexOf(storiesViewPager.getCurrentPeerView().getCurrentPeer()); if (index >= 0) { newPeers.remove(index); } else { close(false); return; } if (!storiesViewPager.switchToNext(true)) { close(false); } else { storiesViewPager.onNextIdle(() -> { storiesViewPager.setPeerIds(newPeers, currentAccount, index); }); } } } @Override public void setHideEnterViewProgress(float v) { if (hideEnterViewProgress != v) { hideEnterViewProgress = v; containerView.invalidate(); } } @Override public void showDialog(Dialog dialog) { StoryViewer.this.showDialog(dialog); } @Override public void updatePeers() { //storiesViewPager.setPeerIds(); } @Override public boolean releasePlayer(Runnable whenReleased) { if (playerHolder != null) { final boolean r = playerHolder.release(whenReleased); playerHolder = null; return r; } else { return false; } } @Override public void requestAdjust(boolean b) { StoryViewer.this.requestAdjust(b); } @Override public void setKeyboardVisible(boolean keyboardVisible) { if (StoryViewer.this.keyboardVisible != keyboardVisible) { StoryViewer.this.keyboardVisible = keyboardVisible; updatePlayingMode(); } } @Override public void setAllowTouchesByViewPager(boolean b) { StoryViewer.this.allowTouchesByViewpager = allowTouchesByViewpager; updatePlayingMode(); } @Override public void requestPlayer(TLRPC.Document document, Uri uri, long t, PeerStoriesView.VideoPlayerSharedScope scope) { if (isClosed || progressToOpen < .9f) { FileLog.d("StoryViewer requestPlayer ignored, because closed: " + isClosed + ", " + progressToOpen); scope.firstFrameRendered = false; scope.player = null; return; } String lastAutority = lastUri == null ? null : lastUri.getAuthority(); String autority = uri == null ? null : uri.getAuthority(); boolean sameUri = Objects.equals(lastAutority, autority); if (!sameUri || playerHolder == null) { lastUri = uri; if (playerHolder != null) { playerHolder.release(null); playerHolder = null; } if (currentPlayerScope != null) { currentPlayerScope.player = null; currentPlayerScope.firstFrameRendered = false; currentPlayerScope.renderView = null; currentPlayerScope.textureView = null; currentPlayerScope.surfaceView = null; currentPlayerScope.invalidate(); currentPlayerScope = null; } if (uri != null) { currentPlayerScope = scope; for (int i = 0; i < preparedPlayers.size(); i++) { if (preparedPlayers.get(i).uri.equals(uri)) { playerHolder = preparedPlayers.remove(i); break; } } if (playerHolder == null) { playerHolder = new VideoPlayerHolder(surfaceView, textureView); playerHolder.document = document; } // if (surfaceView != null) { // AndroidUtilities.removeFromParent(surfaceView); // aspectRatioFrameLayout.addView(surfaceView = new SurfaceView(context)); // } playerHolder.uri = uri; playerHolder.setSpeed(currentSpeed); currentPlayerScope.player = playerHolder; currentPlayerScope.firstFrameRendered = false; currentPlayerScope.renderView = aspectRatioFrameLayout; currentPlayerScope.textureView = textureView; currentPlayerScope.surfaceView = surfaceView; FileStreamLoadOperation.setPriorityForDocument(playerHolder.document, FileLoader.PRIORITY_HIGH); FileLoader.getInstance(currentAccount).changePriority(FileLoader.PRIORITY_HIGH, playerHolder.document, null, null, null, null, null); if (t == 0 && playerSavedPosition != 0) { t = playerSavedPosition; currentPlayerScope.firstFrameRendered = true; } FileLog.d("StoryViewer requestPlayer: currentPlayerScope.player start " + uri); currentPlayerScope.player.start(isPaused(), uri, t, isInSilentMode, currentSpeed); currentPlayerScope.invalidate(); } else { FileLog.d("StoryViewer requestPlayer: url is null (1)"); } } else if (sameUri) { currentPlayerScope = scope; currentPlayerScope.player = playerHolder; playerHolder.setSpeed(currentSpeed); currentPlayerScope.firstFrameRendered = playerHolder.firstFrameRendered; currentPlayerScope.renderView = aspectRatioFrameLayout; currentPlayerScope.textureView = textureView; currentPlayerScope.surfaceView = surfaceView; FileLog.d("StoryViewer requestPlayer: same url"); } if (USE_SURFACE_VIEW) { if (uri == null) { surfaceView.setVisibility(View.INVISIBLE); } else { surfaceView.setVisibility(View.VISIBLE); } } playerSavedPosition = 0; updatePlayingMode(); } @Override public boolean isClosed() { return isClosed; } @Override public float getProgressToDismiss() { return progressToDismiss; } @Override public void setIsRecording(boolean isRecording) { StoryViewer.this.isRecording = isRecording; updatePlayingMode(); } @Override public void setIsWaiting(boolean b) { StoryViewer.this.isWaiting = b; updatePlayingMode(); } @Override public void setIsCaption(boolean b) { StoryViewer.this.isCaption = b; updatePlayingMode(); } @Override public void setIsCaptionPartVisible(boolean b) { StoryViewer.this.isCaptionPartVisible = b; } @Override public void setPopupIsVisible(boolean b) { StoryViewer.this.isPopupVisible = b; updatePlayingMode(); } @Override public void setTranslating(boolean b) { StoryViewer.this.isTranslating = b; updatePlayingMode(); } @Override public void setBulletinIsVisible(boolean b) { StoryViewer.this.isBulletinVisible = b; updatePlayingMode(); } @Override public void setIsInPinchToZoom(boolean b) { if (!StoryViewer.this.isInPinchToZoom && b && StoryViewer.this.inSeekingMode) { StoryViewer.this.inSeekingMode = false; if (currentPlayerScope != null && currentPlayerScope.player != null) { currentPlayerScope.player.setSeeking(false); } PeerStoriesView peerView = getCurrentPeerView(); if (peerView != null) { peerView.invalidate(); } } StoryViewer.this.isInPinchToZoom = b; updatePlayingMode(); } @Override public void setIsHintVisible(boolean visible) { StoryViewer.this.isHintVisible = visible; updatePlayingMode(); } @Override public void setIsSwiping(boolean swiping) { StoryViewer.this.isSwiping = swiping; updatePlayingMode(); } @Override public void setIsInSelectionMode(boolean selectionMode) { StoryViewer.this.isInTextSelectionMode = selectionMode; updatePlayingMode(); } @Override public void setIsLikesReaction(boolean show) { StoryViewer.this.isLikesReactions = show; updatePlayingMode(); } @Override public int getKeyboardHeight() { return realKeyboardHeight; } @Override public void preparePlayer(ArrayList<TLRPC.Document> documents, ArrayList<Uri> uries) { if (!SharedConfig.deviceIsHigh() || !SharedConfig.allowPreparingHevcPlayers()) { return; } if (isClosed) { return; } for (int i = 0; i < preparedPlayers.size(); i++) { boolean found = false; for (int j = 0; j < uries.size(); j++) { if (uries.get(j).equals(preparedPlayers.get(i).uri)) { found = true; uries.remove(j); } } } for (int i = 0; i < uries.size(); i++) { Uri uri = uries.get(i); VideoPlayerHolder playerHolder = new VideoPlayerHolder(surfaceView, textureView); playerHolder.setOnSeekUpdate(() -> { PeerStoriesView currentPeerView = storiesViewPager.getCurrentPeerView(); if (currentPeerView != null && currentPeerView.storyContainer != null && currentPlayerScope != null && currentPlayerScope.player == playerHolder) { currentPeerView.storyContainer.invalidate(); } }); playerHolder.uri = uri; playerHolder.document = documents.get(i); FileStreamLoadOperation.setPriorityForDocument(playerHolder.document, FileLoader.PRIORITY_LOW); playerHolder.preparePlayer(uri, isInSilentMode, currentSpeed); preparedPlayers.add(playerHolder); if (preparedPlayers.size() > 2) { VideoPlayerHolder player = preparedPlayers.remove(0); player.release(null); } } } }); containerView.addView(storiesViewPager, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER_HORIZONTAL)); aspectRatioFrameLayout = new AspectRatioFrameLayout(context); if (USE_SURFACE_VIEW) { surfaceView = new SurfaceView(context); surfaceView.setZOrderMediaOverlay(false); surfaceView.setZOrderOnTop(false); //surfaceView.setZOrderMediaOverlay(true); aspectRatioFrameLayout.addView(surfaceView); } else { textureView = new HwTextureView(context) { @Override public void invalidate() { super.invalidate(); if (currentPlayerScope != null) { currentPlayerScope.invalidate(); } } }; aspectRatioFrameLayout.addView(textureView); } volumeControl = new StoriesVolumeControl(context); containerView.addView(volumeControl, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, 0, 4, 0, 4, 0)); } AndroidUtilities.removeFromParent(aspectRatioFrameLayout); windowView.addView(aspectRatioFrameLayout); if (surfaceView != null) { surfaceView.setVisibility(View.INVISIBLE); } AndroidUtilities.removeFromParent(containerView); windowView.addView(containerView); windowView.setClipChildren(false); if (ATTACH_TO_FRAGMENT) { if (fragment.getParentActivity() instanceof LaunchActivity) { LaunchActivity activity = (LaunchActivity) fragment.getParentActivity(); activity.requestCustomNavigationBar(); } } if (isSingleStory) { updateTransitionParams(); } if (storiesList != null) { storiesViewPager.setDays(storiesList.dialogId, storiesList.getDays(), currentAccount); } else { storiesViewPager.setPeerIds(peerIds, currentAccount, position); } windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); if (fragment == null || fragment.getLayoutContainer() == null) { ATTACH_TO_FRAGMENT = false; } if (ATTACH_TO_FRAGMENT) { AndroidUtilities.removeFromParent(windowView); windowView.setFitsSystemWindows(true); fragment.getLayoutContainer().addView(windowView); AndroidUtilities.requestAdjustResize(fragment.getParentActivity(), fragment.getClassGuid()); } else { windowView.setFocusable(false); containerView.setFocusable(false); if (Build.VERSION.SDK_INT >= 21) { windowView.setFitsSystemWindows(true); containerView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() { @NonNull @Override public WindowInsets onApplyWindowInsets(@NonNull View v, @NonNull WindowInsets insets) { ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) containerView.getLayoutParams(); layoutParams.topMargin = insets.getSystemWindowInsetTop(); layoutParams.bottomMargin = insets.getSystemWindowInsetBottom(); layoutParams.leftMargin = insets.getSystemWindowInsetLeft(); layoutParams.rightMargin = insets.getSystemWindowInsetRight(); windowView.requestLayout(); containerView.requestLayout(); if (Build.VERSION.SDK_INT >= 30) { return WindowInsets.CONSUMED; } else { return insets.consumeSystemWindowInsets(); } } }); containerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION); } windowManager.addView(windowView, windowLayoutParams); } windowView.requestLayout(); runOpenAnimationAfterLayout = true; updateTransitionParams(); progressToOpen = 0f; checkNavBarColor(); animationInProgress = true; checkInSilentMode(); if (ATTACH_TO_FRAGMENT) { lockOrientation(true); } if (!ATTACH_TO_FRAGMENT) { globalInstances.add(this); } AndroidUtilities.hideKeyboard(fragment.getFragmentView()); } static int J = 0; int j = J++; private void showKeyboard() { PeerStoriesView currentPeerView = storiesViewPager.getCurrentPeerView(); if (currentPeerView != null) { if (currentPeerView.showKeyboard()) { AndroidUtilities.runOnUIThread(this::cancelSwipeToReply, 200); return; } } cancelSwipeToReply(); } ValueAnimator swipeToViewsAnimator; public void cancelSwipeToViews(boolean open) { if (swipeToViewsAnimator != null) { return; } if (realKeyboardHeight != 0) { AndroidUtilities.hideKeyboard(selfStoryViewsView); return; } if (allowSelfStoriesView || selfStoriesViewsOffset != 0) { locker.lock(); if (!open && selfStoriesViewsOffset == selfStoryViewsView.maxSelfStoriesViewsOffset) { selfStoriesViewsOffset = selfStoryViewsView.maxSelfStoriesViewsOffset - 1; selfStoryViewsView.setOffset(selfStoryViewsView.maxSelfStoriesViewsOffset - 1); } swipeToViewsAnimator = ValueAnimator.ofFloat(selfStoriesViewsOffset, open ? selfStoryViewsView.maxSelfStoriesViewsOffset : 0); swipeToViewsAnimator.addUpdateListener(animation -> { selfStoriesViewsOffset = (float) animation.getAnimatedValue(); // final PeerStoriesView peerStoriesView = storiesViewPager.getCurrentPeerView(); // if (peerStoriesView != null) { // peerStoriesView.invalidate(); // } containerView.invalidate(); }); swipeToViewsAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { locker.unlock(); selfStoriesViewsOffset = open ? selfStoryViewsView.maxSelfStoriesViewsOffset : 0; final PeerStoriesView peerStoriesView = storiesViewPager.getCurrentPeerView(); if (peerStoriesView != null) { peerStoriesView.invalidate(); } containerView.invalidate(); swipeToViewsAnimator = null; } }); if (open) { swipeToViewsAnimator.setDuration(350); swipeToViewsAnimator.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); } else { swipeToViewsAnimator.setDuration(350); swipeToViewsAnimator.setInterpolator(CubicBezierInterpolator.DEFAULT); } swipeToViewsAnimator.start(); } } public void checkSelfStoriesView() { if (selfStoryViewsView == null) { selfStoryViewsView = new SelfStoryViewsView(containerView.getContext(), this); containerView.addView(selfStoryViewsView, 0); } PeerStoriesView peerStoriesView = storiesViewPager.getCurrentPeerView(); if (peerStoriesView != null) { if (storiesList != null) { ArrayList<TL_stories.StoryItem> storyItems = new ArrayList<>(); for (int i = 0; i < storiesList.messageObjects.size(); i++) { storyItems.add(storiesList.messageObjects.get(i).storyItem); } selfStoryViewsView.setItems(storiesList.dialogId, storyItems, peerStoriesView.getListPosition()); } else { selfStoryViewsView.setItems(peerStoriesView.getCurrentPeer(), peerStoriesView.getStoryItems(), peerStoriesView.getSelectedPosition()); } } } public void showDialog(Dialog dialog) { try { currentDialog = dialog; dialog.setOnDismissListener(dialog1 -> { if (dialog1 == currentDialog) { currentDialog = null; updatePlayingMode(); } }); dialog.show(); updatePlayingMode(); } catch (Throwable e) { FileLog.e(e); currentDialog = null; } } public void cancelSwipeToReply() { if (swipeToReplyBackAnimator == null) { inSwipeToDissmissMode = false; allowSwipeToReply = false; swipeToReplyBackAnimator = ValueAnimator.ofFloat(swipeToReplyOffset, 0); swipeToReplyBackAnimator.addUpdateListener(animation -> { swipeToReplyOffset = (float) animation.getAnimatedValue(); int maxOffset = AndroidUtilities.dp(200); swipeToReplyProgress = Utilities.clamp(swipeToReplyOffset / maxOffset, 1f, 0); PeerStoriesView peerView = storiesViewPager == null ? null : storiesViewPager.getCurrentPeerView(); if (peerView != null) { peerView.invalidate(); } }); swipeToReplyBackAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { swipeToReplyBackAnimator = null; swipeToReplyOffset = 0; swipeToReplyProgress = 0; PeerStoriesView peerView = storiesViewPager == null ? null : storiesViewPager.getCurrentPeerView(); if (peerView != null) { peerView.invalidate(); } } }); swipeToReplyBackAnimator.setDuration(AdjustPanLayoutHelper.keyboardDuration); swipeToReplyBackAnimator.setInterpolator(AdjustPanLayoutHelper.keyboardInterpolator); swipeToReplyBackAnimator.start(); } } public boolean getStoryRect(RectF rectF) { if (storiesViewPager == null) { return false; } PeerStoriesView page = storiesViewPager.getCurrentPeerView(); if (page == null || page.storyContainer == null) { return false; } float x = windowView == null ? 0 : windowView.getX(); float y = windowView == null ? 0 : windowView.getY(); rectF.set( x + swipeToDismissHorizontalOffset + containerView.getLeft() + page.getX() + page.storyContainer.getX(), y + swipeToDismissOffset + containerView.getTop() + page.getY() + page.storyContainer.getY(), x + swipeToDismissHorizontalOffset + containerView.getRight() - (containerView.getWidth() - page.getRight()) - (page.getWidth() - page.storyContainer.getRight()), y + swipeToDismissOffset + containerView.getBottom() - (containerView.getHeight() - page.getBottom()) - (page.getHeight() - page.storyContainer.getBottom()) ); return true; } public void switchByTap(boolean forward) { PeerStoriesView peerView = storiesViewPager.getCurrentPeerView(); if (peerView == null) { return; } if (!peerView.switchToNext(forward)) { if (!storiesViewPager.switchToNext(forward)) { if (forward) { close(true); } else { if (playerHolder != null) { playerHolder.loopBack(); } } } else { storiesViewPager.lockTouchEvent(150); } } } @Nullable public PeerStoriesView getCurrentPeerView() { if (storiesViewPager == null) { return null; } return storiesViewPager.getCurrentPeerView(); } private void lockOrientation(boolean lock) { Activity activity = AndroidUtilities.findActivity(fragment.getContext()); if (activity != null) { try { activity.setRequestedOrientation(lock ? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); } catch (Exception ignore) {} if (lock) { activity.getWindow().addFlags(FLAG_KEEP_SCREEN_ON); } else { activity.getWindow().clearFlags(FLAG_KEEP_SCREEN_ON); } } } private void dispatchVolumeEvent(KeyEvent event) { if (isInSilentMode) { toggleSilentMode(); return; } PeerStoriesView peerStoriesView = storiesViewPager.getCurrentPeerView(); if (peerStoriesView != null && !peerStoriesView.currentStory.hasSound() && peerStoriesView.currentStory.isVideo()) { peerStoriesView.showNoSoundHint(true); return; } volumeControl.onKeyDown(event.getKeyCode(), event); } public void toggleSilentMode() { isInSilentMode = !isInSilentMode; if (playerHolder != null) { playerHolder.setAudioEnabled(!isInSilentMode, false); } for (int i = 0; i < preparedPlayers.size(); i++) { preparedPlayers.get(i).setAudioEnabled(!isInSilentMode, true); } final PeerStoriesView peerStoriesView = storiesViewPager.getCurrentPeerView(); if (peerStoriesView != null) { peerStoriesView.sharedResources.setIconMuted(!soundEnabled(), true); } if (!isInSilentMode) { volumeControl.unmute(); } } private void checkInSilentMode() { if (checkSilentMode) { checkSilentMode = false; AudioManager am = (AudioManager) windowView.getContext().getSystemService(Context.AUDIO_SERVICE); isInSilentMode = am.getRingerMode() != AudioManager.RINGER_MODE_NORMAL; } } private void layoutAndFindView() { foundViewToClose = true; if (transitionViewHolder.avatarImage != null) { transitionViewHolder.avatarImage.setVisible(true, true); } if (transitionViewHolder.storyImage != null) { transitionViewHolder.storyImage.setAlpha(1f); transitionViewHolder.storyImage.setVisible(true, true); } if (storiesList != null) { final PeerStoriesView peerView = storiesViewPager.getCurrentPeerView(); if (peerView != null) { int position = peerView.getSelectedPosition(); if (position >= 0 && position < storiesList.messageObjects.size()) { messageId = storiesList.messageObjects.get(position).getId(); } } } if (placeProvider != null) { placeProvider.preLayout(storiesViewPager.getCurrentDialogId(), messageId, () -> { updateTransitionParams(); if (transitionViewHolder.avatarImage != null) { transitionViewHolder.avatarImage.setVisible(false, true); } if (transitionViewHolder.storyImage != null) { transitionViewHolder.storyImage.setVisible(false, true); } }); } } private void updateTransitionParams() { if (placeProvider != null) { if (transitionViewHolder.avatarImage != null) { transitionViewHolder.avatarImage.setVisible(true, true); } if (transitionViewHolder.storyImage != null) { transitionViewHolder.storyImage.setAlpha(1f); transitionViewHolder.storyImage.setVisible(true, true); } final PeerStoriesView peerView = storiesViewPager.getCurrentPeerView(); int position = peerView == null ? 0 : peerView.getSelectedPosition(); int storyId = peerView == null || position < 0 || position >= peerView.storyItems.size() ? 0 : peerView.storyItems.get(position).id; TL_stories.StoryItem storyItem = peerView == null || position < 0 || position >= peerView.storyItems.size() ? null : peerView.storyItems.get(position); if (storyItem == null && isSingleStory) { storyItem = singleStory; } if (storiesList != null) { storyId = dayStoryId; } transitionViewHolder.clear(); if (placeProvider.findView(storiesViewPager.getCurrentDialogId(), messageId, storyId, storyItem == null ? -1 : storyItem.messageType, transitionViewHolder)) { transitionViewHolder.storyId = storyId; if (transitionViewHolder.view != null) { int[] loc = new int[2]; transitionViewHolder.view.getLocationOnScreen(loc); fromXCell = loc[0]; fromYCell = loc[1]; if (transitionViewHolder.view instanceof StoriesListPlaceProvider.AvatarOverlaysView) { animateFromCell = (StoriesListPlaceProvider.AvatarOverlaysView) transitionViewHolder.view; } else { animateFromCell = null; } animateAvatar = false; if (transitionViewHolder.avatarImage != null) { fromX = loc[0] + transitionViewHolder.avatarImage.getCenterX(); fromY = loc[1] + transitionViewHolder.avatarImage.getCenterY(); fromWidth = transitionViewHolder.avatarImage.getImageWidth(); fromHeight = transitionViewHolder.avatarImage.getImageHeight(); if (transitionViewHolder.params != null) { fromWidth *= transitionViewHolder.params.getScale(); fromHeight *= transitionViewHolder.params.getScale(); } if (transitionViewHolder.view.getParent() instanceof View) { View parent = (View) transitionViewHolder.view.getParent(); fromX = loc[0] + transitionViewHolder.avatarImage.getCenterX() * parent.getScaleX(); fromY = loc[1] + transitionViewHolder.avatarImage.getCenterY() * parent.getScaleY(); fromWidth *= parent.getScaleX(); fromHeight *= parent.getScaleY(); } animateAvatar = true; } else if (transitionViewHolder.storyImage != null) { fromX = loc[0] + transitionViewHolder.storyImage.getCenterX(); fromY = loc[1] + transitionViewHolder.storyImage.getCenterY(); fromWidth = transitionViewHolder.storyImage.getImageWidth(); fromHeight = transitionViewHolder.storyImage.getImageHeight(); fromRadius = transitionViewHolder.storyImage.getRoundRadius()[0]; } transitionViewHolder.clipParent.getLocationOnScreen(loc); if (transitionViewHolder.clipTop == 0 && transitionViewHolder.clipBottom == 0) { clipBottom = clipTop = 0; } else { clipTop = loc[1] + transitionViewHolder.clipTop; clipBottom = loc[1] + transitionViewHolder.clipBottom; } } else { animateAvatar = false; fromX = fromY = 0; } } else { animateAvatar = false; fromX = fromY = 0; } } else { animateAvatar = false; fromX = fromY = 0; } } private void requestAdjust(boolean nothing) { if (ATTACH_TO_FRAGMENT) { if (nothing) { AndroidUtilities.requestAdjustNothing(fragment.getParentActivity(), fragment.getClassGuid()); } else { AndroidUtilities.requestAdjustResize(fragment.getParentActivity(), fragment.getClassGuid()); } } else { windowLayoutParams.softInputMode = (nothing ? WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING : WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); try { windowManager.updateViewLayout(windowView, windowLayoutParams); } catch (Exception e) { FileLog.e(e); } } } private void setInTouchMode(boolean b) { isInTouchMode = b; if (isInTouchMode) { volumeControl.hide(); } updatePlayingMode(); } public void setOverlayVisible(boolean visible) { isOverlayVisible = visible; updatePlayingMode(); } public void setOnCloseListener(Runnable listener) { onCloseListener = listener; } public boolean isPaused() { return ( isPopupVisible || isTranslating || isBulletinVisible || isCaption || isWaiting || isInTouchMode || keyboardVisible || currentDialog != null || allowTouchesByViewpager || isClosed || isRecording || progressToOpen != 1f || selfStoriesViewsOffset != 0 || isHintVisible || (isSwiping && USE_SURFACE_VIEW) || isOverlayVisible || isInTextSelectionMode || isLikesReactions || progressToDismiss != 0 || storiesIntro != null || ATTACH_TO_FRAGMENT && fragment != null && fragment.getLastStoryViewer() != this ); } public void updatePlayingMode() { if (storiesViewPager == null) { return; } boolean pause = isPaused(); if (ATTACH_TO_FRAGMENT && (fragment.isPaused() || !fragment.isLastFragment())) { pause = true; } if (ArticleViewer.getInstance().isVisible()) { pause = true; } storiesViewPager.setPaused(pause); if (playerHolder != null) { if (pause) { playerHolder.pause(); } else { playerHolder.play(currentSpeed); } } storiesViewPager.enableTouch(!keyboardVisible && !isClosed && !isRecording && !isLongpressed && !isInPinchToZoom && selfStoriesViewsOffset == 0 && !isInTextSelectionMode); } private boolean findClickableView(FrameLayout windowView, float x, float y, boolean swipeToDissmiss) { if (windowView == null) { return false; } if (isPopupVisible) { return true; } if (selfStoryViewsView != null && selfStoriesViewsOffset != 0) { return true; } final PeerStoriesView currentPeerView = storiesViewPager.getCurrentPeerView(); if (currentPeerView != null) { //fix view pager strange coordinates //just skip page.getX() float x1 = x - containerView.getX() - storiesViewPager.getX() - currentPeerView.getX(); float y1 = y - containerView.getY() - storiesViewPager.getY() - currentPeerView.getY(); if (currentPeerView.findClickableView(currentPeerView, x1, y1, swipeToDissmiss)) { return true; } if (currentPeerView.keyboardVisible) { return false; } } if (swipeToDissmiss) { return false; } if (currentPeerView != null && currentPeerView.chatActivityEnterView != null && currentPeerView.chatActivityEnterView.getVisibility() == View.VISIBLE && y > containerView.getY() + storiesViewPager.getY() + currentPeerView.getY() + currentPeerView.chatActivityEnterView.getY()) { return true; } if (currentPeerView != null && currentPeerView.chatActivityEnterView != null && currentPeerView.chatActivityEnterView.isRecordingAudioVideo()) { return true; } if (storiesIntro != null) { return true; } return AndroidUtilities.findClickableView(windowView, x, y, currentPeerView); } public boolean closeKeyboardOrEmoji() { if (storiesViewPager == null) { return false; } final PeerStoriesView peerStoriesView = storiesViewPager.getCurrentPeerView(); if (peerStoriesView != null) { return peerStoriesView.closeKeyboardOrEmoji(); } return false; } private void updateProgressToDismiss() { float newProgress; if (swipeToDismissHorizontalOffset != 0) { newProgress = MathUtils.clamp(Math.abs(swipeToDismissHorizontalOffset / AndroidUtilities.dp(80)), 0f, 1f); } else { newProgress = MathUtils.clamp(Math.abs(swipeToDismissOffset / AndroidUtilities.dp(80)), 0f, 1f); } if (progressToDismiss != newProgress) { progressToDismiss = newProgress; checkNavBarColor(); final PeerStoriesView peerStoriesView = storiesViewPager.getCurrentPeerView(); if (peerStoriesView != null) { peerStoriesView.progressToDismissUpdated(); } } if (windowView != null) { windowView.invalidate(); } } private boolean showViewsAfterOpening; public void showViewsAfterOpening() { showViewsAfterOpening = true; } private void startOpenAnimation() { updateTransitionParams(); progressToOpen = 0f; setNavigationButtonsColor(true); foundViewToClose = false; animationInProgress = true; fromDismissOffset = swipeToDismissOffset; if (transitionViewHolder.radialProgressUpload != null) { final PeerStoriesView peerStoriesView = getCurrentPeerView(); if (peerStoriesView != null && peerStoriesView.headerView.radialProgress != null) { peerStoriesView.headerView.radialProgress.copyParams(transitionViewHolder.radialProgressUpload); } } opening = true; openCloseAnimator = ValueAnimator.ofFloat(0, 1f); openCloseAnimator.addUpdateListener(animation -> { progressToOpen = (float) animation.getAnimatedValue(); containerView.checkHwAcceleration(progressToOpen); checkNavBarColor(); if (windowView != null) { windowView.invalidate(); } }); locker.lock(); containerView.enableHwAcceleration(); openCloseAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { progressToOpen = 1f; checkNavBarColor(); animationInProgress = false; containerView.disableHwAcceleration(); if (windowView != null) { windowView.invalidate(); } if (transitionViewHolder.avatarImage != null && !foundViewToClose) { transitionViewHolder.avatarImage.setVisible(true, true); transitionViewHolder.avatarImage = null; } if (transitionViewHolder.storyImage != null && !foundViewToClose) { transitionViewHolder.storyImage.setAlpha(1f); transitionViewHolder.storyImage.setVisible(true, true); transitionViewHolder.storyImage = null; } final PeerStoriesView peerStoriesView = getCurrentPeerView(); if (peerStoriesView != null) { peerStoriesView.updatePosition(); } if (showViewsAfterOpening) { showViewsAfterOpening = false; openViews(); } else if (!SharedConfig.storiesIntroShown) { if (storiesIntro == null) { storiesIntro = new StoriesIntro(containerView.getContext(), windowView); storiesIntro.setAlpha(0f); containerView.addView(storiesIntro); } storiesIntro.setOnClickListener(v -> { storiesIntro.animate() .alpha(0f) .setDuration(150L) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); if (storiesIntro != null) { storiesIntro.stopAnimation(); containerView.removeView(storiesIntro); } storiesIntro = null; updatePlayingMode(); } }) .start(); }); storiesIntro.animate() .alpha(1f) .setDuration(150L) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); if (storiesIntro != null) { storiesIntro.startAnimation(true); } } }).start(); SharedConfig.setStoriesIntroShown(true); } updatePlayingMode(); locker.unlock(); } }); openCloseAnimator.setStartDelay(40); openCloseAnimator.setDuration(250); openCloseAnimator.setInterpolator(CubicBezierInterpolator.DEFAULT); openCloseAnimator.start(); if (!doOnAnimationReadyRunnables.isEmpty()) { for (int i = 0; i < doOnAnimationReadyRunnables.size(); i++) { doOnAnimationReadyRunnables.get(i).run(); } doOnAnimationReadyRunnables.clear(); } } public void instantClose() { if (!isShowing) { return; } AndroidUtilities.hideKeyboard(windowView); isClosed = true; fullyVisible = false; progressToOpen = 0; progressToDismiss = 0; updatePlayingMode(); fromX = fromY = 0; if (transitionViewHolder.avatarImage != null) { transitionViewHolder.avatarImage.setVisible(true, true); } if (transitionViewHolder.storyImage != null) { transitionViewHolder.storyImage.setVisible(true, true); } transitionViewHolder.storyImage = null; transitionViewHolder.avatarImage = null; containerView.disableHwAcceleration(); locker.unlock(); if (currentPlayerScope != null) { currentPlayerScope.invalidate(); } release(); if (ATTACH_TO_FRAGMENT) { AndroidUtilities.removeFromParent(windowView); } else { windowManager.removeView(windowView); } windowView = null; isShowing = false; foundViewToClose = false; checkNavBarColor(); if (onCloseListener != null) { onCloseListener.run(); onCloseListener = null; } } private void startCloseAnimation(boolean backAnimation) { setNavigationButtonsColor(false); updateTransitionParams(); locker.lock(); fromDismissOffset = swipeToDismissOffset; opening = false; openCloseAnimator = ValueAnimator.ofFloat(progressToOpen, 0); openCloseAnimator.addUpdateListener(animation -> { progressToOpen = (float) animation.getAnimatedValue(); checkNavBarColor(); if (windowView != null) { windowView.invalidate(); } }); if (!backAnimation) { fromX = fromY = 0; if (transitionViewHolder.avatarImage != null) { transitionViewHolder.avatarImage.setVisible(true, true); } if (transitionViewHolder.storyImage != null) { transitionViewHolder.storyImage.setVisible(true, true); } transitionViewHolder.storyImage = null; transitionViewHolder.avatarImage = null; } else { layoutAndFindView(); } AndroidUtilities.runOnUIThread(() -> { if (openCloseAnimator == null) { return; } containerView.enableHwAcceleration(); openCloseAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); containerView.disableHwAcceleration(); checkNavBarColor(); locker.unlock(); if (storiesIntro != null) { storiesIntro.stopAnimation(); containerView.removeView(storiesIntro); storiesIntro = null; } if (transitionViewHolder.avatarImage != null) { transitionViewHolder.avatarImage.setVisible(true, true); transitionViewHolder.avatarImage = null; } if (transitionViewHolder.storyImage != null) { transitionViewHolder.storyImage.setAlpha(1f); transitionViewHolder.storyImage.setVisible(true, true); } if (transitionViewHolder.radialProgressUpload != null) { final PeerStoriesView peerStoriesView = getCurrentPeerView(); if (peerStoriesView != null && peerStoriesView.headerView.radialProgress != null) { transitionViewHolder.radialProgressUpload.copyParams(peerStoriesView.headerView.radialProgress); } } if (currentPlayerScope != null) { currentPlayerScope.invalidate(); } release(); try { AndroidUtilities.runOnUIThread(() -> { if (windowView == null) { return; } if (ATTACH_TO_FRAGMENT) { AndroidUtilities.removeFromParent(windowView); } else { windowManager.removeView(windowView); } windowView = null; }); } catch (Exception e) { } isShowing = false; foundViewToClose = false; if (onCloseListener != null) { onCloseListener.run(); onCloseListener = null; } } }); openCloseAnimator.setDuration(400); openCloseAnimator.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); // openCloseAnimator.setDuration(2000); // openCloseAnimator.setInterpolator(CubicBezierInterpolator.DEFAULT); openCloseAnimator.start(); }, 16); } public void release() { lastUri = null; setInTouchMode(false); allowScreenshots(true); if (playerHolder != null) { playerHolder.release(null); playerHolder = null; } for (int i = 0; i < preparedPlayers.size(); i++) { preparedPlayers.get(i).release(null); } preparedPlayers.clear(); MessagesController.getInstance(currentAccount).getStoriesController().stopAllPollers(); if (ATTACH_TO_FRAGMENT) { lockOrientation(false); if (fragment != null && fragment.storyViewerStack != null) { fragment.storyViewerStack.remove(this); } } globalInstances.remove(this); doOnAnimationReadyRunnables.clear(); selfStoriesViewsOffset = 0; lastStoryItem = null; } public void close(boolean backAnimation) { AndroidUtilities.hideKeyboard(windowView); isClosed = true; invalidateOutRect = true; updatePlayingMode(); startCloseAnimation(backAnimation); if (unreadStateChanged) { unreadStateChanged = false; //MessagesController.getInstance(currentAccount).getStoriesController().scheduleSort(); } } public int getNavigationBarColor(int currentColor) { return ColorUtils.blendARGB(currentColor, Color.BLACK, getBlackoutAlpha()); } private float getBlackoutAlpha() { return progressToOpen * (0.5f + 0.5f * (1f - progressToDismiss)); } public boolean onBackPressed() { if (selfStoriesViewsOffset != 0) { if (selfStoryViewsView.onBackPressed()) { return true; } cancelSwipeToViews(false); return true; } else if (closeKeyboardOrEmoji()) { return true; } else { close(true); } return true; } public boolean isShown() { return !isClosed; } public void checkNavBarColor() { if (ATTACH_TO_FRAGMENT && LaunchActivity.instance != null) { LaunchActivity.instance.checkSystemBarColors(true, true, true, false); //LaunchActivity.instance.setNavigationBarColor(fragment.getNavigationBarColor(), false); } } /** * Changing the color of buttons in the navigation bar is a difficult task for weak devices. * It's better to change the color before the animation starts. */ private void setNavigationButtonsColor(boolean isOpening) { LaunchActivity activity = LaunchActivity.instance; if (ATTACH_TO_FRAGMENT && activity != null) { if (isOpening) { openedFromLightNavigationBar = activity.isLightNavigationBar(); } if (openedFromLightNavigationBar) { activity.setLightNavigationBar(!isOpening); } } } public boolean attachedToParent() { if (ATTACH_TO_FRAGMENT) { return windowView != null; } return false; } public void setKeyboardHeightFromParent(int keyboardHeight) { if (realKeyboardHeight != keyboardHeight) { realKeyboardHeight = keyboardHeight; storiesViewPager.setKeyboardHeight(keyboardHeight); storiesViewPager.requestLayout(); if (selfStoryViewsView != null) { selfStoryViewsView.setKeyboardHeight(keyboardHeight); } } } public boolean isFullyVisible() { return fullyVisible; } public void presentFragment(BaseFragment fragment) { BaseFragment lastFragment = LaunchActivity.getLastFragment(); if (lastFragment == null) return; if (ATTACH_TO_FRAGMENT) { lastFragment.presentFragment(fragment); } else { lastFragment.presentFragment(fragment); close(false); } } public Theme.ResourcesProvider getResourceProvider() { return resourcesProvider; } public FrameLayout getContainerView() { return containerView; } @Nullable public FrameLayout getContainerForBulletin() { final PeerStoriesView peerStoriesView = storiesViewPager.getCurrentPeerView(); if (peerStoriesView != null) { return peerStoriesView.storyContainer; } return null; } public void startActivityForResult(Intent photoPickerIntent, int code) { if (fragment.getParentActivity() == null) { return; } fragment.getParentActivity().startActivityForResult(photoPickerIntent, code); } public void onActivityResult(int requestCode, int resultCode, Intent data) { PeerStoriesView currentPeerView = storiesViewPager.getCurrentPeerView(); if (currentPeerView != null) { currentPeerView.onActivityResult(requestCode, resultCode, data); } } public void dispatchKeyEvent(KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP || event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) { dispatchVolumeEvent(event); } } public void dismissVisibleDialogs() { if (currentDialog != null) { currentDialog.dismiss(); } PeerStoriesView peerView = getCurrentPeerView(); if (peerView != null) { if (peerView.reactionsContainerLayout != null && peerView.reactionsContainerLayout.getReactionsWindow() != null) { peerView.reactionsContainerLayout.getReactionsWindow().dismiss(); } if (peerView.shareAlert != null) { peerView.shareAlert.dismiss(); } peerView.needEnterText(); } } public float getProgressToSelfViews() { if (selfStoryViewsView == null) { return 0; } return selfStoryViewsView.progressToOpen; } public void setSelfStoriesViewsOffset(float currentTranslation) { selfStoriesViewsOffset = currentTranslation; final PeerStoriesView peerStoriesView = storiesViewPager.getCurrentPeerView(); if (peerStoriesView != null) { peerStoriesView.invalidate(); } containerView.invalidate(); } public void openViews() { checkSelfStoriesView(); AndroidUtilities.runOnUIThread(() -> { allowSelfStoriesView = true; cancelSwipeToViews(true); }, 30); } public boolean soundEnabled() { return !isInSilentMode; } public void allowScreenshots(boolean allowScreenshots) { if (BuildVars.DEBUG_PRIVATE_VERSION) { return; } allowScreenshots = !isShowing || allowScreenshots; if (this.allowScreenshots != allowScreenshots) { this.allowScreenshots = allowScreenshots; if (surfaceView != null) { surfaceView.setSecure(!allowScreenshots); } if (ATTACH_TO_FRAGMENT) { if (fragment.getParentActivity() != null) { if (allowScreenshots) { fragment.getParentActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE); } else { fragment.getParentActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); } } } else { if (allowScreenshots) { windowLayoutParams.flags &= ~WindowManager.LayoutParams.FLAG_SECURE; } else { windowLayoutParams.flags |= WindowManager.LayoutParams.FLAG_SECURE; } try { windowManager.updateViewLayout(windowView, windowLayoutParams); } catch (Exception e) { FileLog.e(e); } } } } public void openFor(BaseFragment fragment, RecyclerListView recyclerListView, ChatActionCell cell) { MessageObject messageObject = cell.getMessageObject(); if (fragment == null || fragment.getContext() == null) { return; } if (messageObject.type == MessageObject.TYPE_STORY_MENTION) { TL_stories.StoryItem storyItem = messageObject.messageOwner.media.storyItem; storyItem.dialogId = DialogObject.getPeerDialogId(messageObject.messageOwner.media.peer); storyItem.messageId = messageObject.getId(); open(fragment.getContext(), messageObject.messageOwner.media.storyItem, StoriesListPlaceProvider.of(recyclerListView)); } } public void doOnAnimationReady(Runnable runnable) { if (runnable != null) { doOnAnimationReadyRunnables.add(runnable); } } @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.storiesListUpdated) { StoriesController.StoriesList list = (StoriesController.StoriesList) args[0]; if (storiesList == list) { PeerStoriesView peerStoriesView = getCurrentPeerView(); storiesViewPager.setDays(storiesList.dialogId, storiesList.getDays(), currentAccount); if (selfStoryViewsView != null) { TL_stories.StoryItem currentSelectedStory = selfStoryViewsView.getSelectedStory(); ArrayList<TL_stories.StoryItem> storyItems = new ArrayList<>(); int selectedPosition = 0; for (int i = 0; i < storiesList.messageObjects.size(); i++) { if (currentSelectedStory != null && currentSelectedStory.id == storiesList.messageObjects.get(i).storyItem.id) { selectedPosition = i; } storyItems.add(storiesList.messageObjects.get(i).storyItem); } selfStoryViewsView.setItems(storiesList.dialogId, storyItems, selectedPosition); } } } else if (id == NotificationCenter.storiesUpdated) { if (placeProvider instanceof StoriesListPlaceProvider) { StoriesListPlaceProvider storiesListPlaceProvider = (StoriesListPlaceProvider) placeProvider; if (!storiesListPlaceProvider.hasPaginationParams || storiesListPlaceProvider.onlySelfStories) { return; } StoriesController storiesController = MessagesController.getInstance(currentAccount).getStoriesController(); ArrayList<TL_stories.PeerStories> allStories = storiesListPlaceProvider.hiddedStories ? storiesController.getHiddenList() : storiesController.getDialogListStories(); boolean changed = false; ArrayList<Long> dialogs = storiesViewPager.getDialogIds(); for (int i = 0; i < allStories.size(); i++) { TL_stories.PeerStories userStories = allStories.get(i); long dialogId = DialogObject.getPeerDialogId(userStories.peer); if (storiesListPlaceProvider.onlyUnreadStories && !storiesController.hasUnreadStories(dialogId)) { continue; } if (!dialogs.contains(dialogId)) { dialogs.add(dialogId); changed = true; } } if (changed) { storiesViewPager.getAdapter().notifyDataSetChanged(); } } if (selfStoryViewsView != null) { selfStoryViewsView.selfStoriesPreviewView.update(); } } else if (id == NotificationCenter.openArticle || id == NotificationCenter.articleClosed) { updatePlayingMode(); if (id == NotificationCenter.openArticle) { if (playerHolder != null) { playerSavedPosition = playerHolder.currentPosition; playerHolder.release(null); playerHolder = null; } else { playerSavedPosition = 0; } } else if (!paused) { PeerStoriesView peerView = getCurrentPeerView(); if (peerView != null) { getCurrentPeerView().updatePosition(); } } } } public void saveDraft(long dialogId, TL_stories.StoryItem storyItem, CharSequence text) { if (dialogId == 0 || storyItem == null) { return; } replyDrafts.put(draftHash(dialogId, storyItem), text); } public CharSequence getDraft(long dialogId, TL_stories.StoryItem storyItem) { if (dialogId == 0 || storyItem == null) { return ""; } return replyDrafts.get(draftHash(dialogId, storyItem), ""); } public void clearDraft(long dialogId, TL_stories.StoryItem storyItem) { if (dialogId == 0 || storyItem == null) { return; } replyDrafts.remove(draftHash(dialogId, storyItem)); } private long draftHash(long dialogId, TL_stories.StoryItem oldStoryItem) { return dialogId + (dialogId >> 16) + ((long) oldStoryItem.id << 16); } public void onResume() { paused = false; if (!ArticleViewer.getInstance().isVisible()) { PeerStoriesView peerView = getCurrentPeerView(); if (peerView != null) { getCurrentPeerView().updatePosition(); } } if (storiesIntro != null) { storiesIntro.startAnimation(false); } } public void onPause() { paused = true; if (playerHolder != null) { playerHolder.release(null); playerHolder = null; } if (storiesIntro != null) { storiesIntro.stopAnimation(); } } public interface PlaceProvider { boolean findView(long dialogId, int messageId, int storyId, int type, TransitionViewHolder holder); default void preLayout(long currentDialogId, int messageId, Runnable o) { o.run(); } default void loadNext(boolean forward) { } } public interface HolderDrawAbove { void draw(Canvas canvas, RectF bounds, float alpha, boolean opening); } public interface HolderClip { void clip(Canvas canvas, RectF bounds, float alpha, boolean opening); } public static class TransitionViewHolder { public View view; public ImageReceiver avatarImage; public ImageReceiver storyImage; public RadialProgress radialProgressUpload; public HolderDrawAbove drawAbove; public HolderClip drawClip; public View clipParent; public float clipTop; public float clipBottom; public Paint bgPaint; public float alpha = 1; public ImageReceiver crossfadeToAvatarImage; public StoriesUtilities.AvatarStoryParams params; public boolean checkParentScale; public int storyId; public Integer getAvatarImageRoundRadius() { if (avatarImage != null) { float scale = 1f; if (checkParentScale && view != null && view.getParent() != null) { scale = ((ViewGroup) (view.getParent())).getScaleY(); } return (int) (avatarImage.getRoundRadius()[0] * scale); } return null; } public void clear() { view = null; params = null; avatarImage = null; storyImage = null; drawAbove = null; drawClip = null; clipParent = null; radialProgressUpload = null; crossfadeToAvatarImage = null; clipTop = 0; clipBottom = 0; storyId = 0; bgPaint = null; alpha = 1; } } public class VideoPlayerHolder extends VideoPlayerHolderBase { boolean logBuffering; public VideoPlayerHolder(SurfaceView surfaceView, TextureView textureView) { if (USE_SURFACE_VIEW) { with(surfaceView); } else { with(textureView); } } @Override public boolean needRepeat() { return isCaptionPartVisible; } @Override public void onRenderedFirstFrame() { if (currentPlayerScope == null) { return; } firstFrameRendered = currentPlayerScope.firstFrameRendered = true; currentPlayerScope.invalidate(); if (paused && surfaceView != null) { prepareStub(); } } @Override public void onStateChanged(boolean playWhenReady, int playbackState) { if (playbackState == ExoPlayer.STATE_READY || playbackState == ExoPlayer.STATE_BUFFERING) { if (firstFrameRendered && playbackState == ExoPlayer.STATE_BUFFERING) { logBuffering = true; AndroidUtilities.runOnUIThread(() -> { final PeerStoriesView storiesView = getCurrentPeerView(); if (storiesView != null && storiesView.currentStory.storyItem != null) { FileLog.d("StoryViewer displayed story buffering dialogId=" + storiesView.getCurrentPeer() + " storyId=" + storiesView.currentStory.storyItem.id); } }); } if (logBuffering && playbackState == ExoPlayer.STATE_READY) { logBuffering = false; AndroidUtilities.runOnUIThread(() -> { final PeerStoriesView storiesView = getCurrentPeerView(); if (storiesView != null && storiesView.currentStory.storyItem != null) { FileLog.d("StoryViewer displayed story playing dialogId=" + storiesView.getCurrentPeer() + " storyId=" + storiesView.currentStory.storyItem.id); } }); } } } } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/ui/Stories/StoryViewer.java
41,699
package com.termux.terminal; import android.util.Base64; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Locale; import java.util.Objects; import java.util.Stack; /** * Renders text into a screen. Contains all the terminal-specific knowledge and state. Emulates a subset of the X Window * System xterm terminal, which in turn is an emulator for a subset of the Digital Equipment Corporation vt100 terminal. * <p> * References: * <ul> * <li>http://invisible-island.net/xterm/ctlseqs/ctlseqs.html</li> * <li>http://en.wikipedia.org/wiki/ANSI_escape_code</li> * <li>http://man.he.net/man4/console_codes</li> * <li>http://bazaar.launchpad.net/~leonerd/libvterm/trunk/view/head:/src/state.c</li> * <li>http://www.columbia.edu/~kermit/k95manual/iso2022.html</li> * <li>http://www.vt100.net/docs/vt510-rm/chapter4</li> * <li>http://en.wikipedia.org/wiki/ISO/IEC_2022 - for 7-bit and 8-bit GL GR explanation</li> * <li>http://bjh21.me.uk/all-escapes/all-escapes.txt - extensive!</li> * <li>http://woldlab.caltech.edu/~diane/kde4.10/workingdir/kubuntu/konsole/doc/developer/old-documents/VT100/techref. * html - document for konsole - accessible!</li> * </ul> */ public final class TerminalEmulator { /** Log unknown or unimplemented escape sequences received from the shell process. */ private static final boolean LOG_ESCAPE_SEQUENCES = false; public static final int MOUSE_LEFT_BUTTON = 0; /** Mouse moving while having left mouse button pressed. */ public static final int MOUSE_LEFT_BUTTON_MOVED = 32; public static final int MOUSE_WHEELUP_BUTTON = 64; public static final int MOUSE_WHEELDOWN_BUTTON = 65; /** Used for invalid data - http://en.wikipedia.org/wiki/Replacement_character#Replacement_character */ public static final int UNICODE_REPLACEMENT_CHAR = 0xFFFD; /** Escape processing: Not currently in an escape sequence. */ private static final int ESC_NONE = 0; /** Escape processing: Have seen an ESC character - proceed to {@link #doEsc(int)} */ private static final int ESC = 1; /** Escape processing: Have seen ESC POUND */ private static final int ESC_POUND = 2; /** Escape processing: Have seen ESC and a character-set-select ( char */ private static final int ESC_SELECT_LEFT_PAREN = 3; /** Escape processing: Have seen ESC and a character-set-select ) char */ private static final int ESC_SELECT_RIGHT_PAREN = 4; /** Escape processing: "ESC [" or CSI (Control Sequence Introducer). */ private static final int ESC_CSI = 6; /** Escape processing: ESC [ ? */ private static final int ESC_CSI_QUESTIONMARK = 7; /** Escape processing: ESC [ $ */ private static final int ESC_CSI_DOLLAR = 8; /** Escape processing: ESC % */ private static final int ESC_PERCENT = 9; /** Escape processing: ESC ] (AKA OSC - Operating System Controls) */ private static final int ESC_OSC = 10; /** Escape processing: ESC ] (AKA OSC - Operating System Controls) ESC */ private static final int ESC_OSC_ESC = 11; /** Escape processing: ESC [ > */ private static final int ESC_CSI_BIGGERTHAN = 12; /** Escape procession: "ESC P" or Device Control String (DCS) */ private static final int ESC_P = 13; /** Escape processing: CSI > */ private static final int ESC_CSI_QUESTIONMARK_ARG_DOLLAR = 14; /** Escape processing: CSI $ARGS ' ' */ private static final int ESC_CSI_ARGS_SPACE = 15; /** Escape processing: CSI $ARGS '*' */ private static final int ESC_CSI_ARGS_ASTERIX = 16; /** Escape processing: CSI " */ private static final int ESC_CSI_DOUBLE_QUOTE = 17; /** Escape processing: CSI ' */ private static final int ESC_CSI_SINGLE_QUOTE = 18; /** Escape processing: CSI ! */ private static final int ESC_CSI_EXCLAMATION = 19; /** The number of parameter arguments. This name comes from the ANSI standard for terminal escape codes. */ private static final int MAX_ESCAPE_PARAMETERS = 16; /** Needs to be large enough to contain reasonable OSC 52 pastes. */ private static final int MAX_OSC_STRING_LENGTH = 8192; /** DECSET 1 - application cursor keys. */ private static final int DECSET_BIT_APPLICATION_CURSOR_KEYS = 1; private static final int DECSET_BIT_REVERSE_VIDEO = 1 << 1; /** * http://www.vt100.net/docs/vt510-rm/DECOM: "When DECOM is set, the home cursor position is at the upper-left * corner of the screen, within the margins. The starting point for line numbers depends on the current top margin * setting. The cursor cannot move outside of the margins. When DECOM is reset, the home cursor position is at the * upper-left corner of the screen. The starting point for line numbers is independent of the margins. The cursor * can move outside of the margins." */ private static final int DECSET_BIT_ORIGIN_MODE = 1 << 2; /** * http://www.vt100.net/docs/vt510-rm/DECAWM: "If the DECAWM function is set, then graphic characters received when * the cursor is at the right border of the page appear at the beginning of the next line. Any text on the page * scrolls up if the cursor is at the end of the scrolling region. If the DECAWM function is reset, then graphic * characters received when the cursor is at the right border of the page replace characters already on the page." */ private static final int DECSET_BIT_AUTOWRAP = 1 << 3; /** DECSET 25 - if the cursor should be enabled, {@link #isCursorEnabled()}. */ private static final int DECSET_BIT_CURSOR_ENABLED = 1 << 4; private static final int DECSET_BIT_APPLICATION_KEYPAD = 1 << 5; /** DECSET 1000 - if to report mouse press&release events. */ private static final int DECSET_BIT_MOUSE_TRACKING_PRESS_RELEASE = 1 << 6; /** DECSET 1002 - like 1000, but report moving mouse while pressed. */ private static final int DECSET_BIT_MOUSE_TRACKING_BUTTON_EVENT = 1 << 7; /** DECSET 1004 - NOT implemented. */ private static final int DECSET_BIT_SEND_FOCUS_EVENTS = 1 << 8; /** DECSET 1006 - SGR-like mouse protocol (the modern sane choice). */ private static final int DECSET_BIT_MOUSE_PROTOCOL_SGR = 1 << 9; /** DECSET 2004 - see {@link #paste(String)} */ private static final int DECSET_BIT_BRACKETED_PASTE_MODE = 1 << 10; /** Toggled with DECLRMM - http://www.vt100.net/docs/vt510-rm/DECLRMM */ private static final int DECSET_BIT_LEFTRIGHT_MARGIN_MODE = 1 << 11; /** Not really DECSET bit... - http://www.vt100.net/docs/vt510-rm/DECSACE */ private static final int DECSET_BIT_RECTANGULAR_CHANGEATTRIBUTE = 1 << 12; private String mTitle; private final Stack<String> mTitleStack = new Stack<>(); /** If processing first character of first parameter of {@link #ESC_CSI}. */ private boolean mIsCSIStart; /** The last character processed of a parameter of {@link #ESC_CSI}. */ private Integer mLastCSIArg; /** The cursor position. Between (0,0) and (mRows-1, mColumns-1). */ private int mCursorRow, mCursorCol; /** The number of character rows and columns in the terminal screen. */ public int mRows, mColumns; /** The number of terminal transcript rows that can be scrolled back to. */ public static final int TERMINAL_TRANSCRIPT_ROWS_MIN = 100; public static final int TERMINAL_TRANSCRIPT_ROWS_MAX = 50000; public static final int DEFAULT_TERMINAL_TRANSCRIPT_ROWS = 2000; /* The supported terminal cursor styles. */ public static final int TERMINAL_CURSOR_STYLE_BLOCK = 0; public static final int TERMINAL_CURSOR_STYLE_UNDERLINE = 1; public static final int TERMINAL_CURSOR_STYLE_BAR = 2; public static final int DEFAULT_TERMINAL_CURSOR_STYLE = TERMINAL_CURSOR_STYLE_BLOCK; public static final Integer[] TERMINAL_CURSOR_STYLES_LIST = new Integer[]{TERMINAL_CURSOR_STYLE_BLOCK, TERMINAL_CURSOR_STYLE_UNDERLINE, TERMINAL_CURSOR_STYLE_BAR}; /** The terminal cursor styles. */ private int mCursorStyle = DEFAULT_TERMINAL_CURSOR_STYLE; /** The normal screen buffer. Stores the characters that appear on the screen of the emulated terminal. */ private final TerminalBuffer mMainBuffer; /** * The alternate screen buffer, exactly as large as the display and contains no additional saved lines (so that when * the alternate screen buffer is active, you cannot scroll back to view saved lines). * <p> * See http://www.xfree86.org/current/ctlseqs.html#The%20Alternate%20Screen%20Buffer */ final TerminalBuffer mAltBuffer; /** The current screen buffer, pointing at either {@link #mMainBuffer} or {@link #mAltBuffer}. */ private TerminalBuffer mScreen; /** The terminal session this emulator is bound to. */ private final TerminalOutput mSession; TerminalSessionClient mClient; /** Keeps track of the current argument of the current escape sequence. Ranges from 0 to MAX_ESCAPE_PARAMETERS-1. */ private int mArgIndex; /** Holds the arguments of the current escape sequence. */ private final int[] mArgs = new int[MAX_ESCAPE_PARAMETERS]; /** Holds OSC and device control arguments, which can be strings. */ private final StringBuilder mOSCOrDeviceControlArgs = new StringBuilder(); /** * True if the current escape sequence should continue, false if the current escape sequence should be terminated. * Used when parsing a single character. */ private boolean mContinueSequence; /** The current state of the escape sequence state machine. One of the ESC_* constants. */ private int mEscapeState; private final SavedScreenState mSavedStateMain = new SavedScreenState(); private final SavedScreenState mSavedStateAlt = new SavedScreenState(); /** http://www.vt100.net/docs/vt102-ug/table5-15.html */ private boolean mUseLineDrawingG0, mUseLineDrawingG1, mUseLineDrawingUsesG0 = true; /** * @see TerminalEmulator#mapDecSetBitToInternalBit(int) */ private int mCurrentDecSetFlags, mSavedDecSetFlags; /** * If insert mode (as opposed to replace mode) is active. In insert mode new characters are inserted, pushing * existing text to the right. Characters moved past the right margin are lost. */ private boolean mInsertMode; /** An array of tab stops. mTabStop[i] is true if there is a tab stop set for column i. */ private boolean[] mTabStop; /** * Top margin of screen for scrolling ranges from 0 to mRows-2. Bottom margin ranges from mTopMargin + 2 to mRows * (Defines the first row after the scrolling region). Left/right margin in [0, mColumns]. */ private int mTopMargin, mBottomMargin, mLeftMargin, mRightMargin; /** * If the next character to be emitted will be automatically wrapped to the next line. Used to disambiguate the case * where the cursor is positioned on the last column (mColumns-1). When standing there, a written character will be * output in the last column, the cursor not moving but this flag will be set. When outputting another character * this will move to the next line. */ private boolean mAboutToAutoWrap; /** * If the cursor blinking is enabled. It requires cursor itself to be enabled, which is controlled * byt whether {@link #DECSET_BIT_CURSOR_ENABLED} bit is set or not. */ private boolean mCursorBlinkingEnabled; /** * If currently cursor should be in a visible state or not if {@link #mCursorBlinkingEnabled} * is {@code true}. */ private boolean mCursorBlinkState; /** * Current foreground and background colors. Can either be a color index in [0,259] or a truecolor (24-bit) value. * For a 24-bit value the top byte (0xff000000) is set. * * @see TextStyle */ int mForeColor, mBackColor; /** Current {@link TextStyle} effect. */ private int mEffect; /** * The number of scrolled lines since last calling {@link #clearScrollCounter()}. Used for moving selection up along * with the scrolling text. */ private int mScrollCounter = 0; /** If automatic scrolling of terminal is disabled */ private boolean mAutoScrollDisabled; private byte mUtf8ToFollow, mUtf8Index; private final byte[] mUtf8InputBuffer = new byte[4]; private int mLastEmittedCodePoint = -1; public final TerminalColors mColors = new TerminalColors(); private static final String LOG_TAG = "TerminalEmulator"; private boolean isDecsetInternalBitSet(int bit) { return (mCurrentDecSetFlags & bit) != 0; } private void setDecsetinternalBit(int internalBit, boolean set) { if (set) { // The mouse modes are mutually exclusive. if (internalBit == DECSET_BIT_MOUSE_TRACKING_PRESS_RELEASE) { setDecsetinternalBit(DECSET_BIT_MOUSE_TRACKING_BUTTON_EVENT, false); } else if (internalBit == DECSET_BIT_MOUSE_TRACKING_BUTTON_EVENT) { setDecsetinternalBit(DECSET_BIT_MOUSE_TRACKING_PRESS_RELEASE, false); } } if (set) { mCurrentDecSetFlags |= internalBit; } else { mCurrentDecSetFlags &= ~internalBit; } } static int mapDecSetBitToInternalBit(int decsetBit) { switch (decsetBit) { case 1: return DECSET_BIT_APPLICATION_CURSOR_KEYS; case 5: return DECSET_BIT_REVERSE_VIDEO; case 6: return DECSET_BIT_ORIGIN_MODE; case 7: return DECSET_BIT_AUTOWRAP; case 25: return DECSET_BIT_CURSOR_ENABLED; case 66: return DECSET_BIT_APPLICATION_KEYPAD; case 69: return DECSET_BIT_LEFTRIGHT_MARGIN_MODE; case 1000: return DECSET_BIT_MOUSE_TRACKING_PRESS_RELEASE; case 1002: return DECSET_BIT_MOUSE_TRACKING_BUTTON_EVENT; case 1004: return DECSET_BIT_SEND_FOCUS_EVENTS; case 1006: return DECSET_BIT_MOUSE_PROTOCOL_SGR; case 2004: return DECSET_BIT_BRACKETED_PASTE_MODE; default: return -1; // throw new IllegalArgumentException("Unsupported decset: " + decsetBit); } } public TerminalEmulator(TerminalOutput session, int columns, int rows, Integer transcriptRows, TerminalSessionClient client) { mSession = session; mScreen = mMainBuffer = new TerminalBuffer(columns, getTerminalTranscriptRows(transcriptRows), rows); mAltBuffer = new TerminalBuffer(columns, rows, rows); mClient = client; mRows = rows; mColumns = columns; mTabStop = new boolean[mColumns]; reset(); } public void updateTerminalSessionClient(TerminalSessionClient client) { mClient = client; setCursorStyle(); setCursorBlinkState(true); } public TerminalBuffer getScreen() { return mScreen; } public boolean isAlternateBufferActive() { return mScreen == mAltBuffer; } private int getTerminalTranscriptRows(Integer transcriptRows) { if (transcriptRows == null || transcriptRows < TERMINAL_TRANSCRIPT_ROWS_MIN || transcriptRows > TERMINAL_TRANSCRIPT_ROWS_MAX) return DEFAULT_TERMINAL_TRANSCRIPT_ROWS; else return transcriptRows; } /** * @param mouseButton one of the MOUSE_* constants of this class. */ public void sendMouseEvent(int mouseButton, int column, int row, boolean pressed) { if (column < 1) column = 1; if (column > mColumns) column = mColumns; if (row < 1) row = 1; if (row > mRows) row = mRows; if (mouseButton == MOUSE_LEFT_BUTTON_MOVED && !isDecsetInternalBitSet(DECSET_BIT_MOUSE_TRACKING_BUTTON_EVENT)) { // Do not send tracking. } else if (isDecsetInternalBitSet(DECSET_BIT_MOUSE_PROTOCOL_SGR)) { mSession.write(String.format("\033[<%d;%d;%d" + (pressed ? 'M' : 'm'), mouseButton, column, row)); } else { mouseButton = pressed ? mouseButton : 3; // 3 for release of all buttons. // Clip to screen, and clip to the limits of 8-bit data. boolean out_of_bounds = column > 255 - 32 || row > 255 - 32; if (!out_of_bounds) { byte[] data = {'\033', '[', 'M', (byte) (32 + mouseButton), (byte) (32 + column), (byte) (32 + row)}; mSession.write(data, 0, data.length); } } } public void resize(int columns, int rows) { if (mRows == rows && mColumns == columns) { return; } else if (columns < 2 || rows < 2) { throw new IllegalArgumentException("rows=" + rows + ", columns=" + columns); } if (mRows != rows) { mRows = rows; mTopMargin = 0; mBottomMargin = mRows; } if (mColumns != columns) { int oldColumns = mColumns; mColumns = columns; boolean[] oldTabStop = mTabStop; mTabStop = new boolean[mColumns]; setDefaultTabStops(); int toTransfer = Math.min(oldColumns, columns); System.arraycopy(oldTabStop, 0, mTabStop, 0, toTransfer); mLeftMargin = 0; mRightMargin = mColumns; } resizeScreen(); } private void resizeScreen() { final int[] cursor = {mCursorCol, mCursorRow}; int newTotalRows = (mScreen == mAltBuffer) ? mRows : mMainBuffer.mTotalRows; mScreen.resize(mColumns, mRows, newTotalRows, cursor, getStyle(), isAlternateBufferActive()); mCursorCol = cursor[0]; mCursorRow = cursor[1]; } public int getCursorRow() { return mCursorRow; } public int getCursorCol() { return mCursorCol; } /** Get the terminal cursor style. It will be one of {@link #TERMINAL_CURSOR_STYLES_LIST} */ public int getCursorStyle() { return mCursorStyle; } /** Set the terminal cursor style. */ public void setCursorStyle() { Integer cursorStyle = null; if (mClient != null) cursorStyle = mClient.getTerminalCursorStyle(); if (cursorStyle == null || !Arrays.asList(TERMINAL_CURSOR_STYLES_LIST).contains(cursorStyle)) mCursorStyle = DEFAULT_TERMINAL_CURSOR_STYLE; else mCursorStyle = cursorStyle; } public boolean isReverseVideo() { return isDecsetInternalBitSet(DECSET_BIT_REVERSE_VIDEO); } public boolean isCursorEnabled() { return isDecsetInternalBitSet(DECSET_BIT_CURSOR_ENABLED); } public boolean shouldCursorBeVisible() { if (!isCursorEnabled()) return false; else return mCursorBlinkingEnabled ? mCursorBlinkState : true; } public void setCursorBlinkingEnabled(boolean cursorBlinkingEnabled) { this.mCursorBlinkingEnabled = cursorBlinkingEnabled; } public void setCursorBlinkState(boolean cursorBlinkState) { this.mCursorBlinkState = cursorBlinkState; } public boolean isKeypadApplicationMode() { return isDecsetInternalBitSet(DECSET_BIT_APPLICATION_KEYPAD); } public boolean isCursorKeysApplicationMode() { return isDecsetInternalBitSet(DECSET_BIT_APPLICATION_CURSOR_KEYS); } /** If mouse events are being sent as escape codes to the terminal. */ public boolean isMouseTrackingActive() { return isDecsetInternalBitSet(DECSET_BIT_MOUSE_TRACKING_PRESS_RELEASE) || isDecsetInternalBitSet(DECSET_BIT_MOUSE_TRACKING_BUTTON_EVENT); } private void setDefaultTabStops() { for (int i = 0; i < mColumns; i++) mTabStop[i] = (i & 7) == 0 && i != 0; } /** * Accept bytes (typically from the pseudo-teletype) and process them. * * @param buffer a byte array containing the bytes to be processed * @param length the number of bytes in the array to process */ public void append(byte[] buffer, int length) { for (int i = 0; i < length; i++) processByte(buffer[i]); } private void processByte(byte byteToProcess) { if (mUtf8ToFollow > 0) { if ((byteToProcess & 0b11000000) == 0b10000000) { // 10xxxxxx, a continuation byte. mUtf8InputBuffer[mUtf8Index++] = byteToProcess; if (--mUtf8ToFollow == 0) { byte firstByteMask = (byte) (mUtf8Index == 2 ? 0b00011111 : (mUtf8Index == 3 ? 0b00001111 : 0b00000111)); int codePoint = (mUtf8InputBuffer[0] & firstByteMask); for (int i = 1; i < mUtf8Index; i++) codePoint = ((codePoint << 6) | (mUtf8InputBuffer[i] & 0b00111111)); if (((codePoint <= 0b1111111) && mUtf8Index > 1) || (codePoint < 0b11111111111 && mUtf8Index > 2) || (codePoint < 0b1111111111111111 && mUtf8Index > 3)) { // Overlong encoding. codePoint = UNICODE_REPLACEMENT_CHAR; } mUtf8Index = mUtf8ToFollow = 0; if (codePoint >= 0x80 && codePoint <= 0x9F) { // Sequence decoded to a C1 control character which we ignore. They are // not used nowadays and increases the risk of messing up the terminal state // on binary input. XTerm does not allow them in utf-8: // "It is not possible to use a C1 control obtained from decoding the // UTF-8 text" - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html } else { switch (Character.getType(codePoint)) { case Character.UNASSIGNED: case Character.SURROGATE: codePoint = UNICODE_REPLACEMENT_CHAR; } processCodePoint(codePoint); } } } else { // Not a UTF-8 continuation byte so replace the entire sequence up to now with the replacement char: mUtf8Index = mUtf8ToFollow = 0; emitCodePoint(UNICODE_REPLACEMENT_CHAR); // The Unicode Standard Version 6.2 – Core Specification // (http://www.unicode.org/versions/Unicode6.2.0/ch03.pdf): // "If the converter encounters an ill-formed UTF-8 code unit sequence which starts with a valid first // byte, but which does not continue with valid successor bytes (see Table 3-7), it must not consume the // successor bytes as part of the ill-formed subsequence // whenever those successor bytes themselves constitute part of a well-formed UTF-8 code unit // subsequence." processByte(byteToProcess); } } else { if ((byteToProcess & 0b10000000) == 0) { // The leading bit is not set so it is a 7-bit ASCII character. processCodePoint(byteToProcess); return; } else if ((byteToProcess & 0b11100000) == 0b11000000) { // 110xxxxx, a two-byte sequence. mUtf8ToFollow = 1; } else if ((byteToProcess & 0b11110000) == 0b11100000) { // 1110xxxx, a three-byte sequence. mUtf8ToFollow = 2; } else if ((byteToProcess & 0b11111000) == 0b11110000) { // 11110xxx, a four-byte sequence. mUtf8ToFollow = 3; } else { // Not a valid UTF-8 sequence start, signal invalid data: processCodePoint(UNICODE_REPLACEMENT_CHAR); return; } mUtf8InputBuffer[mUtf8Index++] = byteToProcess; } } public void processCodePoint(int b) { switch (b) { case 0: // Null character (NUL, ^@). Do nothing. break; case 7: // Bell (BEL, ^G, \a). If in an OSC sequence, BEL may terminate a string; otherwise signal bell. if (mEscapeState == ESC_OSC) doOsc(b); else mSession.onBell(); break; case 8: // Backspace (BS, ^H). if (mLeftMargin == mCursorCol) { // Jump to previous line if it was auto-wrapped. int previousRow = mCursorRow - 1; if (previousRow >= 0 && mScreen.getLineWrap(previousRow)) { mScreen.clearLineWrap(previousRow); setCursorRowCol(previousRow, mRightMargin - 1); } } else { setCursorCol(mCursorCol - 1); } break; case 9: // Horizontal tab (HT, \t) - move to next tab stop, but not past edge of screen // XXX: Should perhaps use color if writing to new cells. Try with // printf "\033[41m\tXX\033[0m\n" // The OSX Terminal.app colors the spaces from the tab red, but xterm does not. // Note that Terminal.app only colors on new cells, in e.g. // printf "\033[41m\t\r\033[42m\tXX\033[0m\n" // the first cells are created with a red background, but when tabbing over // them again with a green background they are not overwritten. mCursorCol = nextTabStop(1); break; case 10: // Line feed (LF, \n). case 11: // Vertical tab (VT, \v). case 12: // Form feed (FF, \f). doLinefeed(); break; case 13: // Carriage return (CR, \r). setCursorCol(mLeftMargin); break; case 14: // Shift Out (Ctrl-N, SO) → Switch to Alternate Character Set. This invokes the G1 character set. mUseLineDrawingUsesG0 = false; break; case 15: // Shift In (Ctrl-O, SI) → Switch to Standard Character Set. This invokes the G0 character set. mUseLineDrawingUsesG0 = true; break; case 24: // CAN. case 26: // SUB. if (mEscapeState != ESC_NONE) { // FIXME: What is this?? mEscapeState = ESC_NONE; emitCodePoint(127); } break; case 27: // ESC // Starts an escape sequence unless we're parsing a string if (mEscapeState == ESC_P) { // XXX: Ignore escape when reading device control sequence, since it may be part of string terminator. return; } else if (mEscapeState != ESC_OSC) { startEscapeSequence(); } else { doOsc(b); } break; default: mContinueSequence = false; switch (mEscapeState) { case ESC_NONE: if (b >= 32) emitCodePoint(b); break; case ESC: doEsc(b); break; case ESC_POUND: doEscPound(b); break; case ESC_SELECT_LEFT_PAREN: // Designate G0 Character Set (ISO 2022, VT100). mUseLineDrawingG0 = (b == '0'); break; case ESC_SELECT_RIGHT_PAREN: // Designate G1 Character Set (ISO 2022, VT100). mUseLineDrawingG1 = (b == '0'); break; case ESC_CSI: doCsi(b); break; case ESC_CSI_EXCLAMATION: if (b == 'p') { // Soft terminal reset (DECSTR, http://vt100.net/docs/vt510-rm/DECSTR). reset(); } else { unknownSequence(b); } break; case ESC_CSI_QUESTIONMARK: doCsiQuestionMark(b); break; case ESC_CSI_BIGGERTHAN: doCsiBiggerThan(b); break; case ESC_CSI_DOLLAR: boolean originMode = isDecsetInternalBitSet(DECSET_BIT_ORIGIN_MODE); int effectiveTopMargin = originMode ? mTopMargin : 0; int effectiveBottomMargin = originMode ? mBottomMargin : mRows; int effectiveLeftMargin = originMode ? mLeftMargin : 0; int effectiveRightMargin = originMode ? mRightMargin : mColumns; switch (b) { case 'v': // ${CSI}${SRC_TOP}${SRC_LEFT}${SRC_BOTTOM}${SRC_RIGHT}${SRC_PAGE}${DST_TOP}${DST_LEFT}${DST_PAGE}$v" // Copy rectangular area (DECCRA - http://vt100.net/docs/vt510-rm/DECCRA): // "If Pbs is greater than Pts, or Pls is greater than Prs, the terminal ignores DECCRA. // The coordinates of the rectangular area are affected by the setting of origin mode (DECOM). // DECCRA is not affected by the page margins. // The copied text takes on the line attributes of the destination area. // If the value of Pt, Pl, Pb, or Pr exceeds the width or height of the active page, then the value // is treated as the width or height of that page. // If the destination area is partially off the page, then DECCRA clips the off-page data. // DECCRA does not change the active cursor position." int topSource = Math.min(getArg(0, 1, true) - 1 + effectiveTopMargin, mRows); int leftSource = Math.min(getArg(1, 1, true) - 1 + effectiveLeftMargin, mColumns); // Inclusive, so do not subtract one: int bottomSource = Math.min(Math.max(getArg(2, mRows, true) + effectiveTopMargin, topSource), mRows); int rightSource = Math.min(Math.max(getArg(3, mColumns, true) + effectiveLeftMargin, leftSource), mColumns); // int sourcePage = getArg(4, 1, true); int destionationTop = Math.min(getArg(5, 1, true) - 1 + effectiveTopMargin, mRows); int destinationLeft = Math.min(getArg(6, 1, true) - 1 + effectiveLeftMargin, mColumns); // int destinationPage = getArg(7, 1, true); int heightToCopy = Math.min(mRows - destionationTop, bottomSource - topSource); int widthToCopy = Math.min(mColumns - destinationLeft, rightSource - leftSource); mScreen.blockCopy(leftSource, topSource, widthToCopy, heightToCopy, destinationLeft, destionationTop); break; case '{': // ${CSI}${TOP}${LEFT}${BOTTOM}${RIGHT}${" // Selective erase rectangular area (DECSERA - http://www.vt100.net/docs/vt510-rm/DECSERA). case 'x': // ${CSI}${CHAR};${TOP}${LEFT}${BOTTOM}${RIGHT}$x" // Fill rectangular area (DECFRA - http://www.vt100.net/docs/vt510-rm/DECFRA). case 'z': // ${CSI}$${TOP}${LEFT}${BOTTOM}${RIGHT}$z" // Erase rectangular area (DECERA - http://www.vt100.net/docs/vt510-rm/DECERA). boolean erase = b != 'x'; boolean selective = b == '{'; // Only DECSERA keeps visual attributes, DECERA does not: boolean keepVisualAttributes = erase && selective; int argIndex = 0; int fillChar = erase ? ' ' : getArg(argIndex++, -1, true); // "Pch can be any value from 32 to 126 or from 160 to 255. If Pch is not in this range, then the // terminal ignores the DECFRA command": if ((fillChar >= 32 && fillChar <= 126) || (fillChar >= 160 && fillChar <= 255)) { // "If the value of Pt, Pl, Pb, or Pr exceeds the width or height of the active page, the value // is treated as the width or height of that page." int top = Math.min(getArg(argIndex++, 1, true) + effectiveTopMargin, effectiveBottomMargin + 1); int left = Math.min(getArg(argIndex++, 1, true) + effectiveLeftMargin, effectiveRightMargin + 1); int bottom = Math.min(getArg(argIndex++, mRows, true) + effectiveTopMargin, effectiveBottomMargin); int right = Math.min(getArg(argIndex, mColumns, true) + effectiveLeftMargin, effectiveRightMargin); long style = getStyle(); for (int row = top - 1; row < bottom; row++) for (int col = left - 1; col < right; col++) if (!selective || (TextStyle.decodeEffect(mScreen.getStyleAt(row, col)) & TextStyle.CHARACTER_ATTRIBUTE_PROTECTED) == 0) mScreen.setChar(col, row, fillChar, keepVisualAttributes ? mScreen.getStyleAt(row, col) : style); } break; case 'r': // "${CSI}${TOP}${LEFT}${BOTTOM}${RIGHT}${ATTRIBUTES}$r" // Change attributes in rectangular area (DECCARA - http://vt100.net/docs/vt510-rm/DECCARA). case 't': // "${CSI}${TOP}${LEFT}${BOTTOM}${RIGHT}${ATTRIBUTES}$t" // Reverse attributes in rectangular area (DECRARA - http://www.vt100.net/docs/vt510-rm/DECRARA). boolean reverse = b == 't'; // FIXME: "coordinates of the rectangular area are affected by the setting of origin mode (DECOM)". int top = Math.min(getArg(0, 1, true) - 1, effectiveBottomMargin) + effectiveTopMargin; int left = Math.min(getArg(1, 1, true) - 1, effectiveRightMargin) + effectiveLeftMargin; int bottom = Math.min(getArg(2, mRows, true) + 1, effectiveBottomMargin - 1) + effectiveTopMargin; int right = Math.min(getArg(3, mColumns, true) + 1, effectiveRightMargin - 1) + effectiveLeftMargin; if (mArgIndex >= 4) { if (mArgIndex >= mArgs.length) mArgIndex = mArgs.length - 1; for (int i = 4; i <= mArgIndex; i++) { int bits = 0; boolean setOrClear = true; // True if setting, false if clearing. switch (getArg(i, 0, false)) { case 0: // Attributes off (no bold, no underline, no blink, positive image). bits = (TextStyle.CHARACTER_ATTRIBUTE_BOLD | TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE | TextStyle.CHARACTER_ATTRIBUTE_BLINK | TextStyle.CHARACTER_ATTRIBUTE_INVERSE); if (!reverse) setOrClear = false; break; case 1: // Bold. bits = TextStyle.CHARACTER_ATTRIBUTE_BOLD; break; case 4: // Underline. bits = TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE; break; case 5: // Blink. bits = TextStyle.CHARACTER_ATTRIBUTE_BLINK; break; case 7: // Negative image. bits = TextStyle.CHARACTER_ATTRIBUTE_INVERSE; break; case 22: // No bold. bits = TextStyle.CHARACTER_ATTRIBUTE_BOLD; setOrClear = false; break; case 24: // No underline. bits = TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE; setOrClear = false; break; case 25: // No blink. bits = TextStyle.CHARACTER_ATTRIBUTE_BLINK; setOrClear = false; break; case 27: // Positive image. bits = TextStyle.CHARACTER_ATTRIBUTE_INVERSE; setOrClear = false; break; } if (reverse && !setOrClear) { // Reverse attributes in rectangular area ignores non-(1,4,5,7) bits. } else { mScreen.setOrClearEffect(bits, setOrClear, reverse, isDecsetInternalBitSet(DECSET_BIT_RECTANGULAR_CHANGEATTRIBUTE), effectiveLeftMargin, effectiveRightMargin, top, left, bottom, right); } } } else { // Do nothing. } break; default: unknownSequence(b); } break; case ESC_CSI_DOUBLE_QUOTE: if (b == 'q') { // http://www.vt100.net/docs/vt510-rm/DECSCA int arg = getArg0(0); if (arg == 0 || arg == 2) { // DECSED and DECSEL can erase characters. mEffect &= ~TextStyle.CHARACTER_ATTRIBUTE_PROTECTED; } else if (arg == 1) { // DECSED and DECSEL cannot erase characters. mEffect |= TextStyle.CHARACTER_ATTRIBUTE_PROTECTED; } else { unknownSequence(b); } } else { unknownSequence(b); } break; case ESC_CSI_SINGLE_QUOTE: if (b == '}') { // Insert Ps Column(s) (default = 1) (DECIC), VT420 and up. int columnsAfterCursor = mRightMargin - mCursorCol; int columnsToInsert = Math.min(getArg0(1), columnsAfterCursor); int columnsToMove = columnsAfterCursor - columnsToInsert; mScreen.blockCopy(mCursorCol, 0, columnsToMove, mRows, mCursorCol + columnsToInsert, 0); blockClear(mCursorCol, 0, columnsToInsert, mRows); } else if (b == '~') { // Delete Ps Column(s) (default = 1) (DECDC), VT420 and up. int columnsAfterCursor = mRightMargin - mCursorCol; int columnsToDelete = Math.min(getArg0(1), columnsAfterCursor); int columnsToMove = columnsAfterCursor - columnsToDelete; mScreen.blockCopy(mCursorCol + columnsToDelete, 0, columnsToMove, mRows, mCursorCol, 0); } else { unknownSequence(b); } break; case ESC_PERCENT: break; case ESC_OSC: doOsc(b); break; case ESC_OSC_ESC: doOscEsc(b); break; case ESC_P: doDeviceControl(b); break; case ESC_CSI_QUESTIONMARK_ARG_DOLLAR: if (b == 'p') { // Request DEC private mode (DECRQM). int mode = getArg0(0); int value; if (mode == 47 || mode == 1047 || mode == 1049) { // This state is carried by mScreen pointer. value = (mScreen == mAltBuffer) ? 1 : 2; } else { int internalBit = mapDecSetBitToInternalBit(mode); if (internalBit != -1) { value = isDecsetInternalBitSet(internalBit) ? 1 : 2; // 1=set, 2=reset. } else { Logger.logError(mClient, LOG_TAG, "Got DECRQM for unrecognized private DEC mode=" + mode); value = 0; // 0=not recognized, 3=permanently set, 4=permanently reset } } mSession.write(String.format(Locale.US, "\033[?%d;%d$y", mode, value)); } else { unknownSequence(b); } break; case ESC_CSI_ARGS_SPACE: int arg = getArg0(0); switch (b) { case 'q': // "${CSI}${STYLE} q" - set cursor style (http://www.vt100.net/docs/vt510-rm/DECSCUSR). switch (arg) { case 0: // Blinking block. case 1: // Blinking block. case 2: // Steady block. mCursorStyle = TERMINAL_CURSOR_STYLE_BLOCK; break; case 3: // Blinking underline. case 4: // Steady underline. mCursorStyle = TERMINAL_CURSOR_STYLE_UNDERLINE; break; case 5: // Blinking bar (xterm addition). case 6: // Steady bar (xterm addition). mCursorStyle = TERMINAL_CURSOR_STYLE_BAR; break; } break; case 't': case 'u': // Set margin-bell volume - ignore. break; default: unknownSequence(b); } break; case ESC_CSI_ARGS_ASTERIX: int attributeChangeExtent = getArg0(0); if (b == 'x' && (attributeChangeExtent >= 0 && attributeChangeExtent <= 2)) { // Select attribute change extent (DECSACE - http://www.vt100.net/docs/vt510-rm/DECSACE). setDecsetinternalBit(DECSET_BIT_RECTANGULAR_CHANGEATTRIBUTE, attributeChangeExtent == 2); } else { unknownSequence(b); } break; default: unknownSequence(b); break; } if (!mContinueSequence) mEscapeState = ESC_NONE; break; } } /** When in {@link #ESC_P} ("device control") sequence. */ private void doDeviceControl(int b) { switch (b) { case (byte) '\\': // End of ESC \ string Terminator { String dcs = mOSCOrDeviceControlArgs.toString(); // DCS $ q P t ST. Request Status String (DECRQSS) if (dcs.startsWith("$q")) { if (dcs.equals("$q\"p")) { // DECSCL, conformance level, http://www.vt100.net/docs/vt510-rm/DECSCL: String csiString = "64;1\"p"; mSession.write("\033P1$r" + csiString + "\033\\"); } else { finishSequenceAndLogError("Unrecognized DECRQSS string: '" + dcs + "'"); } } else if (dcs.startsWith("+q")) { // Request Termcap/Terminfo String. The string following the "q" is a list of names encoded in // hexadecimal (2 digits per character) separated by ; which correspond to termcap or terminfo key // names. // Two special features are also recognized, which are not key names: Co for termcap colors (or colors // for terminfo colors), and TN for termcap name (or name for terminfo name). // xterm responds with DCS 1 + r P t ST for valid requests, adding to P t an = , and the value of the // corresponding string that xterm would send, or DCS 0 + r P t ST for invalid requests. The strings are // encoded in hexadecimal (2 digits per character). // Example: // :kr=\EOC: ks=\E[?1h\E=: ku=\EOA: le=^H:mb=\E[5m:md=\E[1m:\ // where // kd=down-arrow key // kl=left-arrow key // kr=right-arrow key // ku=up-arrow key // #2=key_shome, "shifted home" // #4=key_sleft, "shift arrow left" // %i=key_sright, "shift arrow right" // *7=key_send, "shifted end" // k1=F1 function key // Example: Request for ku is "ESC P + q 6 b 7 5 ESC \", where 6b7d=ku in hexadecimal. // Xterm response in normal cursor mode: // "<27> P 1 + r 6 b 7 5 = 1 B 5 B 4 1" where 0x1B 0x5B 0x41 = 27 91 65 = ESC [ A // Xterm response in application cursor mode: // "<27> P 1 + r 6 b 7 5 = 1 B 5 B 4 1" where 0x1B 0x4F 0x41 = 27 91 65 = ESC 0 A // #4 is "shift arrow left": // *** Device Control (DCS) for '#4'- 'ESC P + q 23 34 ESC \' // Response: <27> P 1 + r 2 3 3 4 = 1 B 5 B 3 1 3 B 3 2 4 4 <27> \ // where 0x1B 0x5B 0x31 0x3B 0x32 0x44 = ESC [ 1 ; 2 D // which we find in: TermKeyListener.java: KEY_MAP.put(KEYMOD_SHIFT | KEYCODE_DPAD_LEFT, "\033[1;2D"); // See http://h30097.www3.hp.com/docs/base_doc/DOCUMENTATION/V40G_HTML/MAN/MAN4/0178____.HTM for what to // respond, as well as http://www.freebsd.org/cgi/man.cgi?query=termcap&sektion=5#CAPABILITIES for // the meaning of e.g. "ku", "kd", "kr", "kl" for (String part : dcs.substring(2).split(";")) { if (part.length() % 2 == 0) { StringBuilder transBuffer = new StringBuilder(); char c; for (int i = 0; i < part.length(); i += 2) { try { c = (char) Long.decode("0x" + part.charAt(i) + "" + part.charAt(i + 1)).longValue(); } catch (NumberFormatException e) { Logger.logStackTraceWithMessage(mClient, LOG_TAG, "Invalid device termcap/terminfo encoded name \"" + part + "\"", e); continue; } transBuffer.append(c); } String trans = transBuffer.toString(); String responseValue; switch (trans) { case "Co": case "colors": responseValue = "256"; // Number of colors. break; case "TN": case "name": responseValue = "xterm"; break; default: responseValue = KeyHandler.getCodeFromTermcap(trans, isDecsetInternalBitSet(DECSET_BIT_APPLICATION_CURSOR_KEYS), isDecsetInternalBitSet(DECSET_BIT_APPLICATION_KEYPAD)); break; } if (responseValue == null) { switch (trans) { case "%1": // Help key - ignore case "&8": // Undo key - ignore. break; default: Logger.logWarn(mClient, LOG_TAG, "Unhandled termcap/terminfo name: '" + trans + "'"); } // Respond with invalid request: mSession.write("\033P0+r" + part + "\033\\"); } else { StringBuilder hexEncoded = new StringBuilder(); for (int j = 0; j < responseValue.length(); j++) { hexEncoded.append(String.format("%02X", (int) responseValue.charAt(j))); } mSession.write("\033P1+r" + part + "=" + hexEncoded + "\033\\"); } } else { Logger.logError(mClient, LOG_TAG, "Invalid device termcap/terminfo name of odd length: " + part); } } } else { if (LOG_ESCAPE_SEQUENCES) Logger.logError(mClient, LOG_TAG, "Unrecognized device control string: " + dcs); } finishSequence(); } break; default: if (mOSCOrDeviceControlArgs.length() > MAX_OSC_STRING_LENGTH) { // Too long. mOSCOrDeviceControlArgs.setLength(0); finishSequence(); } else { mOSCOrDeviceControlArgs.appendCodePoint(b); continueSequence(mEscapeState); } } } private int nextTabStop(int numTabs) { for (int i = mCursorCol + 1; i < mColumns; i++) if (mTabStop[i] && --numTabs == 0) return Math.min(i, mRightMargin); return mRightMargin - 1; } /** Process byte while in the {@link #ESC_CSI_QUESTIONMARK} escape state. */ private void doCsiQuestionMark(int b) { switch (b) { case 'J': // Selective erase in display (DECSED) - http://www.vt100.net/docs/vt510-rm/DECSED. case 'K': // Selective erase in line (DECSEL) - http://vt100.net/docs/vt510-rm/DECSEL. mAboutToAutoWrap = false; int fillChar = ' '; int startCol = -1; int startRow = -1; int endCol = -1; int endRow = -1; boolean justRow = (b == 'K'); switch (getArg0(0)) { case 0: // Erase from the active position to the end, inclusive (default). startCol = mCursorCol; startRow = mCursorRow; endCol = mColumns; endRow = justRow ? (mCursorRow + 1) : mRows; break; case 1: // Erase from start to the active position, inclusive. startCol = 0; startRow = justRow ? mCursorRow : 0; endCol = mCursorCol + 1; endRow = mCursorRow + 1; break; case 2: // Erase all of the display/line. startCol = 0; startRow = justRow ? mCursorRow : 0; endCol = mColumns; endRow = justRow ? (mCursorRow + 1) : mRows; break; default: unknownSequence(b); break; } long style = getStyle(); for (int row = startRow; row < endRow; row++) { for (int col = startCol; col < endCol; col++) { if ((TextStyle.decodeEffect(mScreen.getStyleAt(row, col)) & TextStyle.CHARACTER_ATTRIBUTE_PROTECTED) == 0) mScreen.setChar(col, row, fillChar, style); } } break; case 'h': case 'l': if (mArgIndex >= mArgs.length) mArgIndex = mArgs.length - 1; for (int i = 0; i <= mArgIndex; i++) doDecSetOrReset(b == 'h', mArgs[i]); break; case 'n': // Device Status Report (DSR, DEC-specific). switch (getArg0(-1)) { case 6: // Extended Cursor Position (DECXCPR - http://www.vt100.net/docs/vt510-rm/DECXCPR). Page=1. mSession.write(String.format(Locale.US, "\033[?%d;%d;1R", mCursorRow + 1, mCursorCol + 1)); break; default: finishSequence(); return; } break; case 'r': case 's': if (mArgIndex >= mArgs.length) mArgIndex = mArgs.length - 1; for (int i = 0; i <= mArgIndex; i++) { int externalBit = mArgs[i]; int internalBit = mapDecSetBitToInternalBit(externalBit); if (internalBit == -1) { Logger.logWarn(mClient, LOG_TAG, "Ignoring request to save/recall decset bit=" + externalBit); } else { if (b == 's') { mSavedDecSetFlags |= internalBit; } else { doDecSetOrReset((mSavedDecSetFlags & internalBit) != 0, externalBit); } } } break; case '$': continueSequence(ESC_CSI_QUESTIONMARK_ARG_DOLLAR); return; default: parseArg(b); } } public void doDecSetOrReset(boolean setting, int externalBit) { int internalBit = mapDecSetBitToInternalBit(externalBit); if (internalBit != -1) { setDecsetinternalBit(internalBit, setting); } switch (externalBit) { case 1: // Application Cursor Keys (DECCKM). break; case 3: // Set: 132 column mode (. Reset: 80 column mode. ANSI name: DECCOLM. // We don't actually set/reset 132 cols, but we do want the side effects // (FIXME: Should only do this if the 95 DECSET bit (DECNCSM) is set, and if changing value?): // Sets the left, right, top and bottom scrolling margins to their default positions, which is important for // the "reset" utility to really reset the terminal: mLeftMargin = mTopMargin = 0; mBottomMargin = mRows; mRightMargin = mColumns; // "DECCOLM resets vertical split screen mode (DECLRMM) to unavailable": setDecsetinternalBit(DECSET_BIT_LEFTRIGHT_MARGIN_MODE, false); // "Erases all data in page memory": blockClear(0, 0, mColumns, mRows); setCursorRowCol(0, 0); break; case 4: // DECSCLM-Scrolling Mode. Ignore. break; case 5: // Reverse video. No action. break; case 6: // Set: Origin Mode. Reset: Normal Cursor Mode. Ansi name: DECOM. if (setting) setCursorPosition(0, 0); break; case 7: // Wrap-around bit, not specific action. case 8: // Auto-repeat Keys (DECARM). Do not implement. case 9: // X10 mouse reporting - outdated. Do not implement. case 12: // Control cursor blinking - ignore. case 25: // Hide/show cursor - no action needed, renderer will check with shouldCursorBeVisible(). if (mClient != null) mClient.onTerminalCursorStateChange(setting); break; case 40: // Allow 80 => 132 Mode, ignore. case 45: // TODO: Reverse wrap-around. Implement??? case 66: // Application keypad (DECNKM). break; case 69: // Left and right margin mode (DECLRMM). if (!setting) { mLeftMargin = 0; mRightMargin = mColumns; } break; case 1000: case 1001: case 1002: case 1003: case 1004: case 1005: // UTF-8 mouse mode, ignore. case 1006: // SGR Mouse Mode case 1015: case 1034: // Interpret "meta" key, sets eighth bit. break; case 1048: // Set: Save cursor as in DECSC. Reset: Restore cursor as in DECRC. if (setting) saveCursor(); else restoreCursor(); break; case 47: case 1047: case 1049: { // Set: Save cursor as in DECSC and use Alternate Screen Buffer, clearing it first. // Reset: Use Normal Screen Buffer and restore cursor as in DECRC. TerminalBuffer newScreen = setting ? mAltBuffer : mMainBuffer; if (newScreen != mScreen) { boolean resized = !(newScreen.mColumns == mColumns && newScreen.mScreenRows == mRows); if (setting) saveCursor(); mScreen = newScreen; if (!setting) { int col = mSavedStateMain.mSavedCursorCol; int row = mSavedStateMain.mSavedCursorRow; restoreCursor(); if (resized) { // Restore cursor position _not_ clipped to current screen (let resizeScreen() handle that): mCursorCol = col; mCursorRow = row; } } // Check if buffer size needs to be updated: if (resized) resizeScreen(); // Clear new screen if alt buffer: if (newScreen == mAltBuffer) newScreen.blockSet(0, 0, mColumns, mRows, ' ', getStyle()); } break; } case 2004: // Bracketed paste mode - setting bit is enough. break; default: unknownParameter(externalBit); break; } } private void doCsiBiggerThan(int b) { switch (b) { case 'c': // "${CSI}>c" or "${CSI}>c". Secondary Device Attributes (DA2). // Originally this was used for the terminal to respond with "identification code, firmware version level, // and hardware options" (http://vt100.net/docs/vt510-rm/DA2), with the first "41" meaning the VT420 // terminal type. This is not used anymore, but the second version level field has been changed by xterm // to mean it's release number ("patch numbers" listed at http://invisible-island.net/xterm/xterm.log.html), // and some applications use it as a feature check: // * tmux used to have a "xterm won't reach version 500 for a while so set that as the upper limit" check, // and then check "xterm_version > 270" if rectangular area operations such as DECCRA could be used. // * vim checks xterm version number >140 for "Request termcap/terminfo string" functionality >276 for SGR // mouse report. // The third number is a keyboard identifier not used nowadays. mSession.write("\033[>41;320;0c"); break; case 'm': // https://bugs.launchpad.net/gnome-terminal/+bug/96676/comments/25 // Depending on the first number parameter, this can set one of the xterm resources // modifyKeyboard, modifyCursorKeys, modifyFunctionKeys and modifyOtherKeys. // http://invisible-island.net/xterm/manpage/xterm.html#RESOURCES // * modifyKeyboard (parameter=1): // Normally xterm makes a special case regarding modifiers (shift, control, etc.) to handle special keyboard // layouts (legacy and vt220). This is done to provide compatible keyboards for DEC VT220 and related // terminals that implement user-defined keys (UDK). // The bits of the resource value selectively enable modification of the given category when these keyboards // are selected. The default is "0": // (0) The legacy/vt220 keyboards interpret only the Control-modifier when constructing numbered // function-keys. Other special keys are not modified. // (1) allows modification of the numeric keypad // (2) allows modification of the editing keypad // (4) allows modification of function-keys, overrides use of Shift-modifier for UDK. // (8) allows modification of other special keys // * modifyCursorKeys (parameter=2): // Tells how to handle the special case where Control-, Shift-, Alt- or Meta-modifiers are used to add a // parameter to the escape sequence returned by a cursor-key. The default is "2". // - Set it to -1 to disable it. // - Set it to 0 to use the old/obsolete behavior. // - Set it to 1 to prefix modified sequences with CSI. // - Set it to 2 to force the modifier to be the second parameter if it would otherwise be the first. // - Set it to 3 to mark the sequence with a ">" to hint that it is private. // * modifyFunctionKeys (parameter=3): // Tells how to handle the special case where Control-, Shift-, Alt- or Meta-modifiers are used to add a // parameter to the escape sequence returned by a (numbered) function- // key. The default is "2". The resource values are similar to modifyCursorKeys: // Set it to -1 to permit the user to use shift- and control-modifiers to construct function-key strings // using the normal encoding scheme. // - Set it to 0 to use the old/obsolete behavior. // - Set it to 1 to prefix modified sequences with CSI. // - Set it to 2 to force the modifier to be the second parameter if it would otherwise be the first. // - Set it to 3 to mark the sequence with a ">" to hint that it is private. // If modifyFunctionKeys is zero, xterm uses Control- and Shift-modifiers to allow the user to construct // numbered function-keys beyond the set provided by the keyboard: // (Control) adds the value given by the ctrlFKeys resource. // (Shift) adds twice the value given by the ctrlFKeys resource. // (Control/Shift) adds three times the value given by the ctrlFKeys resource. // // As a special case, legacy (when oldFunctionKeys is true) or vt220 (when sunKeyboard is true) // keyboards interpret only the Control-modifier when constructing numbered function-keys. // This is done to provide compatible keyboards for DEC VT220 and related terminals that // implement user-defined keys (UDK). // * modifyOtherKeys (parameter=4): // Like modifyCursorKeys, tells xterm to construct an escape sequence for other keys (such as "2") when // modified by Control-, Alt- or Meta-modifiers. This feature does not apply to function keys and // well-defined keys such as ESC or the control keys. The default is "0". // (0) disables this feature. // (1) enables this feature for keys except for those with well-known behavior, e.g., Tab, Backarrow and // some special control character cases, e.g., Control-Space to make a NUL. // (2) enables this feature for keys including the exceptions listed. Logger.logError(mClient, LOG_TAG, "(ignored) CSI > MODIFY RESOURCE: " + getArg0(-1) + " to " + getArg1(-1)); break; default: parseArg(b); break; } } private void startEscapeSequence() { mEscapeState = ESC; mArgIndex = 0; Arrays.fill(mArgs, -1); } private void doLinefeed() { boolean belowScrollingRegion = mCursorRow >= mBottomMargin; int newCursorRow = mCursorRow + 1; if (belowScrollingRegion) { // Move down (but not scroll) as long as we are above the last row. if (mCursorRow != mRows - 1) { setCursorRow(newCursorRow); } } else { if (newCursorRow == mBottomMargin) { scrollDownOneLine(); newCursorRow = mBottomMargin - 1; } setCursorRow(newCursorRow); } } private void continueSequence(int state) { mEscapeState = state; mContinueSequence = true; } private void doEscPound(int b) { switch (b) { case '8': // Esc # 8 - DEC screen alignment test - fill screen with E's. mScreen.blockSet(0, 0, mColumns, mRows, 'E', getStyle()); break; default: unknownSequence(b); break; } } /** Encountering a character in the {@link #ESC} state. */ private void doEsc(int b) { switch (b) { case '#': continueSequence(ESC_POUND); break; case '(': continueSequence(ESC_SELECT_LEFT_PAREN); break; case ')': continueSequence(ESC_SELECT_RIGHT_PAREN); break; case '6': // Back index (http://www.vt100.net/docs/vt510-rm/DECBI). Move left, insert blank column if start. if (mCursorCol > mLeftMargin) { mCursorCol--; } else { int rows = mBottomMargin - mTopMargin; mScreen.blockCopy(mLeftMargin, mTopMargin, mRightMargin - mLeftMargin - 1, rows, mLeftMargin + 1, mTopMargin); mScreen.blockSet(mLeftMargin, mTopMargin, 1, rows, ' ', TextStyle.encode(mForeColor, mBackColor, 0)); } break; case '7': // DECSC save cursor - http://www.vt100.net/docs/vt510-rm/DECSC saveCursor(); break; case '8': // DECRC restore cursor - http://www.vt100.net/docs/vt510-rm/DECRC restoreCursor(); break; case '9': // Forward Index (http://www.vt100.net/docs/vt510-rm/DECFI). Move right, insert blank column if end. if (mCursorCol < mRightMargin - 1) { mCursorCol++; } else { int rows = mBottomMargin - mTopMargin; mScreen.blockCopy(mLeftMargin + 1, mTopMargin, mRightMargin - mLeftMargin - 1, rows, mLeftMargin, mTopMargin); mScreen.blockSet(mRightMargin - 1, mTopMargin, 1, rows, ' ', TextStyle.encode(mForeColor, mBackColor, 0)); } break; case 'c': // RIS - Reset to Initial State (http://vt100.net/docs/vt510-rm/RIS). reset(); mMainBuffer.clearTranscript(); blockClear(0, 0, mColumns, mRows); setCursorPosition(0, 0); break; case 'D': // INDEX doLinefeed(); break; case 'E': // Next line (http://www.vt100.net/docs/vt510-rm/NEL). setCursorCol(isDecsetInternalBitSet(DECSET_BIT_ORIGIN_MODE) ? mLeftMargin : 0); doLinefeed(); break; case 'F': // Cursor to lower-left corner of screen setCursorRowCol(0, mBottomMargin - 1); break; case 'H': // Tab set mTabStop[mCursorCol] = true; break; case 'M': // "${ESC}M" - reverse index (RI). // http://www.vt100.net/docs/vt100-ug/chapter3.html: "Move the active position to the same horizontal // position on the preceding line. If the active position is at the top margin, a scroll down is performed". if (mCursorRow <= mTopMargin) { mScreen.blockCopy(0, mTopMargin, mColumns, mBottomMargin - (mTopMargin + 1), 0, mTopMargin + 1); blockClear(0, mTopMargin, mColumns); } else { mCursorRow--; } break; case 'N': // SS2, ignore. case '0': // SS3, ignore. break; case 'P': // Device control string mOSCOrDeviceControlArgs.setLength(0); continueSequence(ESC_P); break; case '[': continueSequence(ESC_CSI); mIsCSIStart = true; mLastCSIArg = null; break; case '=': // DECKPAM setDecsetinternalBit(DECSET_BIT_APPLICATION_KEYPAD, true); break; case ']': // OSC mOSCOrDeviceControlArgs.setLength(0); continueSequence(ESC_OSC); break; case '>': // DECKPNM setDecsetinternalBit(DECSET_BIT_APPLICATION_KEYPAD, false); break; default: unknownSequence(b); break; } } /** DECSC save cursor - http://www.vt100.net/docs/vt510-rm/DECSC . See {@link #restoreCursor()}. */ private void saveCursor() { SavedScreenState state = (mScreen == mMainBuffer) ? mSavedStateMain : mSavedStateAlt; state.mSavedCursorRow = mCursorRow; state.mSavedCursorCol = mCursorCol; state.mSavedEffect = mEffect; state.mSavedForeColor = mForeColor; state.mSavedBackColor = mBackColor; state.mSavedDecFlags = mCurrentDecSetFlags; state.mUseLineDrawingG0 = mUseLineDrawingG0; state.mUseLineDrawingG1 = mUseLineDrawingG1; state.mUseLineDrawingUsesG0 = mUseLineDrawingUsesG0; } /** DECRS restore cursor - http://www.vt100.net/docs/vt510-rm/DECRC. See {@link #saveCursor()}. */ private void restoreCursor() { SavedScreenState state = (mScreen == mMainBuffer) ? mSavedStateMain : mSavedStateAlt; setCursorRowCol(state.mSavedCursorRow, state.mSavedCursorCol); mEffect = state.mSavedEffect; mForeColor = state.mSavedForeColor; mBackColor = state.mSavedBackColor; int mask = (DECSET_BIT_AUTOWRAP | DECSET_BIT_ORIGIN_MODE); mCurrentDecSetFlags = (mCurrentDecSetFlags & ~mask) | (state.mSavedDecFlags & mask); mUseLineDrawingG0 = state.mUseLineDrawingG0; mUseLineDrawingG1 = state.mUseLineDrawingG1; mUseLineDrawingUsesG0 = state.mUseLineDrawingUsesG0; } /** Following a CSI - Control Sequence Introducer, "\033[". {@link #ESC_CSI}. */ private void doCsi(int b) { switch (b) { case '!': continueSequence(ESC_CSI_EXCLAMATION); break; case '"': continueSequence(ESC_CSI_DOUBLE_QUOTE); break; case '\'': continueSequence(ESC_CSI_SINGLE_QUOTE); break; case '$': continueSequence(ESC_CSI_DOLLAR); break; case '*': continueSequence(ESC_CSI_ARGS_ASTERIX); break; case '@': { // "CSI{n}@" - Insert ${n} space characters (ICH) - http://www.vt100.net/docs/vt510-rm/ICH. mAboutToAutoWrap = false; int columnsAfterCursor = mColumns - mCursorCol; int spacesToInsert = Math.min(getArg0(1), columnsAfterCursor); int charsToMove = columnsAfterCursor - spacesToInsert; mScreen.blockCopy(mCursorCol, mCursorRow, charsToMove, 1, mCursorCol + spacesToInsert, mCursorRow); blockClear(mCursorCol, mCursorRow, spacesToInsert); } break; case 'A': // "CSI${n}A" - Cursor up (CUU) ${n} rows. setCursorRow(Math.max(0, mCursorRow - getArg0(1))); break; case 'B': // "CSI${n}B" - Cursor down (CUD) ${n} rows. setCursorRow(Math.min(mRows - 1, mCursorRow + getArg0(1))); break; case 'C': // "CSI${n}C" - Cursor forward (CUF). case 'a': // "CSI${n}a" - Horizontal position relative (HPR). From ISO-6428/ECMA-48. setCursorCol(Math.min(mRightMargin - 1, mCursorCol + getArg0(1))); break; case 'D': // "CSI${n}D" - Cursor backward (CUB) ${n} columns. setCursorCol(Math.max(mLeftMargin, mCursorCol - getArg0(1))); break; case 'E': // "CSI{n}E - Cursor Next Line (CNL). From ISO-6428/ECMA-48. setCursorPosition(0, mCursorRow + getArg0(1)); break; case 'F': // "CSI{n}F - Cursor Previous Line (CPL). From ISO-6428/ECMA-48. setCursorPosition(0, mCursorRow - getArg0(1)); break; case 'G': // "CSI${n}G" - Cursor horizontal absolute (CHA) to column ${n}. setCursorCol(Math.min(Math.max(1, getArg0(1)), mColumns) - 1); break; case 'H': // "${CSI}${ROW};${COLUMN}H" - Cursor position (CUP). case 'f': // "${CSI}${ROW};${COLUMN}f" - Horizontal and Vertical Position (HVP). setCursorPosition(getArg1(1) - 1, getArg0(1) - 1); break; case 'I': // Cursor Horizontal Forward Tabulation (CHT). Move the active position n tabs forward. setCursorCol(nextTabStop(getArg0(1))); break; case 'J': // "${CSI}${0,1,2,3}J" - Erase in Display (ED) // ED ignores the scrolling margins. switch (getArg0(0)) { case 0: // Erase from the active position to the end of the screen, inclusive (default). blockClear(mCursorCol, mCursorRow, mColumns - mCursorCol); blockClear(0, mCursorRow + 1, mColumns, mRows - (mCursorRow + 1)); break; case 1: // Erase from start of the screen to the active position, inclusive. blockClear(0, 0, mColumns, mCursorRow); blockClear(0, mCursorRow, mCursorCol + 1); break; case 2: // Erase all of the display - all lines are erased, changed to single-width, and the cursor does not // move.. blockClear(0, 0, mColumns, mRows); break; case 3: // Delete all lines saved in the scrollback buffer (xterm etc) mMainBuffer.clearTranscript(); break; default: unknownSequence(b); return; } mAboutToAutoWrap = false; break; case 'K': // "CSI{n}K" - Erase in line (EL). switch (getArg0(0)) { case 0: // Erase from the cursor to the end of the line, inclusive (default) blockClear(mCursorCol, mCursorRow, mColumns - mCursorCol); break; case 1: // Erase from the start of the screen to the cursor, inclusive. blockClear(0, mCursorRow, mCursorCol + 1); break; case 2: // Erase all of the line. blockClear(0, mCursorRow, mColumns); break; default: unknownSequence(b); return; } mAboutToAutoWrap = false; break; case 'L': // "${CSI}{N}L" - insert ${N} lines (IL). { int linesAfterCursor = mBottomMargin - mCursorRow; int linesToInsert = Math.min(getArg0(1), linesAfterCursor); int linesToMove = linesAfterCursor - linesToInsert; mScreen.blockCopy(0, mCursorRow, mColumns, linesToMove, 0, mCursorRow + linesToInsert); blockClear(0, mCursorRow, mColumns, linesToInsert); } break; case 'M': // "${CSI}${N}M" - delete N lines (DL). { mAboutToAutoWrap = false; int linesAfterCursor = mBottomMargin - mCursorRow; int linesToDelete = Math.min(getArg0(1), linesAfterCursor); int linesToMove = linesAfterCursor - linesToDelete; mScreen.blockCopy(0, mCursorRow + linesToDelete, mColumns, linesToMove, 0, mCursorRow); blockClear(0, mCursorRow + linesToMove, mColumns, linesToDelete); } break; case 'P': // "${CSI}{N}P" - delete ${N} characters (DCH). { // http://www.vt100.net/docs/vt510-rm/DCH: "If ${N} is greater than the number of characters between the // cursor and the right margin, then DCH only deletes the remaining characters. // As characters are deleted, the remaining characters between the cursor and right margin move to the left. // Character attributes move with the characters. The terminal adds blank spaces with no visual character // attributes at the right margin. DCH has no effect outside the scrolling margins." mAboutToAutoWrap = false; int cellsAfterCursor = mColumns - mCursorCol; int cellsToDelete = Math.min(getArg0(1), cellsAfterCursor); int cellsToMove = cellsAfterCursor - cellsToDelete; mScreen.blockCopy(mCursorCol + cellsToDelete, mCursorRow, cellsToMove, 1, mCursorCol, mCursorRow); blockClear(mCursorCol + cellsToMove, mCursorRow, cellsToDelete); } break; case 'S': { // "${CSI}${N}S" - scroll up ${N} lines (default = 1) (SU). final int linesToScroll = getArg0(1); for (int i = 0; i < linesToScroll; i++) scrollDownOneLine(); break; } case 'T': if (mArgIndex == 0) { // "${CSI}${N}T" - Scroll down N lines (default = 1) (SD). // http://vt100.net/docs/vt510-rm/SD: "N is the number of lines to move the user window up in page // memory. N new lines appear at the top of the display. N old lines disappear at the bottom of the // display. You cannot pan past the top margin of the current page". final int linesToScrollArg = getArg0(1); final int linesBetweenTopAndBottomMargins = mBottomMargin - mTopMargin; final int linesToScroll = Math.min(linesBetweenTopAndBottomMargins, linesToScrollArg); mScreen.blockCopy(0, mTopMargin, mColumns, linesBetweenTopAndBottomMargins - linesToScroll, 0, mTopMargin + linesToScroll); blockClear(0, mTopMargin, mColumns, linesToScroll); } else { // "${CSI}${func};${startx};${starty};${firstrow};${lastrow}T" - initiate highlight mouse tracking. unimplementedSequence(b); } break; case 'X': // "${CSI}${N}X" - Erase ${N:=1} character(s) (ECH). FIXME: Clears character attributes? mAboutToAutoWrap = false; mScreen.blockSet(mCursorCol, mCursorRow, Math.min(getArg0(1), mColumns - mCursorCol), 1, ' ', getStyle()); break; case 'Z': // Cursor Backward Tabulation (CBT). Move the active position n tabs backward. int numberOfTabs = getArg0(1); int newCol = mLeftMargin; for (int i = mCursorCol - 1; i >= 0; i--) if (mTabStop[i]) { if (--numberOfTabs == 0) { newCol = Math.max(i, mLeftMargin); break; } } mCursorCol = newCol; break; case '?': // Esc [ ? -- start of a private mode set continueSequence(ESC_CSI_QUESTIONMARK); break; case '>': // "Esc [ >" -- continueSequence(ESC_CSI_BIGGERTHAN); break; case '`': // Horizontal position absolute (HPA - http://www.vt100.net/docs/vt510-rm/HPA). setCursorColRespectingOriginMode(getArg0(1) - 1); break; case 'b': // Repeat the preceding graphic character Ps times (REP). if (mLastEmittedCodePoint == -1) break; final int numRepeat = getArg0(1); for (int i = 0; i < numRepeat; i++) emitCodePoint(mLastEmittedCodePoint); break; case 'c': // Primary Device Attributes (http://www.vt100.net/docs/vt510-rm/DA1) if argument is missing or zero. // The important part that may still be used by some (tmux stores this value but does not currently use it) // is the first response parameter identifying the terminal service class, where we send 64 for "vt420". // This is followed by a list of attributes which is probably unused by applications. Send like xterm. if (getArg0(0) == 0) mSession.write("\033[?64;1;2;6;9;15;18;21;22c"); break; case 'd': // ESC [ Pn d - Vert Position Absolute setCursorRow(Math.min(Math.max(1, getArg0(1)), mRows) - 1); break; case 'e': // Vertical Position Relative (VPR). From ISO-6429 (ECMA-48). setCursorPosition(mCursorCol, mCursorRow + getArg0(1)); break; // case 'f': "${CSI}${ROW};${COLUMN}f" - Horizontal and Vertical Position (HVP). Grouped with case 'H'. case 'g': // Clear tab stop switch (getArg0(0)) { case 0: mTabStop[mCursorCol] = false; break; case 3: for (int i = 0; i < mColumns; i++) { mTabStop[i] = false; } break; default: // Specified to have no effect. break; } break; case 'h': // Set Mode doSetMode(true); break; case 'l': // Reset Mode doSetMode(false); break; case 'm': // Esc [ Pn m - character attributes. (can have up to 16 numerical arguments) selectGraphicRendition(); break; case 'n': // Esc [ Pn n - ECMA-48 Status Report Commands // sendDeviceAttributes() switch (getArg0(0)) { case 5: // Device status report (DSR): // Answer is ESC [ 0 n (Terminal OK). byte[] dsr = {(byte) 27, (byte) '[', (byte) '0', (byte) 'n'}; mSession.write(dsr, 0, dsr.length); break; case 6: // Cursor position report (CPR): // Answer is ESC [ y ; x R, where x,y is // the cursor location. mSession.write(String.format(Locale.US, "\033[%d;%dR", mCursorRow + 1, mCursorCol + 1)); break; default: break; } break; case 'r': // "CSI${top};${bottom}r" - set top and bottom Margins (DECSTBM). { // https://vt100.net/docs/vt510-rm/DECSTBM.html // The top margin defaults to 1, the bottom margin defaults to mRows. // The escape sequence numbers top 1..23, but we number top 0..22. // The escape sequence numbers bottom 2..24, and so do we (because we use a zero based numbering // scheme, but we store the first line below the bottom-most scrolling line. // As a result, we adjust the top line by -1, but we leave the bottom line alone. // Also require that top + 2 <= bottom. mTopMargin = Math.max(0, Math.min(getArg0(1) - 1, mRows - 2)); mBottomMargin = Math.max(mTopMargin + 2, Math.min(getArg1(mRows), mRows)); // DECSTBM moves the cursor to column 1, line 1 of the page respecting origin mode. setCursorPosition(0, 0); } break; case 's': if (isDecsetInternalBitSet(DECSET_BIT_LEFTRIGHT_MARGIN_MODE)) { // Set left and right margins (DECSLRM - http://www.vt100.net/docs/vt510-rm/DECSLRM). mLeftMargin = Math.min(getArg0(1) - 1, mColumns - 2); mRightMargin = Math.max(mLeftMargin + 1, Math.min(getArg1(mColumns), mColumns)); // DECSLRM moves the cursor to column 1, line 1 of the page. setCursorPosition(0, 0); } else { // Save cursor (ANSI.SYS), available only when DECLRMM is disabled. saveCursor(); } break; case 't': // Window manipulation (from dtterm, as well as extensions) switch (getArg0(0)) { case 11: // Report xterm window state. If the xterm window is open (non-iconified), it returns CSI 1 t . mSession.write("\033[1t"); break; case 13: // Report xterm window position. Result is CSI 3 ; x ; y t mSession.write("\033[3;0;0t"); break; case 14: // Report xterm window in pixels. Result is CSI 4 ; height ; width t // We just report characters time 12 here. mSession.write(String.format(Locale.US, "\033[4;%d;%dt", mRows * 12, mColumns * 12)); break; case 18: // Report the size of the text area in characters. Result is CSI 8 ; height ; width t mSession.write(String.format(Locale.US, "\033[8;%d;%dt", mRows, mColumns)); break; case 19: // Report the size of the screen in characters. Result is CSI 9 ; height ; width t // We report the same size as the view, since it's the view really isn't resizable from the shell. mSession.write(String.format(Locale.US, "\033[9;%d;%dt", mRows, mColumns)); break; case 20: // Report xterm windows icon label. Result is OSC L label ST. Disabled due to security concerns: mSession.write("\033]LIconLabel\033\\"); break; case 21: // Report xterm windows title. Result is OSC l label ST. Disabled due to security concerns: mSession.write("\033]l\033\\"); break; case 22: // 22;0 -> Save xterm icon and window title on stack. // 22;1 -> Save xterm icon title on stack. // 22;2 -> Save xterm window title on stack. mTitleStack.push(mTitle); if (mTitleStack.size() > 20) { // Limit size mTitleStack.remove(0); } break; case 23: // Like 22 above but restore from stack. if (!mTitleStack.isEmpty()) setTitle(mTitleStack.pop()); break; default: // Ignore window manipulation. break; } break; case 'u': // Restore cursor (ANSI.SYS). restoreCursor(); break; case ' ': continueSequence(ESC_CSI_ARGS_SPACE); break; default: parseArg(b); break; } } /** Select Graphic Rendition (SGR) - see http://en.wikipedia.org/wiki/ANSI_escape_code#graphics. */ private void selectGraphicRendition() { if (mArgIndex >= mArgs.length) mArgIndex = mArgs.length - 1; for (int i = 0; i <= mArgIndex; i++) { int code = mArgs[i]; if (code < 0) { if (mArgIndex > 0) { continue; } else { code = 0; } } if (code == 0) { // reset mForeColor = TextStyle.COLOR_INDEX_FOREGROUND; mBackColor = TextStyle.COLOR_INDEX_BACKGROUND; mEffect = 0; } else if (code == 1) { mEffect |= TextStyle.CHARACTER_ATTRIBUTE_BOLD; } else if (code == 2) { mEffect |= TextStyle.CHARACTER_ATTRIBUTE_DIM; } else if (code == 3) { mEffect |= TextStyle.CHARACTER_ATTRIBUTE_ITALIC; } else if (code == 4) { mEffect |= TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE; } else if (code == 5) { mEffect |= TextStyle.CHARACTER_ATTRIBUTE_BLINK; } else if (code == 7) { mEffect |= TextStyle.CHARACTER_ATTRIBUTE_INVERSE; } else if (code == 8) { mEffect |= TextStyle.CHARACTER_ATTRIBUTE_INVISIBLE; } else if (code == 9) { mEffect |= TextStyle.CHARACTER_ATTRIBUTE_STRIKETHROUGH; } else if (code == 10) { // Exit alt charset (TERM=linux) - ignore. } else if (code == 11) { // Enter alt charset (TERM=linux) - ignore. } else if (code == 22) { // Normal color or intensity, neither bright, bold nor faint. mEffect &= ~(TextStyle.CHARACTER_ATTRIBUTE_BOLD | TextStyle.CHARACTER_ATTRIBUTE_DIM); } else if (code == 23) { // not italic, but rarely used as such; clears standout with TERM=screen mEffect &= ~TextStyle.CHARACTER_ATTRIBUTE_ITALIC; } else if (code == 24) { // underline: none mEffect &= ~TextStyle.CHARACTER_ATTRIBUTE_UNDERLINE; } else if (code == 25) { // blink: none mEffect &= ~TextStyle.CHARACTER_ATTRIBUTE_BLINK; } else if (code == 27) { // image: positive mEffect &= ~TextStyle.CHARACTER_ATTRIBUTE_INVERSE; } else if (code == 28) { mEffect &= ~TextStyle.CHARACTER_ATTRIBUTE_INVISIBLE; } else if (code == 29) { mEffect &= ~TextStyle.CHARACTER_ATTRIBUTE_STRIKETHROUGH; } else if (code >= 30 && code <= 37) { mForeColor = code - 30; } else if (code == 38 || code == 48) { // Extended set foreground(38)/background (48) color. // This is followed by either "2;$R;$G;$B" to set a 24-bit color or // "5;$INDEX" to set an indexed color. if (i + 2 > mArgIndex) continue; int firstArg = mArgs[i + 1]; if (firstArg == 2) { if (i + 4 > mArgIndex) { Logger.logWarn(mClient, LOG_TAG, "Too few CSI" + code + ";2 RGB arguments"); } else { int red = mArgs[i + 2], green = mArgs[i + 3], blue = mArgs[i + 4]; if (red < 0 || green < 0 || blue < 0 || red > 255 || green > 255 || blue > 255) { finishSequenceAndLogError("Invalid RGB: " + red + "," + green + "," + blue); } else { int argbColor = 0xff000000 | (red << 16) | (green << 8) | blue; if (code == 38) { mForeColor = argbColor; } else { mBackColor = argbColor; } } i += 4; // "2;P_r;P_g;P_r" } } else if (firstArg == 5) { int color = mArgs[i + 2]; i += 2; // "5;P_s" if (color >= 0 && color < TextStyle.NUM_INDEXED_COLORS) { if (code == 38) { mForeColor = color; } else { mBackColor = color; } } else { if (LOG_ESCAPE_SEQUENCES) Logger.logWarn(mClient, LOG_TAG, "Invalid color index: " + color); } } else { finishSequenceAndLogError("Invalid ISO-8613-3 SGR first argument: " + firstArg); } } else if (code == 39) { // Set default foreground color. mForeColor = TextStyle.COLOR_INDEX_FOREGROUND; } else if (code >= 40 && code <= 47) { // Set background color. mBackColor = code - 40; } else if (code == 49) { // Set default background color. mBackColor = TextStyle.COLOR_INDEX_BACKGROUND; } else if (code >= 90 && code <= 97) { // Bright foreground colors (aixterm codes). mForeColor = code - 90 + 8; } else if (code >= 100 && code <= 107) { // Bright background color (aixterm codes). mBackColor = code - 100 + 8; } else { if (LOG_ESCAPE_SEQUENCES) Logger.logWarn(mClient, LOG_TAG, String.format("SGR unknown code %d", code)); } } } private void doOsc(int b) { switch (b) { case 7: // Bell. doOscSetTextParameters("\007"); break; case 27: // Escape. continueSequence(ESC_OSC_ESC); break; default: collectOSCArgs(b); break; } } private void doOscEsc(int b) { switch (b) { case '\\': doOscSetTextParameters("\033\\"); break; default: // The ESC character was not followed by a \, so insert the ESC and // the current character in arg buffer. collectOSCArgs(27); collectOSCArgs(b); continueSequence(ESC_OSC); break; } } /** An Operating System Controls (OSC) Set Text Parameters. May come here from BEL or ST. */ private void doOscSetTextParameters(String bellOrStringTerminator) { int value = -1; String textParameter = ""; // Extract initial $value from initial "$value;..." string. for (int mOSCArgTokenizerIndex = 0; mOSCArgTokenizerIndex < mOSCOrDeviceControlArgs.length(); mOSCArgTokenizerIndex++) { char b = mOSCOrDeviceControlArgs.charAt(mOSCArgTokenizerIndex); if (b == ';') { textParameter = mOSCOrDeviceControlArgs.substring(mOSCArgTokenizerIndex + 1); break; } else if (b >= '0' && b <= '9') { value = ((value < 0) ? 0 : value * 10) + (b - '0'); } else { unknownSequence(b); return; } } switch (value) { case 0: // Change icon name and window title to T. case 1: // Change icon name to T. case 2: // Change window title to T. setTitle(textParameter); break; case 4: // P s = 4 ; c ; spec → Change Color Number c to the color specified by spec. This can be a name or RGB // specification as per XParseColor. Any number of c name pairs may be given. The color numbers correspond // to the ANSI colors 0-7, their bright versions 8-15, and if supported, the remainder of the 88-color or // 256-color table. // If a "?" is given rather than a name or RGB specification, xterm replies with a control sequence of the // same form which can be used to set the corresponding color. Because more than one pair of color number // and specification can be given in one control sequence, xterm can make more than one reply. int colorIndex = -1; int parsingPairStart = -1; for (int i = 0; ; i++) { boolean endOfInput = i == textParameter.length(); char b = endOfInput ? ';' : textParameter.charAt(i); if (b == ';') { if (parsingPairStart < 0) { parsingPairStart = i + 1; } else { if (colorIndex < 0 || colorIndex > 255) { unknownSequence(b); return; } else { mColors.tryParseColor(colorIndex, textParameter.substring(parsingPairStart, i)); mSession.onColorsChanged(); colorIndex = -1; parsingPairStart = -1; } } } else if (parsingPairStart >= 0) { // We have passed a color index and are now going through color spec. } else if (parsingPairStart < 0 && (b >= '0' && b <= '9')) { colorIndex = ((colorIndex < 0) ? 0 : colorIndex * 10) + (b - '0'); } else { unknownSequence(b); return; } if (endOfInput) break; } break; case 10: // Set foreground color. case 11: // Set background color. case 12: // Set cursor color. int specialIndex = TextStyle.COLOR_INDEX_FOREGROUND + (value - 10); int lastSemiIndex = 0; for (int charIndex = 0; ; charIndex++) { boolean endOfInput = charIndex == textParameter.length(); if (endOfInput || textParameter.charAt(charIndex) == ';') { try { String colorSpec = textParameter.substring(lastSemiIndex, charIndex); if ("?".equals(colorSpec)) { // Report current color in the same format xterm and gnome-terminal does. int rgb = mColors.mCurrentColors[specialIndex]; int r = (65535 * ((rgb & 0x00FF0000) >> 16)) / 255; int g = (65535 * ((rgb & 0x0000FF00) >> 8)) / 255; int b = (65535 * ((rgb & 0x000000FF))) / 255; mSession.write("\033]" + value + ";rgb:" + String.format(Locale.US, "%04x", r) + "/" + String.format(Locale.US, "%04x", g) + "/" + String.format(Locale.US, "%04x", b) + bellOrStringTerminator); } else { mColors.tryParseColor(specialIndex, colorSpec); mSession.onColorsChanged(); } specialIndex++; if (endOfInput || (specialIndex > TextStyle.COLOR_INDEX_CURSOR) || ++charIndex >= textParameter.length()) break; lastSemiIndex = charIndex; } catch (NumberFormatException e) { // Ignore. } } } break; case 52: // Manipulate Selection Data. Skip the optional first selection parameter(s). int startIndex = textParameter.indexOf(";") + 1; try { String clipboardText = new String(Base64.decode(textParameter.substring(startIndex), 0), StandardCharsets.UTF_8); mSession.onCopyTextToClipboard(clipboardText); } catch (Exception e) { Logger.logError(mClient, LOG_TAG, "OSC Manipulate selection, invalid string '" + textParameter + ""); } break; case 104: // "104;$c" → Reset Color Number $c. It is reset to the color specified by the corresponding X // resource. Any number of c parameters may be given. These parameters correspond to the ANSI colors 0-7, // their bright versions 8-15, and if supported, the remainder of the 88-color or 256-color table. If no // parameters are given, the entire table will be reset. if (textParameter.isEmpty()) { mColors.reset(); mSession.onColorsChanged(); } else { int lastIndex = 0; for (int charIndex = 0; ; charIndex++) { boolean endOfInput = charIndex == textParameter.length(); if (endOfInput || textParameter.charAt(charIndex) == ';') { try { int colorToReset = Integer.parseInt(textParameter.substring(lastIndex, charIndex)); mColors.reset(colorToReset); mSession.onColorsChanged(); if (endOfInput) break; charIndex++; lastIndex = charIndex; } catch (NumberFormatException e) { // Ignore. } } } } break; case 110: // Reset foreground color. case 111: // Reset background color. case 112: // Reset cursor color. mColors.reset(TextStyle.COLOR_INDEX_FOREGROUND + (value - 110)); mSession.onColorsChanged(); break; case 119: // Reset highlight color. break; default: unknownParameter(value); break; } finishSequence(); } private void blockClear(int sx, int sy, int w) { blockClear(sx, sy, w, 1); } private void blockClear(int sx, int sy, int w, int h) { mScreen.blockSet(sx, sy, w, h, ' ', getStyle()); } private long getStyle() { return TextStyle.encode(mForeColor, mBackColor, mEffect); } /** "CSI P_m h" for set or "CSI P_m l" for reset ANSI mode. */ private void doSetMode(boolean newValue) { int modeBit = getArg0(0); switch (modeBit) { case 4: // Set="Insert Mode". Reset="Replace Mode". (IRM). mInsertMode = newValue; break; case 20: // Normal Linefeed (LNM). unknownParameter(modeBit); // http://www.vt100.net/docs/vt510-rm/LNM break; case 34: // Normal cursor visibility - when using TERM=screen, see // http://www.gnu.org/software/screen/manual/html_node/Control-Sequences.html break; default: unknownParameter(modeBit); break; } } /** * NOTE: The parameters of this function respect the {@link #DECSET_BIT_ORIGIN_MODE}. Use * {@link #setCursorRowCol(int, int)} for absolute pos. */ private void setCursorPosition(int x, int y) { boolean originMode = isDecsetInternalBitSet(DECSET_BIT_ORIGIN_MODE); int effectiveTopMargin = originMode ? mTopMargin : 0; int effectiveBottomMargin = originMode ? mBottomMargin : mRows; int effectiveLeftMargin = originMode ? mLeftMargin : 0; int effectiveRightMargin = originMode ? mRightMargin : mColumns; int newRow = Math.max(effectiveTopMargin, Math.min(effectiveTopMargin + y, effectiveBottomMargin - 1)); int newCol = Math.max(effectiveLeftMargin, Math.min(effectiveLeftMargin + x, effectiveRightMargin - 1)); setCursorRowCol(newRow, newCol); } private void scrollDownOneLine() { mScrollCounter++; if (mLeftMargin != 0 || mRightMargin != mColumns) { // Horizontal margin: Do not put anything into scroll history, just non-margin part of screen up. mScreen.blockCopy(mLeftMargin, mTopMargin + 1, mRightMargin - mLeftMargin, mBottomMargin - mTopMargin - 1, mLeftMargin, mTopMargin); // .. and blank bottom row between margins: mScreen.blockSet(mLeftMargin, mBottomMargin - 1, mRightMargin - mLeftMargin, 1, ' ', mEffect); } else { mScreen.scrollDownOneLine(mTopMargin, mBottomMargin, getStyle()); } } /** * Process the next ASCII character of a parameter. * * Parameter characters modify the action or interpretation of the sequence. You can use up to * 16 parameters per sequence. You must use the ; character to separate parameters. * All parameters are unsigned, positive decimal integers, with the most significant * digit sent first. Any parameter greater than 9999 (decimal) is set to 9999 * (decimal). If you do not specify a value, a 0 value is assumed. A 0 value * or omitted parameter indicates a default value for the sequence. For most * sequences, the default value is 1. * * https://vt100.net/docs/vt510-rm/chapter4.html#S4.3.3 * */ private void parseArg(int inputByte) { int[] bytes = new int[]{inputByte}; // Only doing this for ESC_CSI and not for other ESC_CSI_* since they seem to be using their // own defaults with getArg*() calls, but there may be missed cases if (mEscapeState == ESC_CSI) { if ((mIsCSIStart && inputByte == ';') || // If sequence starts with a ; character, like \033[;m (!mIsCSIStart && mLastCSIArg != null && mLastCSIArg == ';' && inputByte == ';')) { // If sequence contains sequential ; characters, like \033[;;m bytes = new int[]{'0', ';'}; // Assume 0 was passed } } mIsCSIStart = false; for (int b : bytes) { if (b >= '0' && b <= '9') { if (mArgIndex < mArgs.length) { int oldValue = mArgs[mArgIndex]; int thisDigit = b - '0'; int value; if (oldValue >= 0) { value = oldValue * 10 + thisDigit; } else { value = thisDigit; } if (value > 9999) value = 9999; mArgs[mArgIndex] = value; } continueSequence(mEscapeState); } else if (b == ';') { if (mArgIndex < mArgs.length) { mArgIndex++; } continueSequence(mEscapeState); } else { unknownSequence(b); } mLastCSIArg = b; } } private int getArg0(int defaultValue) { return getArg(0, defaultValue, true); } private int getArg1(int defaultValue) { return getArg(1, defaultValue, true); } private int getArg(int index, int defaultValue, boolean treatZeroAsDefault) { int result = mArgs[index]; if (result < 0 || (result == 0 && treatZeroAsDefault)) { result = defaultValue; } return result; } private void collectOSCArgs(int b) { if (mOSCOrDeviceControlArgs.length() < MAX_OSC_STRING_LENGTH) { mOSCOrDeviceControlArgs.appendCodePoint(b); continueSequence(mEscapeState); } else { unknownSequence(b); } } private void unimplementedSequence(int b) { logError("Unimplemented sequence char '" + (char) b + "' (U+" + String.format("%04x", b) + ")"); finishSequence(); } private void unknownSequence(int b) { logError("Unknown sequence char '" + (char) b + "' (numeric value=" + b + ")"); finishSequence(); } private void unknownParameter(int parameter) { logError("Unknown parameter: " + parameter); finishSequence(); } private void logError(String errorType) { if (LOG_ESCAPE_SEQUENCES) { StringBuilder buf = new StringBuilder(); buf.append(errorType); buf.append(", escapeState="); buf.append(mEscapeState); boolean firstArg = true; if (mArgIndex >= mArgs.length) mArgIndex = mArgs.length - 1; for (int i = 0; i <= mArgIndex; i++) { int value = mArgs[i]; if (value >= 0) { if (firstArg) { firstArg = false; buf.append(", args={"); } else { buf.append(','); } buf.append(value); } } if (!firstArg) buf.append('}'); finishSequenceAndLogError(buf.toString()); } } private void finishSequenceAndLogError(String error) { if (LOG_ESCAPE_SEQUENCES) Logger.logWarn(mClient, LOG_TAG, error); finishSequence(); } private void finishSequence() { mEscapeState = ESC_NONE; } /** * Send a Unicode code point to the screen. * * @param codePoint The code point of the character to display */ private void emitCodePoint(int codePoint) { mLastEmittedCodePoint = codePoint; if (mUseLineDrawingUsesG0 ? mUseLineDrawingG0 : mUseLineDrawingG1) { // http://www.vt100.net/docs/vt102-ug/table5-15.html. switch (codePoint) { case '_': codePoint = ' '; // Blank. break; case '`': codePoint = '◆'; // Diamond. break; case '0': codePoint = '█'; // Solid block; break; case 'a': codePoint = '▒'; // Checker board. break; case 'b': codePoint = '␉'; // Horizontal tab. break; case 'c': codePoint = '␌'; // Form feed. break; case 'd': codePoint = '\r'; // Carriage return. break; case 'e': codePoint = '␊'; // Linefeed. break; case 'f': codePoint = '°'; // Degree. break; case 'g': codePoint = '±'; // Plus-minus. break; case 'h': codePoint = '\n'; // Newline. break; case 'i': codePoint = '␋'; // Vertical tab. break; case 'j': codePoint = '┘'; // Lower right corner. break; case 'k': codePoint = '┐'; // Upper right corner. break; case 'l': codePoint = '┌'; // Upper left corner. break; case 'm': codePoint = '└'; // Left left corner. break; case 'n': codePoint = '┼'; // Crossing lines. break; case 'o': codePoint = '⎺'; // Horizontal line - scan 1. break; case 'p': codePoint = '⎻'; // Horizontal line - scan 3. break; case 'q': codePoint = '─'; // Horizontal line - scan 5. break; case 'r': codePoint = '⎼'; // Horizontal line - scan 7. break; case 's': codePoint = '⎽'; // Horizontal line - scan 9. break; case 't': codePoint = '├'; // T facing rightwards. break; case 'u': codePoint = '┤'; // T facing leftwards. break; case 'v': codePoint = '┴'; // T facing upwards. break; case 'w': codePoint = '┬'; // T facing downwards. break; case 'x': codePoint = '│'; // Vertical line. break; case 'y': codePoint = '≤'; // Less than or equal to. break; case 'z': codePoint = '≥'; // Greater than or equal to. break; case '{': codePoint = 'π'; // Pi. break; case '|': codePoint = '≠'; // Not equal to. break; case '}': codePoint = '£'; // UK pound. break; case '~': codePoint = '·'; // Centered dot. break; } } final boolean autoWrap = isDecsetInternalBitSet(DECSET_BIT_AUTOWRAP); final int displayWidth = WcWidth.width(codePoint); final boolean cursorInLastColumn = mCursorCol == mRightMargin - 1; if (autoWrap) { if (cursorInLastColumn && ((mAboutToAutoWrap && displayWidth == 1) || displayWidth == 2)) { mScreen.setLineWrap(mCursorRow); mCursorCol = mLeftMargin; if (mCursorRow + 1 < mBottomMargin) { mCursorRow++; } else { scrollDownOneLine(); } } } else if (cursorInLastColumn && displayWidth == 2) { // The behaviour when a wide character is output with cursor in the last column when // autowrap is disabled is not obvious - it's ignored here. return; } if (mInsertMode && displayWidth > 0) { // Move character to right one space. int destCol = mCursorCol + displayWidth; if (destCol < mRightMargin) mScreen.blockCopy(mCursorCol, mCursorRow, mRightMargin - destCol, 1, destCol, mCursorRow); } int offsetDueToCombiningChar = ((displayWidth <= 0 && mCursorCol > 0 && !mAboutToAutoWrap) ? 1 : 0); int column = mCursorCol - offsetDueToCombiningChar; // Fix TerminalRow.setChar() ArrayIndexOutOfBoundsException index=-1 exception reported // The offsetDueToCombiningChar would never be 1 if mCursorCol was 0 to get column/index=-1, // so was mCursorCol changed after the offsetDueToCombiningChar conditional by another thread? // TODO: Check if there are thread synchronization issues with mCursorCol and mCursorRow, possibly causing others bugs too. if (column < 0) column = 0; mScreen.setChar(column, mCursorRow, codePoint, getStyle()); if (autoWrap && displayWidth > 0) mAboutToAutoWrap = (mCursorCol == mRightMargin - displayWidth); mCursorCol = Math.min(mCursorCol + displayWidth, mRightMargin - 1); } private void setCursorRow(int row) { mCursorRow = row; mAboutToAutoWrap = false; } private void setCursorCol(int col) { mCursorCol = col; mAboutToAutoWrap = false; } /** Set the cursor mode, but limit it to margins if {@link #DECSET_BIT_ORIGIN_MODE} is enabled. */ private void setCursorColRespectingOriginMode(int col) { setCursorPosition(col, mCursorRow); } /** TODO: Better name, distinguished from {@link #setCursorPosition(int, int)} by not regarding origin mode. */ private void setCursorRowCol(int row, int col) { mCursorRow = Math.max(0, Math.min(row, mRows - 1)); mCursorCol = Math.max(0, Math.min(col, mColumns - 1)); mAboutToAutoWrap = false; } public int getScrollCounter() { return mScrollCounter; } public void clearScrollCounter() { mScrollCounter = 0; } public boolean isAutoScrollDisabled() { return mAutoScrollDisabled; } public void toggleAutoScrollDisabled() { mAutoScrollDisabled = !mAutoScrollDisabled; } /** Reset terminal state so user can interact with it regardless of present state. */ public void reset() { setCursorStyle(); mArgIndex = 0; mContinueSequence = false; mEscapeState = ESC_NONE; mInsertMode = false; mTopMargin = mLeftMargin = 0; mBottomMargin = mRows; mRightMargin = mColumns; mAboutToAutoWrap = false; mForeColor = mSavedStateMain.mSavedForeColor = mSavedStateAlt.mSavedForeColor = TextStyle.COLOR_INDEX_FOREGROUND; mBackColor = mSavedStateMain.mSavedBackColor = mSavedStateAlt.mSavedBackColor = TextStyle.COLOR_INDEX_BACKGROUND; setDefaultTabStops(); mUseLineDrawingG0 = mUseLineDrawingG1 = false; mUseLineDrawingUsesG0 = true; mSavedStateMain.mSavedCursorRow = mSavedStateMain.mSavedCursorCol = mSavedStateMain.mSavedEffect = mSavedStateMain.mSavedDecFlags = 0; mSavedStateAlt.mSavedCursorRow = mSavedStateAlt.mSavedCursorCol = mSavedStateAlt.mSavedEffect = mSavedStateAlt.mSavedDecFlags = 0; mCurrentDecSetFlags = 0; // Initial wrap-around is not accurate but makes terminal more useful, especially on a small screen: setDecsetinternalBit(DECSET_BIT_AUTOWRAP, true); setDecsetinternalBit(DECSET_BIT_CURSOR_ENABLED, true); mSavedDecSetFlags = mSavedStateMain.mSavedDecFlags = mSavedStateAlt.mSavedDecFlags = mCurrentDecSetFlags; // XXX: Should we set terminal driver back to IUTF8 with termios? mUtf8Index = mUtf8ToFollow = 0; mColors.reset(); mSession.onColorsChanged(); } public String getSelectedText(int x1, int y1, int x2, int y2) { return mScreen.getSelectedText(x1, y1, x2, y2); } /** Get the terminal session's title (null if not set). */ public String getTitle() { return mTitle; } /** Change the terminal session's title. */ private void setTitle(String newTitle) { String oldTitle = mTitle; mTitle = newTitle; if (!Objects.equals(oldTitle, newTitle)) { mSession.titleChanged(oldTitle, newTitle); } } /** If DECSET 2004 is set, prefix paste with "\033[200~" and suffix with "\033[201~". */ public void paste(String text) { // First: Always remove escape key and C1 control characters [0x80,0x9F]: text = text.replaceAll("(\u001B|[\u0080-\u009F])", ""); // Second: Replace all newlines (\n) or CRLF (\r\n) with carriage returns (\r). text = text.replaceAll("\r?\n", "\r"); // Then: Implement bracketed paste mode if enabled: boolean bracketed = isDecsetInternalBitSet(DECSET_BIT_BRACKETED_PASTE_MODE); if (bracketed) mSession.write("\033[200~"); mSession.write(text); if (bracketed) mSession.write("\033[201~"); } /** http://www.vt100.net/docs/vt510-rm/DECSC */ static final class SavedScreenState { /** Saved state of the cursor position, Used to implement the save/restore cursor position escape sequences. */ int mSavedCursorRow, mSavedCursorCol; int mSavedEffect, mSavedForeColor, mSavedBackColor; int mSavedDecFlags; boolean mUseLineDrawingG0, mUseLineDrawingG1, mUseLineDrawingUsesG0 = true; } @Override public String toString() { return "TerminalEmulator[size=" + mScreen.mColumns + "x" + mScreen.mScreenRows + ", margins={" + mTopMargin + "," + mRightMargin + "," + mBottomMargin + "," + mLeftMargin + "}]"; } }
erma0/ZeroTermux
terminal-emulator/src/main/java/com/termux/terminal/TerminalEmulator.java
41,700
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.partialresponse; /** * {@link Video} is a entity to serve from server.It contains all video related information. * Video is a record class. */ public record Video(Integer id, String title, Integer length, String description, String director, String language) { /** * ToString. * * @return json representation of video */ @Override public String toString() { return "{" + "\"id\": " + id + "," + "\"title\": \"" + title + "\"," + "\"length\": " + length + "," + "\"description\": \"" + description + "\"," + "\"director\": \"" + director + "\"," + "\"language\": \"" + language + "\"," + "}"; } }
rajprins/java-design-patterns
partial-response/src/main/java/com/iluwatar/partialresponse/Video.java
41,701
package org.jsoup.parser; import org.jsoup.helper.Validate; import org.jsoup.internal.Normalizer; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; /** * Tag capabilities. * * @author Jonathan Hedley, [email protected] */ public class Tag implements Cloneable { private static final Map<String, Tag> Tags = new HashMap<>(); // map of known tags private String tagName; private final String normalName; // always the lower case version of this tag, regardless of case preservation mode private String namespace; private boolean isBlock = true; // block private boolean formatAsBlock = true; // should be formatted as a block private boolean empty = false; // can hold nothing; e.g. img private boolean selfClosing = false; // can self close (<foo />). used for unknown tags that self close, without forcing them as empty. private boolean preserveWhitespace = false; // for pre, textarea, script etc private boolean formList = false; // a control that appears in forms: input, textarea, output etc private boolean formSubmit = false; // a control that can be submitted in a form: input etc private Tag(String tagName, String namespace) { this.tagName = tagName; normalName = Normalizer.lowerCase(tagName); this.namespace = namespace; } /** * Get this tag's name. * * @return the tag's name */ public String getName() { return tagName; } /** * Get this tag's normalized (lowercased) name. * @return the tag's normal name. */ public String normalName() { return normalName; } public String namespace() { return namespace; } /** * Get a Tag by name. If not previously defined (unknown), returns a new generic tag, that can do anything. * <p> * Pre-defined tags (p, div etc) will be ==, but unknown tags are not registered and will only .equals(). * </p> * * @param tagName Name of tag, e.g. "p". Case-insensitive. * @param namespace the namespace for the tag. * @param settings used to control tag name sensitivity * @return The tag, either defined or new generic. */ public static Tag valueOf(String tagName, String namespace, ParseSettings settings) { Validate.notEmpty(tagName); Validate.notNull(namespace); Tag tag = Tags.get(tagName); if (tag != null && tag.namespace.equals(namespace)) return tag; tagName = settings.normalizeTag(tagName); // the name we'll use Validate.notEmpty(tagName); String normalName = Normalizer.lowerCase(tagName); // the lower-case name to get tag settings off tag = Tags.get(normalName); if (tag != null && tag.namespace.equals(namespace)) { if (settings.preserveTagCase() && !tagName.equals(normalName)) { tag = tag.clone(); // get a new version vs the static one, so name update doesn't reset all tag.tagName = tagName; } return tag; } // not defined: create default; go anywhere, do anything! (incl be inside a <p>) tag = new Tag(tagName, namespace); tag.isBlock = false; return tag; } /** * Get a Tag by name. If not previously defined (unknown), returns a new generic tag, that can do anything. * <p> * Pre-defined tags (P, DIV etc) will be ==, but unknown tags are not registered and will only .equals(). * </p> * * @param tagName Name of tag, e.g. "p". <b>Case sensitive</b>. * @return The tag, either defined or new generic. * @see #valueOf(String tagName, String namespace, ParseSettings settings) */ public static Tag valueOf(String tagName) { return valueOf(tagName, Parser.NamespaceHtml, ParseSettings.preserveCase); } /** * Get a Tag by name. If not previously defined (unknown), returns a new generic tag, that can do anything. * <p> * Pre-defined tags (P, DIV etc) will be ==, but unknown tags are not registered and will only .equals(). * </p> * * @param tagName Name of tag, e.g. "p". <b>Case sensitive</b>. * @param settings used to control tag name sensitivity * @return The tag, either defined or new generic. * @see #valueOf(String tagName, String namespace, ParseSettings settings) */ public static Tag valueOf(String tagName, ParseSettings settings) { return valueOf(tagName, Parser.NamespaceHtml, settings); } /** * Gets if this is a block tag. * * @return if block tag */ public boolean isBlock() { return isBlock; } /** * Gets if this tag should be formatted as a block (or as inline) * * @return if should be formatted as block or inline */ public boolean formatAsBlock() { return formatAsBlock; } /** * Gets if this tag is an inline tag. * * @return if this tag is an inline tag. */ public boolean isInline() { return !isBlock; } /** * Get if this is an empty tag * * @return if this is an empty tag */ public boolean isEmpty() { return empty; } /** * Get if this tag is self-closing. * * @return if this tag should be output as self-closing. */ public boolean isSelfClosing() { return empty || selfClosing; } /** * Get if this is a pre-defined tag, or was auto created on parsing. * * @return if a known tag */ public boolean isKnownTag() { return Tags.containsKey(tagName); } /** * Check if this tagname is a known tag. * * @param tagName name of tag * @return if known HTML tag */ public static boolean isKnownTag(String tagName) { return Tags.containsKey(tagName); } /** * Get if this tag should preserve whitespace within child text nodes. * * @return if preserve whitespace */ public boolean preserveWhitespace() { return preserveWhitespace; } /** * Get if this tag represents a control associated with a form. E.g. input, textarea, output * @return if associated with a form */ public boolean isFormListed() { return formList; } /** * Get if this tag represents an element that should be submitted with a form. E.g. input, option * @return if submittable with a form */ public boolean isFormSubmittable() { return formSubmit; } Tag setSelfClosing() { selfClosing = true; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Tag)) return false; Tag tag = (Tag) o; if (!tagName.equals(tag.tagName)) return false; if (empty != tag.empty) return false; if (formatAsBlock != tag.formatAsBlock) return false; if (isBlock != tag.isBlock) return false; if (preserveWhitespace != tag.preserveWhitespace) return false; if (selfClosing != tag.selfClosing) return false; if (formList != tag.formList) return false; return formSubmit == tag.formSubmit; } @Override public int hashCode() { int result = tagName.hashCode(); result = 31 * result + (isBlock ? 1 : 0); result = 31 * result + (formatAsBlock ? 1 : 0); result = 31 * result + (empty ? 1 : 0); result = 31 * result + (selfClosing ? 1 : 0); result = 31 * result + (preserveWhitespace ? 1 : 0); result = 31 * result + (formList ? 1 : 0); result = 31 * result + (formSubmit ? 1 : 0); return result; } @Override public String toString() { return tagName; } @Override protected Tag clone() { try { return (Tag) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } // internal static initialisers: // prepped from http://www.w3.org/TR/REC-html40/sgml/dtd.html and other sources private static final String[] blockTags = { "html", "head", "body", "frameset", "script", "noscript", "style", "meta", "link", "title", "frame", "noframes", "section", "nav", "aside", "hgroup", "header", "footer", "p", "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "pre", "div", "blockquote", "hr", "address", "figure", "figcaption", "form", "fieldset", "ins", "del", "dl", "dt", "dd", "li", "table", "caption", "thead", "tfoot", "tbody", "colgroup", "col", "tr", "th", "td", "video", "audio", "canvas", "details", "menu", "plaintext", "template", "article", "main", "svg", "math", "center", "template", "dir", "applet", "marquee", "listing" // deprecated but still known / special handling }; private static final String[] inlineTags = { "object", "base", "font", "tt", "i", "b", "u", "big", "small", "em", "strong", "dfn", "code", "samp", "kbd", "var", "cite", "abbr", "time", "acronym", "mark", "ruby", "rt", "rp", "rtc", "a", "img", "br", "wbr", "map", "q", "sub", "sup", "bdo", "iframe", "embed", "span", "input", "select", "textarea", "label", "button", "optgroup", "option", "legend", "datalist", "keygen", "output", "progress", "meter", "area", "param", "source", "track", "summary", "command", "device", "area", "basefont", "bgsound", "menuitem", "param", "source", "track", "data", "bdi", "s", "strike", "nobr", "rb", // deprecated but still known / special handling "text", // in SVG NS "mi", "mo", "msup", "mn", "mtext" // in MathML NS, to ensure inline }; private static final String[] emptyTags = { "meta", "link", "base", "frame", "img", "br", "wbr", "embed", "hr", "input", "keygen", "col", "command", "device", "area", "basefont", "bgsound", "menuitem", "param", "source", "track" }; // todo - rework this to format contents as inline; and update html emitter in Element. Same output, just neater. private static final String[] formatAsInlineTags = { "title", "a", "p", "h1", "h2", "h3", "h4", "h5", "h6", "pre", "address", "li", "th", "td", "script", "style", "ins", "del", "s" }; private static final String[] preserveWhitespaceTags = { "pre", "plaintext", "title", "textarea" // script is not here as it is a data node, which always preserve whitespace }; // todo: I think we just need submit tags, and can scrub listed private static final String[] formListedTags = { "button", "fieldset", "input", "keygen", "object", "output", "select", "textarea" }; private static final String[] formSubmitTags = { "input", "keygen", "object", "select", "textarea" }; private static final Map<String, String[]> namespaces = new HashMap<>(); static { namespaces.put(Parser.NamespaceMathml, new String[]{"math", "mi", "mo", "msup", "mn", "mtext"}); namespaces.put(Parser.NamespaceSvg, new String[]{"svg", "text"}); // We don't need absolute coverage here as other cases will be inferred by the HtmlTreeBuilder } private static void setupTags(String[] tagNames, Consumer<Tag> tagModifier) { for (String tagName : tagNames) { Tag tag = Tags.get(tagName); if (tag == null) { tag = new Tag(tagName, Parser.NamespaceHtml); Tags.put(tag.tagName, tag); } tagModifier.accept(tag); } } static { setupTags(blockTags, tag -> { tag.isBlock = true; tag.formatAsBlock = true; }); setupTags(inlineTags, tag -> { tag.isBlock = false; tag.formatAsBlock = false; }); setupTags(emptyTags, tag -> tag.empty = true); setupTags(formatAsInlineTags, tag -> tag.formatAsBlock = false); setupTags(preserveWhitespaceTags, tag -> tag.preserveWhitespace = true); setupTags(formListedTags, tag -> tag.formList = true); setupTags(formSubmitTags, tag -> tag.formSubmit = true); for (Map.Entry<String, String[]> ns : namespaces.entrySet()) { setupTags(ns.getValue(), tag -> tag.namespace = ns.getKey()); } } }
jhy/jsoup
src/main/java/org/jsoup/parser/Tag.java
41,702
module org.bytedeco.javacv { exports org.bytedeco.javacv; requires java.desktop; requires javafx.graphics; requires transitive org.bytedeco.javacpp; requires org.bytedeco.opencv; requires org.bytedeco.ffmpeg; requires org.bytedeco.flycapture; requires org.bytedeco.libdc1394; requires org.bytedeco.libfreenect; requires org.bytedeco.libfreenect2; requires org.bytedeco.librealsense; requires org.bytedeco.librealsense2; requires org.bytedeco.videoinput; requires org.bytedeco.artoolkitplus; // requires org.bytedeco.flandmark; requires org.bytedeco.leptonica; requires org.bytedeco.tesseract; }
bytedeco/javacv
src/main/java9/module-info.java
41,703
/* * This is the source code of Telegram for Android v. 1.3.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-2018. */ package org.telegram.messenger; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.BlendMode; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.ComposeShader; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.view.View; import androidx.annotation.Keep; import com.google.android.exoplayer2.util.Log; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import org.telegram.ui.Components.AnimatedFileDrawable; import org.telegram.ui.Components.AttachableDrawable; import org.telegram.ui.Components.AvatarDrawable; import org.telegram.ui.Components.ClipRoundedDrawable; import org.telegram.ui.Components.CubicBezierInterpolator; import org.telegram.ui.Components.LoadingStickerDrawable; import org.telegram.ui.Components.RLottieDrawable; import org.telegram.ui.Components.RecyclableDrawable; import org.telegram.ui.Components.VectorAvatarThumbDrawable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ImageReceiver implements NotificationCenter.NotificationCenterDelegate { List<ImageReceiver> preloadReceivers; private boolean allowCrossfadeWithImage = true; private boolean allowDrawWhileCacheGenerating; private ArrayList<Decorator> decorators; public boolean updateThumbShaderMatrix() { if (currentThumbDrawable != null && thumbShader != null) { drawDrawable(null, currentThumbDrawable, 255, thumbShader, 0, 0, 0, null); return true; } if (staticThumbDrawable != null && staticThumbShader != null) { drawDrawable(null, staticThumbDrawable, 255, staticThumbShader, 0, 0, 0, null); return true; } return false; } public void setPreloadingReceivers(List<ImageReceiver> preloadReceivers) { this.preloadReceivers = preloadReceivers; } public Drawable getImageDrawable() { return currentImageDrawable; } public Drawable getMediaDrawable() { return currentMediaDrawable; } public void updateStaticDrawableThump(Bitmap bitmap) { staticThumbShader = null; roundPaint.setShader(null); setStaticDrawable(new BitmapDrawable(bitmap)); } public void setAllowDrawWhileCacheGenerating(boolean allow) { allowDrawWhileCacheGenerating = allow; } public interface ImageReceiverDelegate { void didSetImage(ImageReceiver imageReceiver, boolean set, boolean thumb, boolean memCache); default void onAnimationReady(ImageReceiver imageReceiver) { } default void didSetImageBitmap(int type, String key, Drawable drawable) { } } public static class BitmapHolder { private String key; private boolean recycleOnRelease; public Bitmap bitmap; public Drawable drawable; public int orientation; public BitmapHolder(Bitmap b, String k, int o) { bitmap = b; key = k; orientation = o; if (key != null) { ImageLoader.getInstance().incrementUseCount(key); } } public BitmapHolder(Drawable d, String k, int o) { drawable = d; key = k; orientation = o; if (key != null) { ImageLoader.getInstance().incrementUseCount(key); } } public BitmapHolder(Bitmap b) { bitmap = b; recycleOnRelease = true; } public String getKey() { return key; } public int getWidth() { return bitmap != null ? bitmap.getWidth() : 0; } public int getHeight() { return bitmap != null ? bitmap.getHeight() : 0; } public boolean isRecycled() { return bitmap == null || bitmap.isRecycled(); } public void release() { if (key == null) { if (recycleOnRelease && bitmap != null) { bitmap.recycle(); } bitmap = null; drawable = null; return; } boolean canDelete = ImageLoader.getInstance().decrementUseCount(key); if (!ImageLoader.getInstance().isInMemCache(key, false)) { if (canDelete) { if (bitmap != null) { bitmap.recycle(); } else if (drawable != null) { if (drawable instanceof RLottieDrawable) { RLottieDrawable fileDrawable = (RLottieDrawable) drawable; fileDrawable.recycle(false); } else if (drawable instanceof AnimatedFileDrawable) { AnimatedFileDrawable fileDrawable = (AnimatedFileDrawable) drawable; fileDrawable.recycle(); } else if (drawable instanceof BitmapDrawable) { Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap(); bitmap.recycle(); } } } } key = null; bitmap = null; drawable = null; } } private static class SetImageBackup { public ImageLocation imageLocation; public String imageFilter; public ImageLocation thumbLocation; public String thumbFilter; public ImageLocation mediaLocation; public String mediaFilter; public Drawable thumb; public long size; public int cacheType; public Object parentObject; public String ext; private boolean isSet() { return imageLocation != null || thumbLocation != null || mediaLocation != null || thumb != null; } private boolean isWebfileSet() { return imageLocation != null && (imageLocation.webFile != null || imageLocation.path != null) || thumbLocation != null && (thumbLocation.webFile != null || thumbLocation.path != null) || mediaLocation != null && (mediaLocation.webFile != null || mediaLocation.path != null); } private void clear() { imageLocation = null; thumbLocation = null; mediaLocation = null; thumb = null; } } public final static int TYPE_IMAGE = 0; public final static int TYPE_THUMB = 1; private final static int TYPE_CROSSFDADE = 2; public final static int TYPE_MEDIA = 3; public final static int DEFAULT_CROSSFADE_DURATION = 150; private int currentAccount; private View parentView; private int param; private Object currentParentObject; private boolean canceledLoading; private static PorterDuffColorFilter selectedColorFilter = new PorterDuffColorFilter(0xffdddddd, PorterDuff.Mode.MULTIPLY); private static PorterDuffColorFilter selectedGroupColorFilter = new PorterDuffColorFilter(0xffbbbbbb, PorterDuff.Mode.MULTIPLY); private boolean forceLoding; private long currentTime; private int fileLoadingPriority = FileLoader.PRIORITY_NORMAL; private int currentLayerNum; public boolean ignoreNotifications; private int currentOpenedLayerFlags; private int isLastFrame; private SetImageBackup setImageBackup; private Object blendMode; private Bitmap gradientBitmap; private BitmapShader gradientShader; private ComposeShader composeShader; private Bitmap legacyBitmap; private BitmapShader legacyShader; private Canvas legacyCanvas; private Paint legacyPaint; private ImageLocation strippedLocation; private ImageLocation currentImageLocation; private String currentImageFilter; private String currentImageKey; private int imageTag; private Drawable currentImageDrawable; private BitmapShader imageShader; protected int imageOrientation, imageInvert; private ImageLocation currentThumbLocation; private String currentThumbFilter; private String currentThumbKey; private int thumbTag; private Drawable currentThumbDrawable; public BitmapShader thumbShader; public BitmapShader staticThumbShader; private int thumbOrientation, thumbInvert; private ImageLocation currentMediaLocation; private String currentMediaFilter; private String currentMediaKey; private int mediaTag; private Drawable currentMediaDrawable; private BitmapShader mediaShader; private boolean useRoundForThumb = true; private Drawable staticThumbDrawable; private String currentExt; private boolean ignoreImageSet; private int currentGuid; private long currentSize; private int currentCacheType; private boolean allowLottieVibration = true; private boolean allowStartAnimation = true; private boolean allowStartLottieAnimation = true; private boolean useSharedAnimationQueue; private boolean allowDecodeSingleFrame; private int autoRepeat = 1; private int autoRepeatCount = -1; private long autoRepeatTimeout; private boolean animationReadySent; private boolean crossfadeWithOldImage; private boolean crossfadingWithThumb; private Drawable crossfadeImage; private String crossfadeKey; private BitmapShader crossfadeShader; private boolean needsQualityThumb; private boolean shouldGenerateQualityThumb; private TLRPC.Document qulityThumbDocument; private boolean currentKeyQuality; private boolean invalidateAll; private float imageX, imageY, imageW, imageH; private float sideClip; private final RectF drawRegion = new RectF(); private boolean isVisible = true; private boolean isAspectFit; private boolean forcePreview; private boolean forceCrossfade; private final int[] roundRadius = new int[4]; private boolean isRoundRect = true; private Object mark; private Paint roundPaint; private final RectF roundRect = new RectF(); private final Matrix shaderMatrix = new Matrix(); private final Path roundPath = new Path(); private static final float[] radii = new float[8]; private float overrideAlpha = 1.0f; private int isPressed; private boolean centerRotation; private ImageReceiverDelegate delegate; private float currentAlpha; private float previousAlpha = 1f; private long lastUpdateAlphaTime; private byte crossfadeAlpha = 1; private boolean manualAlphaAnimator; private boolean crossfadeWithThumb; private float crossfadeByScale = .05f; private ColorFilter colorFilter; private boolean isRoundVideo; private long startTime; private long endTime; private int crossfadeDuration = DEFAULT_CROSSFADE_DURATION; private float pressedProgress; private int animateFromIsPressed; private String uniqKeyPrefix; private ArrayList<Runnable> loadingOperations = new ArrayList<>(); private boolean attachedToWindow; private boolean videoThumbIsSame; private boolean allowLoadingOnAttachedOnly = false; private boolean skipUpdateFrame; public boolean clip = true; public int animatedFileDrawableRepeatMaxCount; public ImageReceiver() { this(null); } public ImageReceiver(View view) { parentView = view; roundPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); currentAccount = UserConfig.selectedAccount; } public void cancelLoadImage() { forceLoding = false; ImageLoader.getInstance().cancelLoadingForImageReceiver(this, true); canceledLoading = true; } public void setForceLoading(boolean value) { forceLoding = value; } public boolean isForceLoding() { return forceLoding; } public void setStrippedLocation(ImageLocation location) { strippedLocation = location; } public void setIgnoreImageSet(boolean value) { ignoreImageSet = value; } public ImageLocation getStrippedLocation() { return strippedLocation; } public void setImage(ImageLocation imageLocation, String imageFilter, Drawable thumb, String ext, Object parentObject, int cacheType) { setImage(imageLocation, imageFilter, null, null, thumb, 0, ext, parentObject, cacheType); } public void setImage(ImageLocation imageLocation, String imageFilter, Drawable thumb, long size, String ext, Object parentObject, int cacheType) { setImage(imageLocation, imageFilter, null, null, thumb, size, ext, parentObject, cacheType); } public void setImage(String imagePath, String imageFilter, Drawable thumb, String ext, long size) { setImage(ImageLocation.getForPath(imagePath), imageFilter, null, null, thumb, size, ext, null, 1); } public void setImage(ImageLocation imageLocation, String imageFilter, ImageLocation thumbLocation, String thumbFilter, String ext, Object parentObject, int cacheType) { setImage(imageLocation, imageFilter, thumbLocation, thumbFilter, null, 0, ext, parentObject, cacheType); } public void setImage(ImageLocation imageLocation, String imageFilter, ImageLocation thumbLocation, String thumbFilter, long size, String ext, Object parentObject, int cacheType) { setImage(imageLocation, imageFilter, thumbLocation, thumbFilter, null, size, ext, parentObject, cacheType); } public void setForUserOrChat(TLObject object, Drawable avatarDrawable) { setForUserOrChat(object, avatarDrawable, null); } public void setForUserOrChat(TLObject object, Drawable avatarDrawable, Object parentObject) { setForUserOrChat(object, avatarDrawable, parentObject, false, 0, false); } public void setForUserOrChat(TLObject object, Drawable avatarDrawable, Object parentObject, boolean animationEnabled, int vectorType, boolean big) { if (parentObject == null) { parentObject = object; } setUseRoundForThumbDrawable(true); BitmapDrawable strippedBitmap = null; boolean hasStripped = false; ImageLocation videoLocation = null; TLRPC.VideoSize vectorImageMarkup = null; boolean isPremium = false; if (object instanceof TLRPC.User) { TLRPC.User user = (TLRPC.User) object; isPremium = user.premium; if (user.photo != null) { strippedBitmap = user.photo.strippedBitmap; hasStripped = user.photo.stripped_thumb != null; if (vectorType == VectorAvatarThumbDrawable.TYPE_STATIC) { final TLRPC.UserFull userFull = MessagesController.getInstance(currentAccount).getUserFull(user.id); if (userFull != null) { TLRPC.Photo photo = user.photo.personal ? userFull.personal_photo : userFull.profile_photo; if (photo != null) { vectorImageMarkup = FileLoader.getVectorMarkupVideoSize(photo); } } } if (vectorImageMarkup == null && animationEnabled && MessagesController.getInstance(currentAccount).isPremiumUser(user) && user.photo.has_video && LiteMode.isEnabled(LiteMode.FLAG_AUTOPLAY_VIDEOS)) { final TLRPC.UserFull userFull = MessagesController.getInstance(currentAccount).getUserFull(user.id); if (userFull == null) { MessagesController.getInstance(currentAccount).loadFullUser(user, currentGuid, false); } else { TLRPC.Photo photo = user.photo.personal ? userFull.personal_photo : userFull.profile_photo; if (photo != null) { vectorImageMarkup = FileLoader.getVectorMarkupVideoSize(photo); if (vectorImageMarkup == null) { ArrayList<TLRPC.VideoSize> videoSizes = photo.video_sizes; if (videoSizes != null && !videoSizes.isEmpty()) { TLRPC.VideoSize videoSize = FileLoader.getClosestVideoSizeWithSize(videoSizes, 100); for (int i = 0; i < videoSizes.size(); i++) { TLRPC.VideoSize videoSize1 = videoSizes.get(i); if ("p".equals(videoSize1.type)) { videoSize = videoSize1; } if (videoSize1 instanceof TLRPC.TL_videoSizeEmojiMarkup || videoSize1 instanceof TLRPC.TL_videoSizeStickerMarkup) { vectorImageMarkup = videoSize1; } } videoLocation = ImageLocation.getForPhoto(videoSize, photo); } } } } } } } else if (object instanceof TLRPC.Chat) { TLRPC.Chat chat = (TLRPC.Chat) object; if (chat.photo != null) { strippedBitmap = chat.photo.strippedBitmap; hasStripped = chat.photo.stripped_thumb != null; } } if (vectorImageMarkup != null && vectorType != 0) { VectorAvatarThumbDrawable drawable = new VectorAvatarThumbDrawable(vectorImageMarkup, isPremium, vectorType); setImageBitmap(drawable); } else { ImageLocation location; String filter; if (!big) { location = ImageLocation.getForUserOrChat(object, ImageLocation.TYPE_SMALL); filter = "50_50"; } else { location = ImageLocation.getForUserOrChat(object, ImageLocation.TYPE_BIG); filter = "100_100"; } if (videoLocation != null) { setImage(videoLocation, "avatar", location, filter, null, null, strippedBitmap, 0, null, parentObject, 0); animatedFileDrawableRepeatMaxCount = 3; } else { if (strippedBitmap != null) { setImage(location, filter, strippedBitmap, null, parentObject, 0); } else if (hasStripped) { setImage(location, filter, ImageLocation.getForUserOrChat(object, ImageLocation.TYPE_STRIPPED), "50_50_b", avatarDrawable, parentObject, 0); } else { setImage(location, filter, avatarDrawable, null, parentObject, 0); } } } } public void setImage(ImageLocation fileLocation, String fileFilter, ImageLocation thumbLocation, String thumbFilter, Drawable thumb, Object parentObject, int cacheType) { setImage(null, null, fileLocation, fileFilter, thumbLocation, thumbFilter, thumb, 0, null, parentObject, cacheType); } public void setImage(ImageLocation fileLocation, String fileFilter, ImageLocation thumbLocation, String thumbFilter, Drawable thumb, long size, String ext, Object parentObject, int cacheType) { setImage(null, null, fileLocation, fileFilter, thumbLocation, thumbFilter, thumb, size, ext, parentObject, cacheType); } public void setImage(ImageLocation mediaLocation, String mediaFilter, ImageLocation imageLocation, String imageFilter, ImageLocation thumbLocation, String thumbFilter, Drawable thumb, long size, String ext, Object parentObject, int cacheType) { if (allowLoadingOnAttachedOnly && !attachedToWindow) { if (setImageBackup == null) { setImageBackup = new SetImageBackup(); } setImageBackup.mediaLocation = mediaLocation; setImageBackup.mediaFilter = mediaFilter; setImageBackup.imageLocation = imageLocation; setImageBackup.imageFilter = imageFilter; setImageBackup.thumbLocation = thumbLocation; setImageBackup.thumbFilter = thumbFilter; setImageBackup.thumb = thumb; setImageBackup.size = size; setImageBackup.ext = ext; setImageBackup.cacheType = cacheType; setImageBackup.parentObject = parentObject; return; } if (ignoreImageSet) { return; } if (crossfadeWithOldImage && setImageBackup != null && setImageBackup.isWebfileSet()) { setBackupImage(); } if (setImageBackup != null) { setImageBackup.clear(); } if (imageLocation == null && thumbLocation == null && mediaLocation == null) { for (int a = 0; a < 4; a++) { recycleBitmap(null, a); } currentImageLocation = null; currentImageFilter = null; currentImageKey = null; currentMediaLocation = null; currentMediaFilter = null; currentMediaKey = null; currentThumbLocation = null; currentThumbFilter = null; currentThumbKey = null; currentMediaDrawable = null; mediaShader = null; currentImageDrawable = null; imageShader = null; composeShader = null; thumbShader = null; crossfadeShader = null; legacyShader = null; legacyCanvas = null; if (legacyBitmap != null) { legacyBitmap.recycle(); legacyBitmap = null; } currentExt = ext; currentParentObject = null; currentCacheType = 0; roundPaint.setShader(null); setStaticDrawable(thumb); currentAlpha = 1.0f; previousAlpha = 1f; currentSize = 0; updateDrawableRadius(staticThumbDrawable); ImageLoader.getInstance().cancelLoadingForImageReceiver(this, true); invalidate(); if (delegate != null) { delegate.didSetImage(this, currentImageDrawable != null || currentThumbDrawable != null || staticThumbDrawable != null || currentMediaDrawable != null, currentImageDrawable == null && currentMediaDrawable == null, false); } return; } String imageKey = imageLocation != null ? imageLocation.getKey(parentObject, null, false) : null; if (imageKey == null && imageLocation != null) { imageLocation = null; } animatedFileDrawableRepeatMaxCount = Math.max(autoRepeatCount, 0); currentKeyQuality = false; if (imageKey == null && needsQualityThumb && (parentObject instanceof MessageObject || qulityThumbDocument != null)) { TLRPC.Document document = qulityThumbDocument != null ? qulityThumbDocument : ((MessageObject) parentObject).getDocument(); if (document != null && document.dc_id != 0 && document.id != 0) { imageKey = "q_" + document.dc_id + "_" + document.id; currentKeyQuality = true; } } if (imageKey != null && imageFilter != null) { imageKey += "@" + imageFilter; } if (uniqKeyPrefix != null) { imageKey = uniqKeyPrefix + imageKey; } String mediaKey = mediaLocation != null ? mediaLocation.getKey(parentObject, null, false) : null; if (mediaKey == null && mediaLocation != null) { mediaLocation = null; } if (mediaKey != null && mediaFilter != null) { mediaKey += "@" + mediaFilter; } if (uniqKeyPrefix != null) { mediaKey = uniqKeyPrefix + mediaKey; } if (mediaKey == null && currentImageKey != null && currentImageKey.equals(imageKey) || currentMediaKey != null && currentMediaKey.equals(mediaKey)) { if (delegate != null) { delegate.didSetImage(this, currentImageDrawable != null || currentThumbDrawable != null || staticThumbDrawable != null || currentMediaDrawable != null, currentImageDrawable == null && currentMediaDrawable == null, false); } if (!canceledLoading) { return; } } ImageLocation strippedLoc; if (strippedLocation != null) { strippedLoc = strippedLocation; } else { strippedLoc = mediaLocation != null ? mediaLocation : imageLocation; } if (strippedLoc == null) { strippedLoc = thumbLocation; } String thumbKey = thumbLocation != null ? thumbLocation.getKey(parentObject, strippedLoc, false) : null; if (thumbKey != null && thumbFilter != null) { thumbKey += "@" + thumbFilter; } if (crossfadeWithOldImage) { if (currentParentObject instanceof MessageObject && ((MessageObject) currentParentObject).lastGeoWebFileSet != null && MessageObject.getMedia((MessageObject) currentParentObject) instanceof TLRPC.TL_messageMediaGeoLive) { ((MessageObject) currentParentObject).lastGeoWebFileLoaded = ((MessageObject) currentParentObject).lastGeoWebFileSet; } if (currentMediaDrawable != null) { if (currentMediaDrawable instanceof AnimatedFileDrawable) { ((AnimatedFileDrawable) currentMediaDrawable).stop(); ((AnimatedFileDrawable) currentMediaDrawable).removeParent(this); } recycleBitmap(thumbKey, TYPE_THUMB); recycleBitmap(null, TYPE_CROSSFDADE); recycleBitmap(mediaKey, TYPE_IMAGE); crossfadeImage = currentMediaDrawable; crossfadeShader = mediaShader; crossfadeKey = currentImageKey; crossfadingWithThumb = false; currentMediaDrawable = null; currentMediaKey = null; } else if (currentImageDrawable != null) { recycleBitmap(thumbKey, TYPE_THUMB); recycleBitmap(null, TYPE_CROSSFDADE); recycleBitmap(mediaKey, TYPE_MEDIA); crossfadeShader = imageShader; crossfadeImage = currentImageDrawable; crossfadeKey = currentImageKey; crossfadingWithThumb = false; currentImageDrawable = null; currentImageKey = null; } else if (currentThumbDrawable != null) { recycleBitmap(imageKey, TYPE_IMAGE); recycleBitmap(null, TYPE_CROSSFDADE); recycleBitmap(mediaKey, TYPE_MEDIA); crossfadeShader = thumbShader; crossfadeImage = currentThumbDrawable; crossfadeKey = currentThumbKey; crossfadingWithThumb = false; currentThumbDrawable = null; currentThumbKey = null; } else if (staticThumbDrawable != null) { recycleBitmap(imageKey, TYPE_IMAGE); recycleBitmap(thumbKey, TYPE_THUMB); recycleBitmap(null, TYPE_CROSSFDADE); recycleBitmap(mediaKey, TYPE_MEDIA); crossfadeShader = staticThumbShader; crossfadeImage = staticThumbDrawable; crossfadingWithThumb = false; crossfadeKey = null; currentThumbDrawable = null; currentThumbKey = null; } else { recycleBitmap(imageKey, TYPE_IMAGE); recycleBitmap(thumbKey, TYPE_THUMB); recycleBitmap(null, TYPE_CROSSFDADE); recycleBitmap(mediaKey, TYPE_MEDIA); crossfadeShader = null; } } else { recycleBitmap(imageKey, TYPE_IMAGE); recycleBitmap(thumbKey, TYPE_THUMB); recycleBitmap(null, TYPE_CROSSFDADE); recycleBitmap(mediaKey, TYPE_MEDIA); crossfadeShader = null; } currentImageLocation = imageLocation; currentImageFilter = imageFilter; currentImageKey = imageKey; currentMediaLocation = mediaLocation; currentMediaFilter = mediaFilter; currentMediaKey = mediaKey; currentThumbLocation = thumbLocation; currentThumbFilter = thumbFilter; currentThumbKey = thumbKey; currentParentObject = parentObject; currentExt = ext; currentSize = size; currentCacheType = cacheType; setStaticDrawable(thumb); imageShader = null; composeShader = null; thumbShader = null; staticThumbShader = null; mediaShader = null; legacyShader = null; legacyCanvas = null; roundPaint.setShader(null); if (legacyBitmap != null) { legacyBitmap.recycle(); legacyBitmap = null; } currentAlpha = 1.0f; previousAlpha = 1f; updateDrawableRadius(staticThumbDrawable); if (delegate != null) { delegate.didSetImage(this, currentImageDrawable != null || currentThumbDrawable != null || staticThumbDrawable != null || currentMediaDrawable != null, currentImageDrawable == null && currentMediaDrawable == null, false); } loadImage(); isRoundVideo = parentObject instanceof MessageObject && ((MessageObject) parentObject).isRoundVideo(); } private void loadImage() { ImageLoader.getInstance().loadImageForImageReceiver(this, preloadReceivers); invalidate(); } public boolean canInvertBitmap() { return currentMediaDrawable instanceof ExtendedBitmapDrawable || currentImageDrawable instanceof ExtendedBitmapDrawable || currentThumbDrawable instanceof ExtendedBitmapDrawable || staticThumbDrawable instanceof ExtendedBitmapDrawable; } public void setColorFilter(ColorFilter filter) { colorFilter = filter; } public void setDelegate(ImageReceiverDelegate delegate) { this.delegate = delegate; } public void setPressed(int value) { isPressed = value; } public boolean getPressed() { return isPressed != 0; } public void setOrientation(int angle, boolean center) { setOrientation(angle, 0, center); } public void setOrientation(int angle, int invert, boolean center) { while (angle < 0) { angle += 360; } while (angle > 360) { angle -= 360; } imageOrientation = thumbOrientation = angle; imageInvert = thumbInvert = invert; centerRotation = center; } public void setInvalidateAll(boolean value) { invalidateAll = value; } public Drawable getStaticThumb() { return staticThumbDrawable; } public int getAnimatedOrientation() { AnimatedFileDrawable animation = getAnimation(); return animation != null ? animation.getOrientation() : 0; } public int getOrientation() { return imageOrientation; } public int getInvert() { return imageInvert; } public void setLayerNum(int value) { currentLayerNum = value; if (attachedToWindow) { currentOpenedLayerFlags = NotificationCenter.getGlobalInstance().getCurrentHeavyOperationFlags(); currentOpenedLayerFlags &= ~currentLayerNum; } } public void setImageBitmap(Bitmap bitmap) { setImageBitmap(bitmap != null ? new BitmapDrawable(null, bitmap) : null); } public void setImageBitmap(Drawable bitmap) { ImageLoader.getInstance().cancelLoadingForImageReceiver(this, true); if (crossfadeWithOldImage) { if (currentImageDrawable != null) { recycleBitmap(null, TYPE_THUMB); recycleBitmap(null, TYPE_CROSSFDADE); recycleBitmap(null, TYPE_MEDIA); crossfadeShader = imageShader; crossfadeImage = currentImageDrawable; crossfadeKey = currentImageKey; crossfadingWithThumb = true; } else if (currentThumbDrawable != null) { recycleBitmap(null, TYPE_IMAGE); recycleBitmap(null, TYPE_CROSSFDADE); recycleBitmap(null, TYPE_MEDIA); crossfadeShader = thumbShader; crossfadeImage = currentThumbDrawable; crossfadeKey = currentThumbKey; crossfadingWithThumb = true; } else if (staticThumbDrawable != null) { recycleBitmap(null, TYPE_IMAGE); recycleBitmap(null, TYPE_THUMB); recycleBitmap(null, TYPE_CROSSFDADE); recycleBitmap(null, TYPE_MEDIA); crossfadeShader = staticThumbShader; crossfadeImage = staticThumbDrawable; crossfadingWithThumb = true; crossfadeKey = null; } else { for (int a = 0; a < 4; a++) { recycleBitmap(null, a); } crossfadeShader = null; } } else { for (int a = 0; a < 4; a++) { recycleBitmap(null, a); } } if (staticThumbDrawable instanceof RecyclableDrawable) { RecyclableDrawable drawable = (RecyclableDrawable) staticThumbDrawable; drawable.recycle(); } if (bitmap instanceof AnimatedFileDrawable) { AnimatedFileDrawable fileDrawable = (AnimatedFileDrawable) bitmap; fileDrawable.setParentView(parentView); if (attachedToWindow) { fileDrawable.addParent(this); } fileDrawable.setUseSharedQueue(useSharedAnimationQueue || fileDrawable.isWebmSticker); if (allowStartAnimation && currentOpenedLayerFlags == 0) { fileDrawable.checkRepeat(); } fileDrawable.setAllowDecodeSingleFrame(allowDecodeSingleFrame); } else if (bitmap instanceof RLottieDrawable) { RLottieDrawable fileDrawable = (RLottieDrawable) bitmap; if (attachedToWindow) { fileDrawable.addParentView(this); } if (fileDrawable != null) { fileDrawable.setAllowVibration(allowLottieVibration); } if (allowStartLottieAnimation && (!fileDrawable.isHeavyDrawable() || currentOpenedLayerFlags == 0)) { fileDrawable.start(); } fileDrawable.setAllowDecodeSingleFrame(true); } staticThumbShader = null; thumbShader = null; roundPaint.setShader(null); setStaticDrawable(bitmap); updateDrawableRadius(bitmap); currentMediaLocation = null; currentMediaFilter = null; if (currentMediaDrawable instanceof AnimatedFileDrawable) { ((AnimatedFileDrawable) currentMediaDrawable).removeParent(this); } currentMediaDrawable = null; currentMediaKey = null; mediaShader = null; currentImageLocation = null; currentImageFilter = null; currentImageDrawable = null; currentImageKey = null; imageShader = null; composeShader = null; legacyShader = null; legacyCanvas = null; if (legacyBitmap != null) { legacyBitmap.recycle(); legacyBitmap = null; } currentThumbLocation = null; currentThumbFilter = null; currentThumbKey = null; currentKeyQuality = false; currentExt = null; currentSize = 0; currentCacheType = 0; currentAlpha = 1; previousAlpha = 1f; if (setImageBackup != null) { setImageBackup.clear(); } if (delegate != null) { delegate.didSetImage(this, currentThumbDrawable != null || staticThumbDrawable != null, true, false); } invalidate(); if (forceCrossfade && crossfadeWithOldImage && crossfadeImage != null) { currentAlpha = 0.0f; lastUpdateAlphaTime = System.currentTimeMillis(); crossfadeWithThumb = currentThumbDrawable != null || staticThumbDrawable != null; } } private void setStaticDrawable(Drawable bitmap) { if (bitmap == staticThumbDrawable) { return; } AttachableDrawable oldDrawable = null; if (staticThumbDrawable instanceof AttachableDrawable) { if (staticThumbDrawable.equals(bitmap)) { return; } oldDrawable = (AttachableDrawable) staticThumbDrawable; } staticThumbDrawable = bitmap; if (attachedToWindow && staticThumbDrawable instanceof AttachableDrawable) { ((AttachableDrawable) staticThumbDrawable).onAttachedToWindow(this); } if (attachedToWindow && oldDrawable != null) { oldDrawable.onDetachedFromWindow(this); } } private void setDrawableShader(Drawable drawable, BitmapShader shader) { if (drawable == currentThumbDrawable) { thumbShader = shader; } else if (drawable == staticThumbDrawable) { staticThumbShader = shader; } else if (drawable == currentMediaDrawable) { mediaShader = shader; } else if (drawable == currentImageDrawable) { imageShader = shader; if (gradientShader != null && drawable instanceof BitmapDrawable) { if (Build.VERSION.SDK_INT >= 28) { composeShader = new ComposeShader(gradientShader, imageShader, PorterDuff.Mode.DST_IN); } else { BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; int w = bitmapDrawable.getBitmap().getWidth(); int h = bitmapDrawable.getBitmap().getHeight(); if (legacyBitmap == null || legacyBitmap.getWidth() != w || legacyBitmap.getHeight() != h) { if (legacyBitmap != null) { legacyBitmap.recycle(); } legacyBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); legacyCanvas = new Canvas(legacyBitmap); legacyShader = new BitmapShader(legacyBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); if (legacyPaint == null) { legacyPaint = new Paint(); legacyPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN)); } } } } } } private boolean hasRoundRadius() { /*for (int a = 0; a < roundRadius.length; a++) { if (roundRadius[a] != 0) { return true; } }*/ return true; } private void updateDrawableRadius(Drawable drawable) { if (drawable == null) { return; } if (drawable instanceof ClipRoundedDrawable) { ((ClipRoundedDrawable) drawable).setRadii(roundRadius[0], roundRadius[1], roundRadius[2], roundRadius[3]); } else if ((hasRoundRadius() || gradientShader != null) && (drawable instanceof BitmapDrawable || drawable instanceof AvatarDrawable)) { if (drawable instanceof AvatarDrawable) { ((AvatarDrawable) drawable).setRoundRadius(roundRadius[0]); } else { BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; if (bitmapDrawable instanceof RLottieDrawable) { } else if (bitmapDrawable instanceof AnimatedFileDrawable) { AnimatedFileDrawable animatedFileDrawable = (AnimatedFileDrawable) drawable; animatedFileDrawable.setRoundRadius(roundRadius); } else if (bitmapDrawable.getBitmap() != null && !bitmapDrawable.getBitmap().isRecycled()) { setDrawableShader(drawable, new BitmapShader(bitmapDrawable.getBitmap(), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)); } } } else { setDrawableShader(drawable, null); } } public void clearImage() { for (int a = 0; a < 4; a++) { recycleBitmap(null, a); } ImageLoader.getInstance().cancelLoadingForImageReceiver(this, true); } public void onDetachedFromWindow() { if (!attachedToWindow) { return; } attachedToWindow = false; if (currentImageLocation != null || currentMediaLocation != null || currentThumbLocation != null || staticThumbDrawable != null) { if (setImageBackup == null) { setImageBackup = new SetImageBackup(); } setImageBackup.mediaLocation = currentMediaLocation; setImageBackup.mediaFilter = currentMediaFilter; setImageBackup.imageLocation = currentImageLocation; setImageBackup.imageFilter = currentImageFilter; setImageBackup.thumbLocation = currentThumbLocation; setImageBackup.thumbFilter = currentThumbFilter; setImageBackup.thumb = staticThumbDrawable; setImageBackup.size = currentSize; setImageBackup.ext = currentExt; setImageBackup.cacheType = currentCacheType; setImageBackup.parentObject = currentParentObject; } if (!ignoreNotifications) { NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.didReplacedPhotoInMemCache); NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.stopAllHeavyOperations); NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.startAllHeavyOperations); } if (staticThumbDrawable instanceof AttachableDrawable) { ((AttachableDrawable) staticThumbDrawable).onDetachedFromWindow(this); } if (staticThumbDrawable != null) { setStaticDrawable(null); staticThumbShader = null; } clearImage(); roundPaint.setShader(null); if (isPressed == 0) { pressedProgress = 0f; } AnimatedFileDrawable animatedFileDrawable = getAnimation(); if (animatedFileDrawable != null) { animatedFileDrawable.removeParent(this); } RLottieDrawable lottieDrawable = getLottieAnimation(); if (lottieDrawable != null) { lottieDrawable.removeParentView(this); } if (decorators != null) { for (int i = 0; i < decorators.size(); i++) { decorators.get(i).onDetachedFromWidnow(); } } } public boolean setBackupImage() { if (setImageBackup != null && setImageBackup.isSet()) { SetImageBackup temp = setImageBackup; setImageBackup = null; if (temp.thumb instanceof BitmapDrawable) { BitmapDrawable bitmapDrawable = (BitmapDrawable) temp.thumb; if (!(bitmapDrawable instanceof RLottieDrawable) && !(bitmapDrawable instanceof AnimatedFileDrawable) && bitmapDrawable.getBitmap() != null && bitmapDrawable.getBitmap().isRecycled()) { temp.thumb = null; } } setImage(temp.mediaLocation, temp.mediaFilter, temp.imageLocation, temp.imageFilter, temp.thumbLocation, temp.thumbFilter, temp.thumb, temp.size, temp.ext, temp.parentObject, temp.cacheType); temp.clear(); setImageBackup = temp; RLottieDrawable lottieDrawable = getLottieAnimation(); if (lottieDrawable != null) { lottieDrawable.setAllowVibration(allowLottieVibration); } if (lottieDrawable != null && allowStartLottieAnimation && (!lottieDrawable.isHeavyDrawable() || currentOpenedLayerFlags == 0)) { lottieDrawable.start(); } return true; } return false; } public boolean onAttachedToWindow() { if (attachedToWindow) { return false; } attachedToWindow = true; currentOpenedLayerFlags = NotificationCenter.getGlobalInstance().getCurrentHeavyOperationFlags(); currentOpenedLayerFlags &= ~currentLayerNum; if (!ignoreNotifications) { NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.didReplacedPhotoInMemCache); NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.stopAllHeavyOperations); NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.startAllHeavyOperations); } if (setBackupImage()) { return true; } RLottieDrawable lottieDrawable = getLottieAnimation(); if (lottieDrawable != null) { lottieDrawable.addParentView(this); lottieDrawable.setAllowVibration(allowLottieVibration); } if (lottieDrawable != null && allowStartLottieAnimation && (!lottieDrawable.isHeavyDrawable() || currentOpenedLayerFlags == 0)) { lottieDrawable.start(); } AnimatedFileDrawable animatedFileDrawable = getAnimation(); if (animatedFileDrawable != null) { animatedFileDrawable.addParent(this); } if (animatedFileDrawable != null && allowStartAnimation && currentOpenedLayerFlags == 0) { animatedFileDrawable.checkRepeat(); invalidate(); } if (NotificationCenter.getGlobalInstance().isAnimationInProgress()) { didReceivedNotification(NotificationCenter.stopAllHeavyOperations, currentAccount, 512); } if (staticThumbDrawable instanceof AttachableDrawable) { ((AttachableDrawable) staticThumbDrawable).onAttachedToWindow(this); } if (decorators != null) { for (int i = 0; i < decorators.size(); i++) { decorators.get(i).onAttachedToWindow(this); } } return false; } private void drawDrawable(Canvas canvas, Drawable drawable, int alpha, BitmapShader shader, int orientation, int invert, BackgroundThreadDrawHolder backgroundThreadDrawHolder) { if (isPressed == 0 && pressedProgress != 0) { pressedProgress -= 16 / 150f; if (pressedProgress < 0) { pressedProgress = 0; } invalidate(); } if (isPressed != 0) { pressedProgress = 1f; animateFromIsPressed = isPressed; } if (pressedProgress == 0 || pressedProgress == 1f) { drawDrawable(canvas, drawable, alpha, shader, orientation, invert, isPressed, backgroundThreadDrawHolder); } else { drawDrawable(canvas, drawable, alpha, shader, orientation, invert, isPressed, backgroundThreadDrawHolder); drawDrawable(canvas, drawable, (int) (alpha * pressedProgress), shader, orientation, invert, animateFromIsPressed, backgroundThreadDrawHolder); } } public void setUseRoundForThumbDrawable(boolean value) { useRoundForThumb = value; } protected void drawDrawable(Canvas canvas, Drawable drawable, int alpha, BitmapShader shader, int orientation, int invert, int isPressed, BackgroundThreadDrawHolder backgroundThreadDrawHolder) { float imageX, imageY, imageH, imageW; RectF drawRegion; ColorFilter colorFilter; int[] roundRadius; boolean reactionLastFrame = false; if (backgroundThreadDrawHolder != null) { imageX = backgroundThreadDrawHolder.imageX; imageY = backgroundThreadDrawHolder.imageY; imageH = backgroundThreadDrawHolder.imageH; imageW = backgroundThreadDrawHolder.imageW; drawRegion = backgroundThreadDrawHolder.drawRegion; colorFilter = backgroundThreadDrawHolder.colorFilter; roundRadius = backgroundThreadDrawHolder.roundRadius; } else { imageX = this.imageX; imageY = this.imageY; imageH = this.imageH; imageW = this.imageW; drawRegion = this.drawRegion; colorFilter = this.colorFilter; roundRadius = this.roundRadius; } if (drawable instanceof BitmapDrawable) { BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; if (drawable instanceof RLottieDrawable) { ((RLottieDrawable) drawable).skipFrameUpdate = skipUpdateFrame; } else if (drawable instanceof AnimatedFileDrawable) { ((AnimatedFileDrawable) drawable).skipFrameUpdate = skipUpdateFrame; } Paint paint; if (shader != null) { paint = roundPaint; } else { paint = bitmapDrawable.getPaint(); } if (Build.VERSION.SDK_INT >= 29) { if (blendMode != null && gradientShader == null) { paint.setBlendMode((BlendMode) blendMode); } else { paint.setBlendMode(null); } } boolean hasFilter = paint != null && paint.getColorFilter() != null; if (hasFilter && isPressed == 0) { if (shader != null) { roundPaint.setColorFilter(null); } else if (staticThumbDrawable != drawable) { bitmapDrawable.setColorFilter(null); } } else if (!hasFilter && isPressed != 0) { if (isPressed == 1) { if (shader != null) { roundPaint.setColorFilter(selectedColorFilter); } else { bitmapDrawable.setColorFilter(selectedColorFilter); } } else { if (shader != null) { roundPaint.setColorFilter(selectedGroupColorFilter); } else { bitmapDrawable.setColorFilter(selectedGroupColorFilter); } } } if (colorFilter != null && gradientShader == null) { if (shader != null) { roundPaint.setColorFilter(colorFilter); } else { bitmapDrawable.setColorFilter(colorFilter); } } int bitmapW; int bitmapH; if (bitmapDrawable instanceof AnimatedFileDrawable || bitmapDrawable instanceof RLottieDrawable) { if (orientation % 360 == 90 || orientation % 360 == 270) { bitmapW = bitmapDrawable.getIntrinsicHeight(); bitmapH = bitmapDrawable.getIntrinsicWidth(); } else { bitmapW = bitmapDrawable.getIntrinsicWidth(); bitmapH = bitmapDrawable.getIntrinsicHeight(); } } else { Bitmap bitmap = bitmapDrawable.getBitmap(); if (bitmap != null && bitmap.isRecycled()) { return; } if (orientation % 360 == 90 || orientation % 360 == 270) { bitmapW = bitmap.getHeight(); bitmapH = bitmap.getWidth(); } else { bitmapW = bitmap.getWidth(); bitmapH = bitmap.getHeight(); } reactionLastFrame = bitmapDrawable instanceof ReactionLastFrame; } float realImageW = imageW - sideClip * 2; float realImageH = imageH - sideClip * 2; float scaleW = imageW == 0 ? 1.0f : (bitmapW / realImageW); float scaleH = imageH == 0 ? 1.0f : (bitmapH / realImageH); if (reactionLastFrame) { scaleW /= ReactionLastFrame.LAST_FRAME_SCALE; scaleH /= ReactionLastFrame.LAST_FRAME_SCALE; } if (shader != null && backgroundThreadDrawHolder == null) { if (isAspectFit) { float scale = Math.max(scaleW, scaleH); bitmapW /= scale; bitmapH /= scale; drawRegion.set(imageX + (imageW - bitmapW) / 2, imageY + (imageH - bitmapH) / 2, imageX + (imageW + bitmapW) / 2, imageY + (imageH + bitmapH) / 2); if (isVisible) { shaderMatrix.reset(); shaderMatrix.setTranslate((int) drawRegion.left, (int) drawRegion.top); if (invert != 0) { shaderMatrix.preScale(invert == 1 ? -1 : 1, invert == 2 ? -1 : 1, drawRegion.width() / 2f, drawRegion.height() / 2f); } if (orientation == 90) { shaderMatrix.preRotate(90); shaderMatrix.preTranslate(0, -drawRegion.width()); } else if (orientation == 180) { shaderMatrix.preRotate(180); shaderMatrix.preTranslate(-drawRegion.width(), -drawRegion.height()); } else if (orientation == 270) { shaderMatrix.preRotate(270); shaderMatrix.preTranslate(-drawRegion.height(), 0); } final float toScale = 1.0f / scale; shaderMatrix.preScale(toScale, toScale); shader.setLocalMatrix(shaderMatrix); roundPaint.setShader(shader); roundPaint.setAlpha(alpha); roundRect.set(drawRegion); if (isRoundRect) { try { if (canvas != null) { if (roundRadius[0] == 0) { canvas.drawRect(roundRect, roundPaint); } else { canvas.drawRoundRect(roundRect, roundRadius[0], roundRadius[0], roundPaint); } } } catch (Exception e) { onBitmapException(bitmapDrawable); FileLog.e(e); } } else { for (int a = 0; a < roundRadius.length; a++) { radii[a * 2] = roundRadius[a]; radii[a * 2 + 1] = roundRadius[a]; } roundPath.reset(); roundPath.addRoundRect(roundRect, radii, Path.Direction.CW); roundPath.close(); if (canvas != null) { canvas.drawPath(roundPath, roundPaint); } } } } else { if (legacyCanvas != null) { roundRect.set(0, 0, legacyBitmap.getWidth(), legacyBitmap.getHeight()); legacyCanvas.drawBitmap(gradientBitmap, null, roundRect, null); legacyCanvas.drawBitmap(bitmapDrawable.getBitmap(), null, roundRect, legacyPaint); } if (shader == imageShader && gradientShader != null) { if (composeShader != null) { roundPaint.setShader(composeShader); } else { roundPaint.setShader(legacyShader); } } else { roundPaint.setShader(shader); } float scale = 1.0f / Math.min(scaleW, scaleH); roundRect.set(imageX + sideClip, imageY + sideClip, imageX + imageW - sideClip, imageY + imageH - sideClip); if (Math.abs(scaleW - scaleH) > 0.0005f) { if (bitmapW / scaleH > realImageW) { bitmapW /= scaleH; drawRegion.set(imageX - (bitmapW - realImageW) / 2, imageY, imageX + (bitmapW + realImageW) / 2, imageY + realImageH); } else { bitmapH /= scaleW; drawRegion.set(imageX, imageY - (bitmapH - realImageH) / 2, imageX + realImageW, imageY + (bitmapH + realImageH) / 2); } } else { drawRegion.set(imageX, imageY, imageX + realImageW, imageY + realImageH); } if (isVisible) { shaderMatrix.reset(); if (reactionLastFrame) { shaderMatrix.setTranslate((drawRegion.left + sideClip) - (drawRegion.width() * ReactionLastFrame.LAST_FRAME_SCALE - drawRegion.width()) / 2f, drawRegion.top + sideClip - (drawRegion.height() * ReactionLastFrame.LAST_FRAME_SCALE - drawRegion.height()) / 2f); } else { shaderMatrix.setTranslate(drawRegion.left + sideClip, drawRegion.top + sideClip); } if (invert != 0) { shaderMatrix.preScale(invert == 1 ? -1 : 1, invert == 2 ? -1 : 1, drawRegion.width() / 2f, drawRegion.height() / 2f); } if (orientation == 90) { shaderMatrix.preRotate(90); shaderMatrix.preTranslate(0, -drawRegion.width()); } else if (orientation == 180) { shaderMatrix.preRotate(180); shaderMatrix.preTranslate(-drawRegion.width(), -drawRegion.height()); } else if (orientation == 270) { shaderMatrix.preRotate(270); shaderMatrix.preTranslate(-drawRegion.height(), 0); } shaderMatrix.preScale(scale, scale); if (isRoundVideo) { float postScale = (realImageW + AndroidUtilities.roundMessageInset * 2) / realImageW; shaderMatrix.postScale(postScale, postScale, drawRegion.centerX(), drawRegion.centerY()); } if (legacyShader != null) { legacyShader.setLocalMatrix(shaderMatrix); } shader.setLocalMatrix(shaderMatrix); if (composeShader != null) { int bitmapW2 = gradientBitmap.getWidth(); int bitmapH2 = gradientBitmap.getHeight(); float scaleW2 = imageW == 0 ? 1.0f : (bitmapW2 / realImageW); float scaleH2 = imageH == 0 ? 1.0f : (bitmapH2 / realImageH); if (Math.abs(scaleW2 - scaleH2) > 0.0005f) { if (bitmapW2 / scaleH2 > realImageW) { bitmapW2 /= scaleH2; drawRegion.set(imageX - (bitmapW2 - realImageW) / 2, imageY, imageX + (bitmapW2 + realImageW) / 2, imageY + realImageH); } else { bitmapH2 /= scaleW2; drawRegion.set(imageX, imageY - (bitmapH2 - realImageH) / 2, imageX + realImageW, imageY + (bitmapH2 + realImageH) / 2); } } else { drawRegion.set(imageX, imageY, imageX + realImageW, imageY + realImageH); } scale = 1.0f / Math.min(imageW == 0 ? 1.0f : (bitmapW2 / realImageW), imageH == 0 ? 1.0f : (bitmapH2 / realImageH)); shaderMatrix.reset(); shaderMatrix.setTranslate(drawRegion.left + sideClip, drawRegion.top + sideClip); shaderMatrix.preScale(scale, scale); gradientShader.setLocalMatrix(shaderMatrix); } roundPaint.setAlpha(alpha); if (isRoundRect) { try { if (canvas != null) { if (roundRadius[0] == 0) { if (reactionLastFrame) { AndroidUtilities.rectTmp.set(roundRect); AndroidUtilities.rectTmp.inset(-(drawRegion.width() * ReactionLastFrame.LAST_FRAME_SCALE - drawRegion.width()) / 2f, -(drawRegion.height() * ReactionLastFrame.LAST_FRAME_SCALE - drawRegion.height()) / 2f); canvas.drawRect(AndroidUtilities.rectTmp, roundPaint); } else { canvas.drawRect(roundRect, roundPaint); } } else { canvas.drawRoundRect(roundRect, roundRadius[0], roundRadius[0], roundPaint); } } } catch (Exception e) { if (backgroundThreadDrawHolder == null) { onBitmapException(bitmapDrawable); } FileLog.e(e); } } else { for (int a = 0; a < roundRadius.length; a++) { radii[a * 2] = roundRadius[a]; radii[a * 2 + 1] = roundRadius[a]; } roundPath.reset(); roundPath.addRoundRect(roundRect, radii, Path.Direction.CW); roundPath.close(); if (canvas != null) { canvas.drawPath(roundPath, roundPaint); } } } } } else { if (isAspectFit) { float scale = Math.max(scaleW, scaleH); canvas.save(); bitmapW /= scale; bitmapH /= scale; if (backgroundThreadDrawHolder == null) { drawRegion.set(imageX + (imageW - bitmapW) / 2.0f, imageY + (imageH - bitmapH) / 2.0f, imageX + (imageW + bitmapW) / 2.0f, imageY + (imageH + bitmapH) / 2.0f); bitmapDrawable.setBounds((int) drawRegion.left, (int) drawRegion.top, (int) drawRegion.right, (int) drawRegion.bottom); if (bitmapDrawable instanceof AnimatedFileDrawable) { ((AnimatedFileDrawable) bitmapDrawable).setActualDrawRect(drawRegion.left, drawRegion.top, drawRegion.width(), drawRegion.height()); } } if (backgroundThreadDrawHolder != null && roundRadius != null && roundRadius[0] > 0) { canvas.save(); Path path = backgroundThreadDrawHolder.roundPath == null ? backgroundThreadDrawHolder.roundPath = new Path() : backgroundThreadDrawHolder.roundPath; path.rewind(); AndroidUtilities.rectTmp.set(imageX, imageY, imageX + imageW, imageY + imageH); path.addRoundRect(AndroidUtilities.rectTmp, roundRadius[0], roundRadius[2], Path.Direction.CW); canvas.clipPath(path); } if (isVisible) { try { bitmapDrawable.setAlpha(alpha); drawBitmapDrawable(canvas, bitmapDrawable, backgroundThreadDrawHolder, alpha); } catch (Exception e) { if (backgroundThreadDrawHolder == null) { onBitmapException(bitmapDrawable); } FileLog.e(e); } } canvas.restore(); if (backgroundThreadDrawHolder != null && roundRadius != null && roundRadius[0] > 0) { canvas.restore(); } } else { if (canvas != null) { if (Math.abs(scaleW - scaleH) > 0.00001f) { canvas.save(); if (clip) { canvas.clipRect(imageX, imageY, imageX + imageW, imageY + imageH); } if (invert == 1) { canvas.scale(-1, 1, imageW / 2, imageH / 2); } else if (invert == 2) { canvas.scale(1, -1, imageW / 2, imageH / 2); } if (orientation % 360 != 0) { if (centerRotation) { canvas.rotate(orientation, imageW / 2, imageH / 2); } else { canvas.rotate(orientation, 0, 0); } } if (bitmapW / scaleH > imageW) { bitmapW /= scaleH; drawRegion.set(imageX - (bitmapW - imageW) / 2.0f, imageY, imageX + (bitmapW + imageW) / 2.0f, imageY + imageH); } else { bitmapH /= scaleW; drawRegion.set(imageX, imageY - (bitmapH - imageH) / 2.0f, imageX + imageW, imageY + (bitmapH + imageH) / 2.0f); } if (bitmapDrawable instanceof AnimatedFileDrawable) { ((AnimatedFileDrawable) bitmapDrawable).setActualDrawRect(imageX, imageY, imageW, imageH); } if (backgroundThreadDrawHolder == null) { if (orientation % 360 == 90 || orientation % 360 == 270) { float width = drawRegion.width() / 2; float height = drawRegion.height() / 2; float centerX = drawRegion.centerX(); float centerY = drawRegion.centerY(); bitmapDrawable.setBounds((int) (centerX - height), (int) (centerY - width), (int) (centerX + height), (int) (centerY + width)); } else { bitmapDrawable.setBounds((int) drawRegion.left, (int) drawRegion.top, (int) drawRegion.right, (int) drawRegion.bottom); } } if (isVisible) { try { if (Build.VERSION.SDK_INT >= 29) { if (blendMode != null) { bitmapDrawable.getPaint().setBlendMode((BlendMode) blendMode); } else { bitmapDrawable.getPaint().setBlendMode(null); } } drawBitmapDrawable(canvas, bitmapDrawable, backgroundThreadDrawHolder, alpha); } catch (Exception e) { if (backgroundThreadDrawHolder == null) { onBitmapException(bitmapDrawable); } FileLog.e(e); } } canvas.restore(); } else { canvas.save(); if (invert == 1) { canvas.scale(-1, 1, imageW / 2, imageH / 2); } else if (invert == 2) { canvas.scale(1, -1, imageW / 2, imageH / 2); } if (orientation % 360 != 0) { if (centerRotation) { canvas.rotate(orientation, imageW / 2, imageH / 2); } else { canvas.rotate(orientation, 0, 0); } } drawRegion.set(imageX, imageY, imageX + imageW, imageY + imageH); if (isRoundVideo) { drawRegion.inset(-AndroidUtilities.roundMessageInset, -AndroidUtilities.roundMessageInset); } if (bitmapDrawable instanceof AnimatedFileDrawable) { ((AnimatedFileDrawable) bitmapDrawable).setActualDrawRect(imageX, imageY, imageW, imageH); } if (backgroundThreadDrawHolder == null) { if (orientation % 360 == 90 || orientation % 360 == 270) { float width = drawRegion.width() / 2; float height = drawRegion.height() / 2; float centerX = drawRegion.centerX(); float centerY = drawRegion.centerY(); bitmapDrawable.setBounds((int) (centerX - height), (int) (centerY - width), (int) (centerX + height), (int) (centerY + width)); } else { bitmapDrawable.setBounds((int) drawRegion.left, (int) drawRegion.top, (int) drawRegion.right, (int) drawRegion.bottom); } } if (isVisible) { try { if (Build.VERSION.SDK_INT >= 29) { if (blendMode != null) { bitmapDrawable.getPaint().setBlendMode((BlendMode) blendMode); } else { bitmapDrawable.getPaint().setBlendMode(null); } } drawBitmapDrawable(canvas, bitmapDrawable, backgroundThreadDrawHolder, alpha); } catch (Exception e) { onBitmapException(bitmapDrawable); FileLog.e(e); } } canvas.restore(); } } } } if (drawable instanceof RLottieDrawable) { ((RLottieDrawable) drawable).skipFrameUpdate = false; } else if (drawable instanceof AnimatedFileDrawable) { ((AnimatedFileDrawable) drawable).skipFrameUpdate = false; } } else { if (backgroundThreadDrawHolder == null) { if (isAspectFit) { int bitmapW = drawable.getIntrinsicWidth(); int bitmapH = drawable.getIntrinsicHeight(); float realImageW = imageW - sideClip * 2; float realImageH = imageH - sideClip * 2; float scaleW = imageW == 0 ? 1.0f : (bitmapW / realImageW); float scaleH = imageH == 0 ? 1.0f : (bitmapH / realImageH); float scale = Math.max(scaleW, scaleH); bitmapW /= scale; bitmapH /= scale; drawRegion.set(imageX + (imageW - bitmapW) / 2.0f, imageY + (imageH - bitmapH) / 2.0f, imageX + (imageW + bitmapW) / 2.0f, imageY + (imageH + bitmapH) / 2.0f); } else { drawRegion.set(imageX, imageY, imageX + imageW, imageY + imageH); } drawable.setBounds((int) drawRegion.left, (int) drawRegion.top, (int) drawRegion.right, (int) drawRegion.bottom); } if (isVisible && canvas != null) { SvgHelper.SvgDrawable svgDrawable = null; if (drawable instanceof SvgHelper.SvgDrawable) { svgDrawable = (SvgHelper.SvgDrawable) drawable; svgDrawable.setParent(this); } else if (drawable instanceof ClipRoundedDrawable && ((ClipRoundedDrawable) drawable).getDrawable() instanceof SvgHelper.SvgDrawable) { svgDrawable = (SvgHelper.SvgDrawable) ((ClipRoundedDrawable) drawable).getDrawable(); svgDrawable.setParent(this); } if (colorFilter != null && drawable != null) { drawable.setColorFilter(colorFilter); } try { drawable.setAlpha(alpha); if (backgroundThreadDrawHolder != null) { if (svgDrawable != null) { long time = backgroundThreadDrawHolder.time; if (time == 0) { time = System.currentTimeMillis(); } ((SvgHelper.SvgDrawable) drawable).drawInternal(canvas, true, backgroundThreadDrawHolder.threadIndex, time, backgroundThreadDrawHolder.imageX, backgroundThreadDrawHolder.imageY, backgroundThreadDrawHolder.imageW, backgroundThreadDrawHolder.imageH); } else { drawable.draw(canvas); } } else { drawable.draw(canvas); } } catch (Exception e) { FileLog.e(e); } if (svgDrawable != null) { svgDrawable.setParent(null); } } } } private void drawBitmapDrawable(Canvas canvas, BitmapDrawable bitmapDrawable, BackgroundThreadDrawHolder backgroundThreadDrawHolder, int alpha) { if (backgroundThreadDrawHolder != null) { if (bitmapDrawable instanceof RLottieDrawable) { ((RLottieDrawable) bitmapDrawable).drawInBackground(canvas, backgroundThreadDrawHolder.imageX, backgroundThreadDrawHolder.imageY, backgroundThreadDrawHolder.imageW, backgroundThreadDrawHolder.imageH, alpha, backgroundThreadDrawHolder.colorFilter, backgroundThreadDrawHolder.threadIndex); } else if (bitmapDrawable instanceof AnimatedFileDrawable) { ((AnimatedFileDrawable) bitmapDrawable).drawInBackground(canvas, backgroundThreadDrawHolder.imageX, backgroundThreadDrawHolder.imageY, backgroundThreadDrawHolder.imageW, backgroundThreadDrawHolder.imageH, alpha, backgroundThreadDrawHolder.colorFilter, backgroundThreadDrawHolder.threadIndex); } else { Bitmap bitmap = bitmapDrawable.getBitmap(); if (bitmap != null) { if (backgroundThreadDrawHolder.paint == null) { backgroundThreadDrawHolder.paint = new Paint(Paint.ANTI_ALIAS_FLAG); } backgroundThreadDrawHolder.paint.setAlpha(alpha); backgroundThreadDrawHolder.paint.setColorFilter(backgroundThreadDrawHolder.colorFilter); canvas.save(); canvas.translate(backgroundThreadDrawHolder.imageX, backgroundThreadDrawHolder.imageY); canvas.scale(backgroundThreadDrawHolder.imageW / bitmap.getWidth(), backgroundThreadDrawHolder.imageH / bitmap.getHeight()); canvas.drawBitmap(bitmap, 0, 0, backgroundThreadDrawHolder.paint); canvas.restore(); } } } else { bitmapDrawable.setAlpha(alpha); if (bitmapDrawable instanceof RLottieDrawable) { ((RLottieDrawable) bitmapDrawable).drawInternal(canvas, null, false, currentTime, 0); } else if (bitmapDrawable instanceof AnimatedFileDrawable) { ((AnimatedFileDrawable) bitmapDrawable).drawInternal(canvas, false, currentTime, 0); } else { bitmapDrawable.draw(canvas); } } } public void setBlendMode(Object mode) { blendMode = mode; invalidate(); } public void setGradientBitmap(Bitmap bitmap) { if (bitmap != null) { if (gradientShader == null || gradientBitmap != bitmap) { gradientShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); updateDrawableRadius(currentImageDrawable); } isRoundRect = true; } else { gradientShader = null; composeShader = null; legacyShader = null; legacyCanvas = null; if (legacyBitmap != null) { legacyBitmap.recycle(); legacyBitmap = null; } } gradientBitmap = bitmap; } private void onBitmapException(Drawable bitmapDrawable) { if (bitmapDrawable == currentMediaDrawable && currentMediaKey != null) { ImageLoader.getInstance().removeImage(currentMediaKey); currentMediaKey = null; } else if (bitmapDrawable == currentImageDrawable && currentImageKey != null) { ImageLoader.getInstance().removeImage(currentImageKey); currentImageKey = null; } else if (bitmapDrawable == currentThumbDrawable && currentThumbKey != null) { ImageLoader.getInstance().removeImage(currentThumbKey); currentThumbKey = null; } setImage(currentMediaLocation, currentMediaFilter, currentImageLocation, currentImageFilter, currentThumbLocation, currentThumbFilter, currentThumbDrawable, currentSize, currentExt, currentParentObject, currentCacheType); } private void checkAlphaAnimation(boolean skip, BackgroundThreadDrawHolder backgroundThreadDrawHolder) { if (manualAlphaAnimator) { return; } if (currentAlpha != 1) { if (!skip) { if (backgroundThreadDrawHolder != null) { long currentTime = System.currentTimeMillis(); long dt = currentTime - lastUpdateAlphaTime; if (lastUpdateAlphaTime == 0) { dt = 16; } if (dt > 30 && AndroidUtilities.screenRefreshRate > 60) { dt = 30; } currentAlpha += dt / (float) crossfadeDuration; } else { currentAlpha += 16f / (float) crossfadeDuration; } if (currentAlpha > 1) { currentAlpha = 1; previousAlpha = 1f; if (crossfadeImage != null) { recycleBitmap(null, 2); crossfadeShader = null; } } } if (backgroundThreadDrawHolder != null) { AndroidUtilities.runOnUIThread(this::invalidate); } else { invalidate(); } } } public void skipDraw() { // RLottieDrawable lottieDrawable = getLottieAnimation(); // if (lottieDrawable != null) { // lottieDrawable.setCurrentParentView(parentView); // lottieDrawable.updateCurrentFrame(); // } } public boolean draw(Canvas canvas) { return draw(canvas, null); } public boolean draw(Canvas canvas, BackgroundThreadDrawHolder backgroundThreadDrawHolder) { boolean result = false; if (gradientBitmap != null && currentImageKey != null) { canvas.save(); canvas.clipRect(imageX, imageY, imageX + imageW, imageY + imageH); canvas.drawColor(0xff000000); } try { Drawable drawable = null; AnimatedFileDrawable animation; RLottieDrawable lottieDrawable; Drawable currentMediaDrawable; BitmapShader mediaShader; Drawable currentImageDrawable; BitmapShader imageShader; Drawable currentThumbDrawable; BitmapShader thumbShader; BitmapShader staticThumbShader; boolean crossfadeWithOldImage; boolean crossfadingWithThumb; Drawable crossfadeImage; BitmapShader crossfadeShader; Drawable staticThumbDrawable; float currentAlpha; float previousAlpha; float overrideAlpha; int[] roundRadius; boolean animationNotReady; ColorFilter colorFilter; boolean drawInBackground = backgroundThreadDrawHolder != null; if (drawInBackground) { animation = backgroundThreadDrawHolder.animation; lottieDrawable = backgroundThreadDrawHolder.lottieDrawable; roundRadius = backgroundThreadDrawHolder.roundRadius; currentMediaDrawable = backgroundThreadDrawHolder.mediaDrawable; mediaShader = backgroundThreadDrawHolder.mediaShader; currentImageDrawable = backgroundThreadDrawHolder.imageDrawable; imageShader = backgroundThreadDrawHolder.imageShader; thumbShader = backgroundThreadDrawHolder.thumbShader; staticThumbShader = backgroundThreadDrawHolder.staticThumbShader; crossfadeImage = backgroundThreadDrawHolder.crossfadeImage; crossfadeWithOldImage = backgroundThreadDrawHolder.crossfadeWithOldImage; crossfadingWithThumb = backgroundThreadDrawHolder.crossfadingWithThumb; currentThumbDrawable = backgroundThreadDrawHolder.thumbDrawable; staticThumbDrawable = backgroundThreadDrawHolder.staticThumbDrawable; currentAlpha = backgroundThreadDrawHolder.currentAlpha; previousAlpha = backgroundThreadDrawHolder.previousAlpha; crossfadeShader = backgroundThreadDrawHolder.crossfadeShader; animationNotReady = backgroundThreadDrawHolder.animationNotReady; overrideAlpha = backgroundThreadDrawHolder.overrideAlpha; colorFilter = backgroundThreadDrawHolder.colorFilter; } else { animation = getAnimation(); lottieDrawable = getLottieAnimation(); roundRadius = this.roundRadius; currentMediaDrawable = this.currentMediaDrawable; mediaShader = this.mediaShader; currentImageDrawable = this.currentImageDrawable; imageShader = this.imageShader; currentThumbDrawable = this.currentThumbDrawable; thumbShader = this.thumbShader; staticThumbShader = this.staticThumbShader; crossfadeWithOldImage = this.crossfadeWithOldImage; crossfadingWithThumb = this.crossfadingWithThumb; crossfadeImage = this.crossfadeImage; staticThumbDrawable = this.staticThumbDrawable; currentAlpha = this.currentAlpha; previousAlpha = this.previousAlpha; crossfadeShader = this.crossfadeShader; overrideAlpha = this.overrideAlpha; animationNotReady = animation != null && !animation.hasBitmap() || lottieDrawable != null && !lottieDrawable.hasBitmap(); colorFilter = this.colorFilter; } if (animation != null) { animation.setRoundRadius(roundRadius); } if (lottieDrawable != null && !drawInBackground) { lottieDrawable.setCurrentParentView(parentView); } if ((animation != null || lottieDrawable != null) && !animationNotReady && !animationReadySent && !drawInBackground) { animationReadySent = true; if (delegate != null) { delegate.onAnimationReady(this); } } int orientation = 0, invert = 0; BitmapShader shaderToUse = null; if (!forcePreview && currentMediaDrawable != null && !animationNotReady) { drawable = currentMediaDrawable; shaderToUse = mediaShader; orientation = imageOrientation; invert = imageInvert; } else if (!forcePreview && currentImageDrawable != null && (!animationNotReady || currentMediaDrawable != null)) { drawable = currentImageDrawable; shaderToUse = imageShader; orientation = imageOrientation; invert = imageInvert; animationNotReady = false; } else if (crossfadeImage != null && !crossfadingWithThumb) { drawable = crossfadeImage; shaderToUse = crossfadeShader; orientation = imageOrientation; invert = imageInvert; } else if (currentThumbDrawable != null) { drawable = currentThumbDrawable; shaderToUse = thumbShader; orientation = thumbOrientation; invert = thumbInvert; } else if (staticThumbDrawable instanceof BitmapDrawable) { drawable = staticThumbDrawable; if (useRoundForThumb && staticThumbShader == null) { updateDrawableRadius(staticThumbDrawable); staticThumbShader = this.staticThumbShader; } shaderToUse = staticThumbShader; orientation = thumbOrientation; invert = thumbInvert; } float crossfadeProgress = currentAlpha; if (crossfadeByScale > 0) { currentAlpha = Math.min(currentAlpha + crossfadeByScale * currentAlpha, 1); } if (drawable != null) { if (crossfadeAlpha != 0) { if (previousAlpha != 1f && (drawable == currentImageDrawable || drawable == currentMediaDrawable) && staticThumbDrawable != null) { if (useRoundForThumb && staticThumbShader == null) { updateDrawableRadius(staticThumbDrawable); staticThumbShader = this.staticThumbShader; } drawDrawable(canvas, staticThumbDrawable, (int) (overrideAlpha * 255), staticThumbShader, orientation, invert, backgroundThreadDrawHolder); } if (crossfadeWithThumb && animationNotReady) { drawDrawable(canvas, drawable, (int) (overrideAlpha * 255), shaderToUse, orientation, invert, backgroundThreadDrawHolder); } else { Drawable thumbDrawable = null; if (crossfadeWithThumb && currentAlpha != 1.0f) { BitmapShader thumbShaderToUse = null; if (drawable == currentImageDrawable || drawable == currentMediaDrawable) { if (crossfadeImage != null) { thumbDrawable = crossfadeImage; thumbShaderToUse = crossfadeShader; } else if (currentThumbDrawable != null) { thumbDrawable = currentThumbDrawable; thumbShaderToUse = thumbShader; } else if (staticThumbDrawable != null) { thumbDrawable = staticThumbDrawable; if (useRoundForThumb && staticThumbShader == null) { updateDrawableRadius(staticThumbDrawable); staticThumbShader = this.staticThumbShader; } thumbShaderToUse = staticThumbShader; } } else if (drawable == currentThumbDrawable || drawable == crossfadeImage) { if (staticThumbDrawable != null) { thumbDrawable = staticThumbDrawable; if (useRoundForThumb && staticThumbShader == null) { updateDrawableRadius(staticThumbDrawable); staticThumbShader = this.staticThumbShader; } thumbShaderToUse = staticThumbShader; } } else if (drawable == staticThumbDrawable) { if (crossfadeImage != null) { thumbDrawable = crossfadeImage; thumbShaderToUse = crossfadeShader; } } if (thumbDrawable != null) { int alpha; if (thumbDrawable instanceof SvgHelper.SvgDrawable || thumbDrawable instanceof Emoji.EmojiDrawable) { alpha = (int) (overrideAlpha * (1.0f - currentAlpha) * 255); } else { alpha = (int) (overrideAlpha * previousAlpha * 255); } drawDrawable(canvas, thumbDrawable, alpha, thumbShaderToUse, thumbOrientation, thumbInvert, backgroundThreadDrawHolder); if (alpha != 255 && thumbDrawable instanceof Emoji.EmojiDrawable) { thumbDrawable.setAlpha(255); } } } boolean restore = false; if (crossfadeByScale > 0 && currentAlpha < 1 && crossfadingWithThumb) { canvas.save(); restore = true; roundPath.rewind(); AndroidUtilities.rectTmp.set(imageX, imageY, imageX + imageW, imageY + imageH); for (int a = 0; a < roundRadius.length; a++) { radii[a * 2] = roundRadius[a]; radii[a * 2 + 1] = roundRadius[a]; } roundPath.addRoundRect(AndroidUtilities.rectTmp, radii, Path.Direction.CW); canvas.clipPath(roundPath); float s = 1f + crossfadeByScale * (1f - CubicBezierInterpolator.EASE_IN.getInterpolation(crossfadeProgress)); canvas.scale(s, s, getCenterX(), getCenterY()); } drawDrawable(canvas, drawable, (int) (overrideAlpha * currentAlpha * 255), shaderToUse, orientation, invert, backgroundThreadDrawHolder); if (restore) { canvas.restore(); } } } else { drawDrawable(canvas, drawable, (int) (overrideAlpha * 255), shaderToUse, orientation, invert, backgroundThreadDrawHolder); } checkAlphaAnimation(animationNotReady && crossfadeWithThumb, backgroundThreadDrawHolder); result = true; } else if (staticThumbDrawable != null) { if (staticThumbDrawable instanceof VectorAvatarThumbDrawable) { ((VectorAvatarThumbDrawable) staticThumbDrawable).setParent(this); } drawDrawable(canvas, staticThumbDrawable, (int) (overrideAlpha * 255), null, thumbOrientation, thumbInvert, backgroundThreadDrawHolder); checkAlphaAnimation(animationNotReady, backgroundThreadDrawHolder); result = true; } else { checkAlphaAnimation(animationNotReady, backgroundThreadDrawHolder); } if (drawable == null && animationNotReady && !drawInBackground) { invalidate(); } } catch (Exception e) { FileLog.e(e); } if (gradientBitmap != null && currentImageKey != null) { canvas.restore(); } if (result && isVisible && decorators != null) { for (int i = 0; i < decorators.size(); i++) { decorators.get(i).onDraw(canvas, this); } } return result; } public void setManualAlphaAnimator(boolean value) { manualAlphaAnimator = value; } @Keep public float getCurrentAlpha() { return currentAlpha; } @Keep public void setCurrentAlpha(float value) { currentAlpha = value; } public Drawable getDrawable() { if (currentMediaDrawable != null) { return currentMediaDrawable; } else if (currentImageDrawable != null) { return currentImageDrawable; } else if (currentThumbDrawable != null) { return currentThumbDrawable; } else if (staticThumbDrawable != null) { return staticThumbDrawable; } return null; } public Bitmap getBitmap() { RLottieDrawable lottieDrawable = getLottieAnimation(); if (lottieDrawable != null && lottieDrawable.hasBitmap()) { return lottieDrawable.getAnimatedBitmap(); } AnimatedFileDrawable animation = getAnimation(); if (animation != null && animation.hasBitmap()) { return animation.getAnimatedBitmap(); } else if (currentMediaDrawable instanceof BitmapDrawable && !(currentMediaDrawable instanceof AnimatedFileDrawable) && !(currentMediaDrawable instanceof RLottieDrawable)) { return ((BitmapDrawable) currentMediaDrawable).getBitmap(); } else if (currentImageDrawable instanceof BitmapDrawable && !(currentImageDrawable instanceof AnimatedFileDrawable) && !(currentMediaDrawable instanceof RLottieDrawable)) { return ((BitmapDrawable) currentImageDrawable).getBitmap(); } else if (currentThumbDrawable instanceof BitmapDrawable && !(currentThumbDrawable instanceof AnimatedFileDrawable) && !(currentMediaDrawable instanceof RLottieDrawable)) { return ((BitmapDrawable) currentThumbDrawable).getBitmap(); } else if (staticThumbDrawable instanceof BitmapDrawable) { return ((BitmapDrawable) staticThumbDrawable).getBitmap(); } return null; } public BitmapHolder getBitmapSafe() { Bitmap bitmap = null; String key = null; AnimatedFileDrawable animation = getAnimation(); RLottieDrawable lottieDrawable = getLottieAnimation(); int orientation = 0; if (lottieDrawable != null && lottieDrawable.hasBitmap()) { bitmap = lottieDrawable.getAnimatedBitmap(); } else if (animation != null && animation.hasBitmap()) { bitmap = animation.getAnimatedBitmap(); orientation = animation.getOrientation(); if (orientation != 0) { return new BitmapHolder(Bitmap.createBitmap(bitmap), null, orientation); } } else if (currentMediaDrawable instanceof BitmapDrawable && !(currentMediaDrawable instanceof AnimatedFileDrawable) && !(currentMediaDrawable instanceof RLottieDrawable)) { bitmap = ((BitmapDrawable) currentMediaDrawable).getBitmap(); key = currentMediaKey; } else if (currentImageDrawable instanceof BitmapDrawable && !(currentImageDrawable instanceof AnimatedFileDrawable) && !(currentMediaDrawable instanceof RLottieDrawable)) { bitmap = ((BitmapDrawable) currentImageDrawable).getBitmap(); key = currentImageKey; } else if (currentThumbDrawable instanceof BitmapDrawable && !(currentThumbDrawable instanceof AnimatedFileDrawable) && !(currentMediaDrawable instanceof RLottieDrawable)) { bitmap = ((BitmapDrawable) currentThumbDrawable).getBitmap(); key = currentThumbKey; } else if (staticThumbDrawable instanceof BitmapDrawable) { bitmap = ((BitmapDrawable) staticThumbDrawable).getBitmap(); } if (bitmap != null) { return new BitmapHolder(bitmap, key, orientation); } return null; } public BitmapHolder getDrawableSafe() { Drawable drawable = null; String key = null; if (currentMediaDrawable instanceof BitmapDrawable && !(currentMediaDrawable instanceof AnimatedFileDrawable) && !(currentMediaDrawable instanceof RLottieDrawable)) { drawable = currentMediaDrawable; key = currentMediaKey; } else if (currentImageDrawable instanceof BitmapDrawable && !(currentImageDrawable instanceof AnimatedFileDrawable) && !(currentMediaDrawable instanceof RLottieDrawable)) { drawable = currentImageDrawable; key = currentImageKey; } else if (currentThumbDrawable instanceof BitmapDrawable && !(currentThumbDrawable instanceof AnimatedFileDrawable) && !(currentMediaDrawable instanceof RLottieDrawable)) { drawable = currentThumbDrawable; key = currentThumbKey; } else if (staticThumbDrawable instanceof BitmapDrawable) { drawable = staticThumbDrawable; } if (drawable != null) { return new BitmapHolder(drawable, key, 0); } return null; } public Drawable getThumb() { return currentThumbDrawable; } public Bitmap getThumbBitmap() { if (currentThumbDrawable instanceof BitmapDrawable) { return ((BitmapDrawable) currentThumbDrawable).getBitmap(); } else if (staticThumbDrawable instanceof BitmapDrawable) { return ((BitmapDrawable) staticThumbDrawable).getBitmap(); } return null; } public BitmapHolder getThumbBitmapSafe() { Bitmap bitmap = null; String key = null; if (currentThumbDrawable instanceof BitmapDrawable) { bitmap = ((BitmapDrawable) currentThumbDrawable).getBitmap(); key = currentThumbKey; } else if (staticThumbDrawable instanceof BitmapDrawable) { bitmap = ((BitmapDrawable) staticThumbDrawable).getBitmap(); } if (bitmap != null) { return new BitmapHolder(bitmap, key, 0); } return null; } public int getBitmapWidth() { Drawable drawable = getDrawable(); AnimatedFileDrawable animation = getAnimation(); if (animation != null) { return imageOrientation % 360 == 0 || imageOrientation % 360 == 180 ? animation.getIntrinsicWidth() : animation.getIntrinsicHeight(); } RLottieDrawable lottieDrawable = getLottieAnimation(); if (lottieDrawable != null) { return lottieDrawable.getIntrinsicWidth(); } Bitmap bitmap = getBitmap(); if (bitmap == null) { if (staticThumbDrawable != null) { return staticThumbDrawable.getIntrinsicWidth(); } return 1; } return imageOrientation % 360 == 0 || imageOrientation % 360 == 180 ? bitmap.getWidth() : bitmap.getHeight(); } public int getBitmapHeight() { Drawable drawable = getDrawable(); AnimatedFileDrawable animation = getAnimation(); if (animation != null) { return imageOrientation % 360 == 0 || imageOrientation % 360 == 180 ? animation.getIntrinsicHeight() : animation.getIntrinsicWidth(); } RLottieDrawable lottieDrawable = getLottieAnimation(); if (lottieDrawable != null) { return lottieDrawable.getIntrinsicHeight(); } Bitmap bitmap = getBitmap(); if (bitmap == null) { if (staticThumbDrawable != null) { return staticThumbDrawable.getIntrinsicHeight(); } return 1; } return imageOrientation % 360 == 0 || imageOrientation % 360 == 180 ? bitmap.getHeight() : bitmap.getWidth(); } public void setVisible(boolean value, boolean invalidate) { if (isVisible == value) { return; } isVisible = value; if (invalidate) { invalidate(); } } public void invalidate() { if (parentView == null) { return; } if (invalidateAll) { parentView.invalidate(); } else { parentView.invalidate((int) imageX, (int) imageY, (int) (imageX + imageW), (int) (imageY + imageH)); } } public void getParentPosition(int[] position) { if (parentView == null) { return; } parentView.getLocationInWindow(position); } public boolean getVisible() { return isVisible; } @Keep public void setAlpha(float value) { overrideAlpha = value; } @Keep public float getAlpha() { return overrideAlpha; } public void setCrossfadeAlpha(byte value) { crossfadeAlpha = value; } public boolean hasImageSet() { return currentImageDrawable != null || currentMediaDrawable != null || currentThumbDrawable != null || staticThumbDrawable != null || currentImageKey != null || currentMediaKey != null; } public boolean hasMediaSet() { return currentMediaDrawable != null; } public boolean hasBitmapImage() { return currentImageDrawable != null || currentThumbDrawable != null || staticThumbDrawable != null || currentMediaDrawable != null; } public boolean hasImageLoaded() { return currentImageDrawable != null || currentMediaDrawable != null; } public boolean hasNotThumb() { return currentImageDrawable != null || currentMediaDrawable != null || staticThumbDrawable instanceof VectorAvatarThumbDrawable; } public boolean hasNotThumbOrOnlyStaticThumb() { return currentImageDrawable != null || currentMediaDrawable != null || staticThumbDrawable instanceof VectorAvatarThumbDrawable || (staticThumbDrawable != null && !(staticThumbDrawable instanceof AvatarDrawable) && currentImageKey == null && currentMediaKey == null); } public boolean hasStaticThumb() { return staticThumbDrawable != null; } public void setAspectFit(boolean value) { isAspectFit = value; } public boolean isAspectFit() { return isAspectFit; } public void setParentView(View view) { View oldParent = parentView; parentView = view; AnimatedFileDrawable animation = getAnimation(); if (animation != null && attachedToWindow) { animation.setParentView(parentView); } } public void setImageX(float x) { imageX = x; } public void setImageY(float y) { imageY = y; } public void setImageWidth(int width) { imageW = width; } public void setImageCoords(float x, float y, float width, float height) { imageX = x; imageY = y; imageW = width; imageH = height; } public void setImageCoords(Rect bounds) { if (bounds != null) { imageX = bounds.left; imageY = bounds.top; imageW = bounds.width(); imageH = bounds.height(); } } public void setImageCoords(RectF bounds) { if (bounds != null) { imageX = bounds.left; imageY = bounds.top; imageW = bounds.width(); imageH = bounds.height(); } } public void setSideClip(float value) { sideClip = value; } public float getCenterX() { return imageX + imageW / 2.0f; } public float getCenterY() { return imageY + imageH / 2.0f; } public float getImageX() { return imageX; } public float getImageX2() { return imageX + imageW; } public float getImageY() { return imageY; } public float getImageY2() { return imageY + imageH; } public float getImageWidth() { return imageW; } public float getImageHeight() { return imageH; } public float getImageAspectRatio() { return imageOrientation % 180 != 0 ? drawRegion.height() / drawRegion.width() : drawRegion.width() / drawRegion.height(); } public String getExt() { return currentExt; } public boolean isInsideImage(float x, float y) { return x >= imageX && x <= imageX + imageW && y >= imageY && y <= imageY + imageH; } public RectF getDrawRegion() { return drawRegion; } public int getNewGuid() { return ++currentGuid; } public String getImageKey() { return currentImageKey; } public String getMediaKey() { return currentMediaKey; } public String getThumbKey() { return currentThumbKey; } public long getSize() { return currentSize; } public ImageLocation getMediaLocation() { return currentMediaLocation; } public ImageLocation getImageLocation() { return currentImageLocation; } public ImageLocation getThumbLocation() { return currentThumbLocation; } public String getMediaFilter() { return currentMediaFilter; } public String getImageFilter() { return currentImageFilter; } public String getThumbFilter() { return currentThumbFilter; } public int getCacheType() { return currentCacheType; } public void setForcePreview(boolean value) { forcePreview = value; } public void setForceCrossfade(boolean value) { forceCrossfade = value; } public boolean isForcePreview() { return forcePreview; } public void setRoundRadius(int value) { setRoundRadius(new int[]{value, value, value, value}); } public void setRoundRadius(int tl, int tr, int br, int bl) { setRoundRadius(new int[]{tl, tr, br, bl}); } public void setRoundRadius(int[] value) { boolean changed = false; int firstValue = value[0]; isRoundRect = true; for (int a = 0; a < roundRadius.length; a++) { if (roundRadius[a] != value[a]) { changed = true; } if (firstValue != value[a]) { isRoundRect = false; } roundRadius[a] = value[a]; } if (changed) { if (currentImageDrawable != null && imageShader == null) { updateDrawableRadius(currentImageDrawable); } if (currentMediaDrawable != null && mediaShader == null) { updateDrawableRadius(currentMediaDrawable); } if (currentThumbDrawable != null) { updateDrawableRadius(currentThumbDrawable); } if (staticThumbDrawable != null) { updateDrawableRadius(staticThumbDrawable); } } } public void setMark(Object mark) { this.mark = mark; } public Object getMark() { return mark; } public void setCurrentAccount(int value) { currentAccount = value; } public int[] getRoundRadius() { return roundRadius; } public Object getParentObject() { return currentParentObject; } public void setNeedsQualityThumb(boolean value) { needsQualityThumb = value; } public void setQualityThumbDocument(TLRPC.Document document) { qulityThumbDocument = document; } public TLRPC.Document getQualityThumbDocument() { return qulityThumbDocument; } public void setCrossfadeWithOldImage(boolean value) { crossfadeWithOldImage = value; } public boolean isCrossfadingWithOldImage() { return crossfadeWithOldImage && crossfadeImage != null && !crossfadingWithThumb; } public boolean isNeedsQualityThumb() { return needsQualityThumb; } public boolean isCurrentKeyQuality() { return currentKeyQuality; } public int getCurrentAccount() { return currentAccount; } public void setShouldGenerateQualityThumb(boolean value) { shouldGenerateQualityThumb = value; } public boolean isShouldGenerateQualityThumb() { return shouldGenerateQualityThumb; } public void setAllowStartAnimation(boolean value) { allowStartAnimation = value; } public void setAllowLottieVibration(boolean allow) { allowLottieVibration = allow; } public boolean getAllowStartAnimation() { return allowStartAnimation; } public void setAllowStartLottieAnimation(boolean value) { allowStartLottieAnimation = value; } public void setAllowDecodeSingleFrame(boolean value) { allowDecodeSingleFrame = value; } public void setAutoRepeat(int value) { autoRepeat = value; RLottieDrawable drawable = getLottieAnimation(); if (drawable != null) { drawable.setAutoRepeat(value); } } public void setAutoRepeatCount(int count) { autoRepeatCount = count; if (getLottieAnimation() != null) { getLottieAnimation().setAutoRepeatCount(count); } else { animatedFileDrawableRepeatMaxCount = count; if (getAnimation() != null) { getAnimation().repeatCount = 0; } } } public void setAutoRepeatTimeout(long timeout) { autoRepeatTimeout = timeout; RLottieDrawable drawable = getLottieAnimation(); if (drawable != null) { drawable.setAutoRepeatTimeout(autoRepeatTimeout); } } public void setUseSharedAnimationQueue(boolean value) { useSharedAnimationQueue = value; } public boolean isAllowStartAnimation() { return allowStartAnimation; } public void startAnimation() { AnimatedFileDrawable animation = getAnimation(); if (animation != null) { animation.setUseSharedQueue(useSharedAnimationQueue); animation.start(); } else { RLottieDrawable rLottieDrawable = getLottieAnimation(); if (rLottieDrawable != null && !rLottieDrawable.isRunning()) { rLottieDrawable.restart(); } } } public void stopAnimation() { AnimatedFileDrawable animation = getAnimation(); if (animation != null) { animation.stop(); } else { RLottieDrawable rLottieDrawable = getLottieAnimation(); if (rLottieDrawable != null && !rLottieDrawable.isRunning()) { rLottieDrawable.stop(); } } } public boolean isAnimationRunning() { AnimatedFileDrawable animation = getAnimation(); return animation != null && animation.isRunning(); } public AnimatedFileDrawable getAnimation() { if (currentMediaDrawable instanceof AnimatedFileDrawable) { return (AnimatedFileDrawable) currentMediaDrawable; } else if (currentImageDrawable instanceof AnimatedFileDrawable) { return (AnimatedFileDrawable) currentImageDrawable; } else if (currentThumbDrawable instanceof AnimatedFileDrawable) { return (AnimatedFileDrawable) currentThumbDrawable; } else if (staticThumbDrawable instanceof AnimatedFileDrawable) { return (AnimatedFileDrawable) staticThumbDrawable; } return null; } public RLottieDrawable getLottieAnimation() { if (currentMediaDrawable instanceof RLottieDrawable) { return (RLottieDrawable) currentMediaDrawable; } else if (currentImageDrawable instanceof RLottieDrawable) { return (RLottieDrawable) currentImageDrawable; } else if (currentThumbDrawable instanceof RLottieDrawable) { return (RLottieDrawable) currentThumbDrawable; } else if (staticThumbDrawable instanceof RLottieDrawable) { return (RLottieDrawable) staticThumbDrawable; } return null; } protected int getTag(int type) { if (type == TYPE_THUMB) { return thumbTag; } else if (type == TYPE_MEDIA) { return mediaTag; } else { return imageTag; } } protected void setTag(int value, int type) { if (type == TYPE_THUMB) { thumbTag = value; } else if (type == TYPE_MEDIA) { mediaTag = value; } else { imageTag = value; } } public void setParam(int value) { param = value; } public int getParam() { return param; } protected boolean setImageBitmapByKey(Drawable drawable, String key, int type, boolean memCache, int guid) { if (drawable == null || key == null || currentGuid != guid) { return false; } if (type == TYPE_IMAGE) { if (!key.equals(currentImageKey)) { return false; } if (delegate != null) { delegate.didSetImageBitmap(type, key, drawable); } boolean allowCrossFade = true; if (!(drawable instanceof AnimatedFileDrawable)) { ImageLoader.getInstance().incrementUseCount(currentImageKey); if (videoThumbIsSame) { allowCrossFade = drawable != currentImageDrawable && currentAlpha >= 1; } } else { AnimatedFileDrawable animatedFileDrawable = (AnimatedFileDrawable) drawable; animatedFileDrawable.setStartEndTime(startTime, endTime); if (animatedFileDrawable.isWebmSticker) { ImageLoader.getInstance().incrementUseCount(currentImageKey); } if (videoThumbIsSame) { allowCrossFade = !animatedFileDrawable.hasBitmap(); } } currentImageDrawable = drawable; if (drawable instanceof ExtendedBitmapDrawable) { imageOrientation = ((ExtendedBitmapDrawable) drawable).getOrientation(); imageInvert = ((ExtendedBitmapDrawable) drawable).getInvert(); } updateDrawableRadius(drawable); if (allowCrossFade && isVisible && (!memCache && !forcePreview || forceCrossfade) && crossfadeDuration != 0) { boolean allowCrossfade = true; if (currentMediaDrawable instanceof RLottieDrawable && ((RLottieDrawable) currentMediaDrawable).hasBitmap()) { allowCrossfade = false; } else if (currentMediaDrawable instanceof AnimatedFileDrawable && ((AnimatedFileDrawable) currentMediaDrawable).hasBitmap()) { allowCrossfade = false; } else if (currentImageDrawable instanceof RLottieDrawable) { allowCrossfade = staticThumbDrawable instanceof LoadingStickerDrawable || staticThumbDrawable instanceof SvgHelper.SvgDrawable || staticThumbDrawable instanceof Emoji.EmojiDrawable; } if (allowCrossfade && (currentThumbDrawable != null || staticThumbDrawable != null || forceCrossfade)) { if (currentThumbDrawable != null && staticThumbDrawable != null) { previousAlpha = currentAlpha; } else { previousAlpha = 1f; } currentAlpha = 0.0f; lastUpdateAlphaTime = System.currentTimeMillis(); crossfadeWithThumb = crossfadeImage != null || currentThumbDrawable != null || staticThumbDrawable != null; } } else { currentAlpha = 1.0f; previousAlpha = 1f; } } else if (type == TYPE_MEDIA) { if (!key.equals(currentMediaKey)) { return false; } if (delegate != null) { delegate.didSetImageBitmap(type, key, drawable); } if (!(drawable instanceof AnimatedFileDrawable)) { ImageLoader.getInstance().incrementUseCount(currentMediaKey); } else { AnimatedFileDrawable animatedFileDrawable = (AnimatedFileDrawable) drawable; animatedFileDrawable.setStartEndTime(startTime, endTime); if (animatedFileDrawable.isWebmSticker) { ImageLoader.getInstance().incrementUseCount(currentMediaKey); } if (videoThumbIsSame && (currentThumbDrawable instanceof AnimatedFileDrawable || currentImageDrawable instanceof AnimatedFileDrawable)) { long currentTimestamp = 0; if (currentThumbDrawable instanceof AnimatedFileDrawable) { currentTimestamp = ((AnimatedFileDrawable) currentThumbDrawable).getLastFrameTimestamp(); } animatedFileDrawable.seekTo(currentTimestamp, true, true); } } currentMediaDrawable = drawable; updateDrawableRadius(drawable); if (currentImageDrawable == null) { boolean allowCrossfade = true; if (!memCache && !forcePreview || forceCrossfade) { if (currentThumbDrawable == null && staticThumbDrawable == null || currentAlpha == 1.0f || forceCrossfade) { if (currentThumbDrawable != null && staticThumbDrawable != null) { previousAlpha = currentAlpha; } else { previousAlpha = 1f; } currentAlpha = 0.0f; lastUpdateAlphaTime = System.currentTimeMillis(); crossfadeWithThumb = crossfadeImage != null || currentThumbDrawable != null || staticThumbDrawable != null; } } else { currentAlpha = 1.0f; previousAlpha = 1f; } } } else if (type == TYPE_THUMB) { if (currentThumbDrawable != null) { return false; } if (!forcePreview) { AnimatedFileDrawable animation = getAnimation(); if (animation != null && animation.hasBitmap()) { return false; } if (currentImageDrawable != null && !(currentImageDrawable instanceof AnimatedFileDrawable) || currentMediaDrawable != null && !(currentMediaDrawable instanceof AnimatedFileDrawable)) { return false; } } if (!key.equals(currentThumbKey)) { return false; } if (delegate != null) { delegate.didSetImageBitmap(type, key, drawable); } ImageLoader.getInstance().incrementUseCount(currentThumbKey); currentThumbDrawable = drawable; if (drawable instanceof ExtendedBitmapDrawable) { thumbOrientation = ((ExtendedBitmapDrawable) drawable).getOrientation(); thumbInvert = ((ExtendedBitmapDrawable) drawable).getInvert(); } updateDrawableRadius(drawable); if (!memCache && crossfadeAlpha != 2) { if (currentParentObject instanceof MessageObject && ((MessageObject) currentParentObject).isRoundVideo() && ((MessageObject) currentParentObject).isSending()) { currentAlpha = 1.0f; previousAlpha = 1f; } else { currentAlpha = 0.0f; previousAlpha = 1f; lastUpdateAlphaTime = System.currentTimeMillis(); crossfadeWithThumb = staticThumbDrawable != null; } } else { currentAlpha = 1.0f; previousAlpha = 1f; } } if (delegate != null) { delegate.didSetImage(this, currentImageDrawable != null || currentThumbDrawable != null || staticThumbDrawable != null || currentMediaDrawable != null, currentImageDrawable == null && currentMediaDrawable == null, memCache); } if (drawable instanceof AnimatedFileDrawable) { AnimatedFileDrawable fileDrawable = (AnimatedFileDrawable) drawable; fileDrawable.setUseSharedQueue(useSharedAnimationQueue); if (attachedToWindow) { fileDrawable.addParent(this); } if (allowStartAnimation && currentOpenedLayerFlags == 0) { fileDrawable.checkRepeat(); } fileDrawable.setAllowDecodeSingleFrame(allowDecodeSingleFrame); animationReadySent = false; if (parentView != null) { parentView.invalidate(); } } else if (drawable instanceof RLottieDrawable) { RLottieDrawable fileDrawable = (RLottieDrawable) drawable; if (attachedToWindow) { fileDrawable.addParentView(this); } if (allowStartLottieAnimation && (!fileDrawable.isHeavyDrawable() || currentOpenedLayerFlags == 0)) { fileDrawable.start(); } fileDrawable.setAllowDecodeSingleFrame(true); fileDrawable.setAutoRepeat(autoRepeat); fileDrawable.setAutoRepeatCount(autoRepeatCount); fileDrawable.setAutoRepeatTimeout(autoRepeatTimeout); fileDrawable.setAllowDrawFramesWhileCacheGenerating(allowDrawWhileCacheGenerating); animationReadySent = false; } invalidate(); return true; } public void setMediaStartEndTime(long startTime, long endTime) { this.startTime = startTime; this.endTime = endTime; if (currentMediaDrawable instanceof AnimatedFileDrawable) { ((AnimatedFileDrawable) currentMediaDrawable).setStartEndTime(startTime, endTime); } } public void recycleBitmap(String newKey, int type) { String key; Drawable image; if (type == TYPE_MEDIA) { key = currentMediaKey; image = currentMediaDrawable; } else if (type == TYPE_CROSSFDADE) { key = crossfadeKey; image = crossfadeImage; } else if (type == TYPE_THUMB) { key = currentThumbKey; image = currentThumbDrawable; } else { key = currentImageKey; image = currentImageDrawable; } if (key != null && (key.startsWith("-") || key.startsWith("strippedmessage-"))) { String replacedKey = ImageLoader.getInstance().getReplacedKey(key); if (replacedKey != null) { key = replacedKey; } } if (image instanceof RLottieDrawable) { RLottieDrawable lottieDrawable = (RLottieDrawable) image; lottieDrawable.removeParentView(this); } if (image instanceof AnimatedFileDrawable) { AnimatedFileDrawable animatedFileDrawable = (AnimatedFileDrawable) image; animatedFileDrawable.removeParent(this); } if (key != null && (newKey == null || !newKey.equals(key)) && image != null) { if (image instanceof RLottieDrawable) { RLottieDrawable fileDrawable = (RLottieDrawable) image; boolean canDelete = ImageLoader.getInstance().decrementUseCount(key); if (!ImageLoader.getInstance().isInMemCache(key, true)) { if (canDelete) { fileDrawable.recycle(false); } } } else if (image instanceof AnimatedFileDrawable) { AnimatedFileDrawable fileDrawable = (AnimatedFileDrawable) image; if (fileDrawable.isWebmSticker) { boolean canDelete = ImageLoader.getInstance().decrementUseCount(key); if (!ImageLoader.getInstance().isInMemCache(key, true)) { if (canDelete) { fileDrawable.recycle(); } } else if (canDelete) { fileDrawable.stop(); } } else { if (fileDrawable.getParents().isEmpty()) { fileDrawable.recycle(); } } } else if (image instanceof BitmapDrawable) { Bitmap bitmap = ((BitmapDrawable) image).getBitmap(); boolean canDelete = ImageLoader.getInstance().decrementUseCount(key); if (!ImageLoader.getInstance().isInMemCache(key, false)) { if (canDelete) { ArrayList<Bitmap> bitmapToRecycle = new ArrayList<>(); bitmapToRecycle.add(bitmap); AndroidUtilities.recycleBitmaps(bitmapToRecycle); } } } } if (type == TYPE_MEDIA) { currentMediaKey = null; currentMediaDrawable = null; mediaShader = null; } else if (type == TYPE_CROSSFDADE) { crossfadeKey = null; crossfadeImage = null; crossfadeShader = null; } else if (type == TYPE_THUMB) { currentThumbDrawable = null; currentThumbKey = null; thumbShader = null; } else { currentImageDrawable = null; currentImageKey = null; imageShader = null; } } public void setCrossfadeDuration(int duration) { crossfadeDuration = duration; } public void setCrossfadeByScale(float value) { crossfadeByScale = value; } @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.didReplacedPhotoInMemCache) { String oldKey = (String) args[0]; if (currentMediaKey != null && currentMediaKey.equals(oldKey)) { currentMediaKey = (String) args[1]; currentMediaLocation = (ImageLocation) args[2]; if (setImageBackup != null) { setImageBackup.mediaLocation = (ImageLocation) args[2]; } } if (currentImageKey != null && currentImageKey.equals(oldKey)) { currentImageKey = (String) args[1]; currentImageLocation = (ImageLocation) args[2]; if (setImageBackup != null) { setImageBackup.imageLocation = (ImageLocation) args[2]; } } if (currentThumbKey != null && currentThumbKey.equals(oldKey)) { currentThumbKey = (String) args[1]; currentThumbLocation = (ImageLocation) args[2]; if (setImageBackup != null) { setImageBackup.thumbLocation = (ImageLocation) args[2]; } } } else if (id == NotificationCenter.stopAllHeavyOperations) { Integer layer = (Integer) args[0]; if (currentLayerNum >= layer) { return; } currentOpenedLayerFlags |= layer; if (currentOpenedLayerFlags != 0) { RLottieDrawable lottieDrawable = getLottieAnimation(); if (lottieDrawable != null && lottieDrawable.isHeavyDrawable()) { lottieDrawable.stop(); } AnimatedFileDrawable animatedFileDrawable = getAnimation(); if (animatedFileDrawable != null) { animatedFileDrawable.stop(); } } } else if (id == NotificationCenter.startAllHeavyOperations) { Integer layer = (Integer) args[0]; if (currentLayerNum >= layer || currentOpenedLayerFlags == 0) { return; } currentOpenedLayerFlags &= ~layer; if (currentOpenedLayerFlags == 0) { RLottieDrawable lottieDrawable = getLottieAnimation(); if (lottieDrawable != null) { lottieDrawable.setAllowVibration(allowLottieVibration); } if (allowStartLottieAnimation && lottieDrawable != null && lottieDrawable.isHeavyDrawable()) { lottieDrawable.start(); } AnimatedFileDrawable animatedFileDrawable = getAnimation(); if (allowStartAnimation && animatedFileDrawable != null) { animatedFileDrawable.checkRepeat(); invalidate(); } } } } public void startCrossfadeFromStaticThumb(Bitmap thumb) { startCrossfadeFromStaticThumb(new BitmapDrawable(null, thumb)); } public void startCrossfadeFromStaticThumb(Drawable thumb) { currentThumbKey = null; currentThumbDrawable = null; thumbShader = null; staticThumbShader = null; roundPaint.setShader(null); setStaticDrawable(thumb); crossfadeWithThumb = true; currentAlpha = 0f; updateDrawableRadius(staticThumbDrawable); } public void setUniqKeyPrefix(String prefix) { uniqKeyPrefix = prefix; } public String getUniqKeyPrefix() { return uniqKeyPrefix; } public void addLoadingImageRunnable(Runnable loadOperationRunnable) { loadingOperations.add(loadOperationRunnable); } public ArrayList<Runnable> getLoadingOperations() { return loadingOperations; } public void moveImageToFront() { ImageLoader.getInstance().moveToFront(currentImageKey); ImageLoader.getInstance().moveToFront(currentThumbKey); } public void moveLottieToFront() { BitmapDrawable drawable = null; String key = null; if (currentMediaDrawable instanceof RLottieDrawable) { drawable = (BitmapDrawable) currentMediaDrawable; key = currentMediaKey; } else if (currentImageDrawable instanceof RLottieDrawable) { drawable = (BitmapDrawable) currentImageDrawable; key = currentImageKey; } if (key != null && drawable != null) { ImageLoader.getInstance().moveToFront(key); if (!ImageLoader.getInstance().isInMemCache(key, true)) { ImageLoader.getInstance().getLottieMemCahce().put(key, drawable); } } } public View getParentView() { return parentView; } public boolean isAttachedToWindow() { return attachedToWindow; } public void setVideoThumbIsSame(boolean b) { videoThumbIsSame = b; } public void setAllowLoadingOnAttachedOnly(boolean b) { allowLoadingOnAttachedOnly = b; } public void setSkipUpdateFrame(boolean skipUpdateFrame) { this.skipUpdateFrame = skipUpdateFrame; } public void setCurrentTime(long time) { this.currentTime = time; } public void setFileLoadingPriority(int fileLoadingPriority) { if (this.fileLoadingPriority != fileLoadingPriority) { this.fileLoadingPriority = fileLoadingPriority; if (attachedToWindow && hasImageSet()) { ImageLoader.getInstance().changeFileLoadingPriorityForImageReceiver(this); } } } public void bumpPriority() { ImageLoader.getInstance().changeFileLoadingPriorityForImageReceiver(this); } public int getFileLoadingPriority() { return fileLoadingPriority; } public BackgroundThreadDrawHolder setDrawInBackgroundThread(BackgroundThreadDrawHolder holder, int threadIndex) { if (holder == null) { holder = new BackgroundThreadDrawHolder(); } holder.threadIndex = threadIndex; holder.animation = getAnimation(); holder.lottieDrawable = getLottieAnimation(); for (int i = 0; i < 4; i++) { holder.roundRadius[i] = roundRadius[i]; } holder.mediaDrawable = currentMediaDrawable; holder.mediaShader = mediaShader; holder.imageDrawable = currentImageDrawable; holder.imageShader = imageShader; holder.thumbDrawable = currentThumbDrawable; holder.thumbShader = thumbShader; holder.staticThumbShader = staticThumbShader; holder.staticThumbDrawable = staticThumbDrawable; holder.crossfadeImage = crossfadeImage; holder.colorFilter = colorFilter; holder.crossfadingWithThumb = crossfadingWithThumb; holder.crossfadeWithOldImage = crossfadeWithOldImage; holder.currentAlpha = currentAlpha; holder.previousAlpha = previousAlpha; holder.crossfadeShader = crossfadeShader; holder.animationNotReady = holder.animation != null && !holder.animation.hasBitmap() || holder.lottieDrawable != null && !holder.lottieDrawable.hasBitmap(); holder.imageX = imageX; holder.imageY = imageY; holder.imageW = imageW; holder.imageH = imageH; holder.overrideAlpha = overrideAlpha; return holder; } public void clearDecorators() { if (decorators != null) { if (attachedToWindow) { for (int i = 0; i < decorators.size(); i++) { decorators.get(i).onDetachedFromWidnow(); } } decorators.clear(); } } public void addDecorator(Decorator decorator) { if (decorators == null) { decorators = new ArrayList<>(); } decorators.add(decorator); if (attachedToWindow) { decorator.onAttachedToWindow(this); } } public static class BackgroundThreadDrawHolder { public boolean animationNotReady; public float overrideAlpha; public long time; public int threadIndex; public BitmapShader staticThumbShader; private AnimatedFileDrawable animation; private RLottieDrawable lottieDrawable; private int[] roundRadius = new int[4]; private BitmapShader mediaShader; private Drawable mediaDrawable; private BitmapShader imageShader; private Drawable imageDrawable; private Drawable thumbDrawable; private BitmapShader thumbShader; private Drawable staticThumbDrawable; private float currentAlpha; private float previousAlpha; private BitmapShader crossfadeShader; public float imageH, imageW, imageX, imageY; private boolean crossfadeWithOldImage; private boolean crossfadingWithThumb; private Drawable crossfadeImage; public RectF drawRegion = new RectF(); public ColorFilter colorFilter; Paint paint; private Path roundPath; public void release() { animation = null; lottieDrawable = null; for (int i = 0; i < 4; i++) { roundRadius[i] = roundRadius[i]; } mediaDrawable = null; mediaShader = null; imageDrawable = null; imageShader = null; thumbDrawable = null; thumbShader = null; staticThumbShader = null; staticThumbDrawable = null; crossfadeImage = null; colorFilter = null; } public void setBounds(Rect bounds) { if (bounds != null) { imageX = bounds.left; imageY = bounds.top; imageW = bounds.width(); imageH = bounds.height(); } } public void getBounds(RectF out) { if (out != null) { out.left = imageX; out.top = imageY; out.right = out.left + imageW; out.bottom = out.top + imageH; } } public void getBounds(Rect out) { if (out != null) { out.left = (int) imageX; out.top = (int) imageY; out.right = (int) (out.left + imageW); out.bottom = (int) (out.top + imageH); } } } public static class ReactionLastFrame extends BitmapDrawable { public final static float LAST_FRAME_SCALE = 1.2f; public ReactionLastFrame(Bitmap bitmap) { super(bitmap); } } public static abstract class Decorator { protected abstract void onDraw(Canvas canvas, ImageReceiver imageReceiver); public void onAttachedToWindow(ImageReceiver imageReceiver) { } public void onDetachedFromWidnow() { } } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/messenger/ImageReceiver.java
41,704
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.ui; import static com.google.android.exoplayer2.Player.COMMAND_GET_TEXT; import static com.google.android.exoplayer2.Player.COMMAND_SET_VIDEO_SURFACE; import static com.google.android.exoplayer2.util.Util.getDrawable; import static java.lang.annotation.ElementType.TYPE_USE; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.opengl.GLSurfaceView; import android.os.Looper; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.SurfaceView; import android.view.TextureView; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.IntDef; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.core.content.ContextCompat; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.MediaMetadata; import com.google.android.exoplayer2.PlaybackException; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.Player.DiscontinuityReason; import com.google.android.exoplayer2.Timeline; import com.google.android.exoplayer2.Timeline.Period; import com.google.android.exoplayer2.Tracks; import com.google.android.exoplayer2.text.CueGroup; import com.google.android.exoplayer2.ui.AspectRatioFrameLayout.ResizeMode; import com.google.android.exoplayer2.util.Assertions; import com.google.android.exoplayer2.util.ErrorMessageProvider; import com.google.android.exoplayer2.util.RepeatModeUtil; import com.google.android.exoplayer2.util.Util; import com.google.android.exoplayer2.video.VideoSize; import com.google.common.collect.ImmutableList; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.ArrayList; import java.util.List; import org.checkerframework.checker.nullness.qual.EnsuresNonNullIf; import org.checkerframework.checker.nullness.qual.RequiresNonNull; /** * A high level view for {@link Player} media playbacks. It displays video, subtitles and album art * during playback, and displays playback controls using a {@link PlayerControlView}. * * <p>A PlayerView can be customized by setting attributes (or calling corresponding methods), * overriding drawables, overriding the view's layout file, or by specifying a custom view layout * file. * * <h2>Attributes</h2> * * The following attributes can be set on a PlayerView when used in a layout XML file: * * <ul> * <li><b>{@code use_artwork}</b> - Whether artwork is used if available in audio streams. * <ul> * <li>Corresponding method: {@link #setUseArtwork(boolean)} * <li>Default: {@code true} * </ul> * <li><b>{@code default_artwork}</b> - Default artwork to use if no artwork available in audio * streams. * <ul> * <li>Corresponding method: {@link #setDefaultArtwork(Drawable)} * <li>Default: {@code null} * </ul> * <li><b>{@code use_controller}</b> - Whether the playback controls can be shown. * <ul> * <li>Corresponding method: {@link #setUseController(boolean)} * <li>Default: {@code true} * </ul> * <li><b>{@code hide_on_touch}</b> - Whether the playback controls are hidden by touch events. * <ul> * <li>Corresponding method: {@link #setControllerHideOnTouch(boolean)} * <li>Default: {@code true} * </ul> * <li><b>{@code auto_show}</b> - Whether the playback controls are automatically shown when * playback starts, pauses, ends, or fails. If set to false, the playback controls can be * manually operated with {@link #showController()} and {@link #hideController()}. * <ul> * <li>Corresponding method: {@link #setControllerAutoShow(boolean)} * <li>Default: {@code true} * </ul> * <li><b>{@code hide_during_ads}</b> - Whether the playback controls are hidden during ads. * Controls are always shown during ads if they are enabled and the player is paused. * <ul> * <li>Corresponding method: {@link #setControllerHideDuringAds(boolean)} * <li>Default: {@code true} * </ul> * <li><b>{@code show_buffering}</b> - Whether the buffering spinner is displayed when the player * is buffering. Valid values are {@code never}, {@code when_playing} and {@code always}. * <ul> * <li>Corresponding method: {@link #setShowBuffering(int)} * <li>Default: {@code never} * </ul> * <li><b>{@code resize_mode}</b> - Controls how video and album art is resized within the view. * Valid values are {@code fit}, {@code fixed_width}, {@code fixed_height}, {@code fill} and * {@code zoom}. * <ul> * <li>Corresponding method: {@link #setResizeMode(int)} * <li>Default: {@code fit} * </ul> * <li><b>{@code surface_type}</b> - The type of surface view used for video playbacks. Valid * values are {@code surface_view}, {@code texture_view}, {@code spherical_gl_surface_view}, * {@code video_decoder_gl_surface_view} and {@code none}. Using {@code none} is recommended * for audio only applications, since creating the surface can be expensive. Using {@code * surface_view} is recommended for video applications. Note, TextureView can only be used in * a hardware accelerated window. When rendered in software, TextureView will draw nothing. * <ul> * <li>Corresponding method: None * <li>Default: {@code surface_view} * </ul> * <li><b>{@code shutter_background_color}</b> - The background color of the {@code exo_shutter} * view. * <ul> * <li>Corresponding method: {@link #setShutterBackgroundColor(int)} * <li>Default: {@code unset} * </ul> * <li><b>{@code keep_content_on_player_reset}</b> - Whether the currently displayed video frame * or media artwork is kept visible when the player is reset. * <ul> * <li>Corresponding method: {@link #setKeepContentOnPlayerReset(boolean)} * <li>Default: {@code false} * </ul> * <li><b>{@code player_layout_id}</b> - Specifies the id of the layout to be inflated. See below * for more details. * <ul> * <li>Corresponding method: None * <li>Default: {@code R.layout.exo_player_view} * </ul> * <li><b>{@code controller_layout_id}</b> - Specifies the id of the layout resource to be * inflated by the child {@link PlayerControlView}. See below for more details. * <ul> * <li>Corresponding method: None * <li>Default: {@code R.layout.exo_player_control_view} * </ul> * <li>All attributes that can be set on {@link PlayerControlView} and {@link DefaultTimeBar} can * also be set on a PlayerView, and will be propagated to the inflated {@link * PlayerControlView} unless the layout is overridden to specify a custom {@code * exo_controller} (see below). * </ul> * * <h2>Overriding drawables</h2> * * The drawables used by {@link PlayerControlView} (with its default layout file) can be overridden * by drawables with the same names defined in your application. See the {@link PlayerControlView} * documentation for a list of drawables that can be overridden. * * <h2>Overriding the layout file</h2> * * To customize the layout of PlayerView throughout your app, or just for certain configurations, * you can define {@code exo_player_view.xml} layout files in your application {@code res/layout*} * directories. These layouts will override the one provided by the library, and will be inflated * for use by PlayerView. The view identifies and binds its children by looking for the following * ids: * * <ul> * <li><b>{@code exo_content_frame}</b> - A frame whose aspect ratio is resized based on the video * or album art of the media being played, and the configured {@code resize_mode}. The video * surface view is inflated into this frame as its first child. * <ul> * <li>Type: {@link AspectRatioFrameLayout} * </ul> * <li><b>{@code exo_shutter}</b> - A view that's made visible when video should be hidden. This * view is typically an opaque view that covers the video surface, thereby obscuring it when * visible. Obscuring the surface in this way also helps to prevent flicker at the start of * playback when {@code surface_type="surface_view"}. * <ul> * <li>Type: {@link View} * </ul> * <li><b>{@code exo_buffering}</b> - A view that's made visible when the player is buffering. * This view typically displays a buffering spinner or animation. * <ul> * <li>Type: {@link View} * </ul> * <li><b>{@code exo_subtitles}</b> - Displays subtitles. * <ul> * <li>Type: {@link SubtitleView} * </ul> * <li><b>{@code exo_artwork}</b> - Displays album art. * <ul> * <li>Type: {@link ImageView} * </ul> * <li><b>{@code exo_error_message}</b> - Displays an error message to the user if playback fails. * <ul> * <li>Type: {@link TextView} * </ul> * <li><b>{@code exo_controller_placeholder}</b> - A placeholder that's replaced with the inflated * {@link PlayerControlView}. Ignored if an {@code exo_controller} view exists. * <ul> * <li>Type: {@link View} * </ul> * <li><b>{@code exo_controller}</b> - An already inflated {@link PlayerControlView}. Allows use * of a custom extension of {@link PlayerControlView}. {@link PlayerControlView} and {@link * DefaultTimeBar} attributes set on the PlayerView will not be automatically propagated * through to this instance. If a view exists with this id, any {@code * exo_controller_placeholder} view will be ignored. * <ul> * <li>Type: {@link PlayerControlView} * </ul> * <li><b>{@code exo_ad_overlay}</b> - A {@link FrameLayout} positioned on top of the player which * is used to show ad UI (if applicable). * <ul> * <li>Type: {@link FrameLayout} * </ul> * <li><b>{@code exo_overlay}</b> - A {@link FrameLayout} positioned on top of the player which * the app can access via {@link #getOverlayFrameLayout()}, provided for convenience. * <ul> * <li>Type: {@link FrameLayout} * </ul> * </ul> * * <p>All child views are optional and so can be omitted if not required, however where defined they * must be of the expected type. * * <h2>Specifying a custom layout file</h2> * * Defining your own {@code exo_player_view.xml} is useful to customize the layout of PlayerView * throughout your application. It's also possible to customize the layout for a single instance in * a layout file. This is achieved by setting the {@code player_layout_id} attribute on a * PlayerView. This will cause the specified layout to be inflated instead of {@code * exo_player_view.xml} for only the instance on which the attribute is set. * * @deprecated Use {@link StyledPlayerView} instead. */ @Deprecated public class PlayerView extends FrameLayout implements AdViewProvider { /** * Determines when the buffering view is shown. One of {@link #SHOW_BUFFERING_NEVER}, {@link * #SHOW_BUFFERING_WHEN_PLAYING} or {@link #SHOW_BUFFERING_ALWAYS}. */ @Documented @Retention(RetentionPolicy.SOURCE) @Target(TYPE_USE) @IntDef({SHOW_BUFFERING_NEVER, SHOW_BUFFERING_WHEN_PLAYING, SHOW_BUFFERING_ALWAYS}) public @interface ShowBuffering {} /** The buffering view is never shown. */ public static final int SHOW_BUFFERING_NEVER = 0; /** * The buffering view is shown when the player is in the {@link Player#STATE_BUFFERING buffering} * state and {@link Player#getPlayWhenReady() playWhenReady} is {@code true}. */ public static final int SHOW_BUFFERING_WHEN_PLAYING = 1; /** * The buffering view is always shown when the player is in the {@link Player#STATE_BUFFERING * buffering} state. */ public static final int SHOW_BUFFERING_ALWAYS = 2; private static final int SURFACE_TYPE_NONE = 0; private static final int SURFACE_TYPE_SURFACE_VIEW = 1; private static final int SURFACE_TYPE_TEXTURE_VIEW = 2; private static final int SURFACE_TYPE_SPHERICAL_GL_SURFACE_VIEW = 3; private static final int SURFACE_TYPE_VIDEO_DECODER_GL_SURFACE_VIEW = 4; private final ComponentListener componentListener; @Nullable private final AspectRatioFrameLayout contentFrame; @Nullable private final View shutterView; @Nullable private final View surfaceView; private final boolean surfaceViewIgnoresVideoAspectRatio; @Nullable private final ImageView artworkView; @Nullable private final SubtitleView subtitleView; @Nullable private final View bufferingView; @Nullable private final TextView errorMessageView; @Nullable private final PlayerControlView controller; @Nullable private final FrameLayout adOverlayFrameLayout; @Nullable private final FrameLayout overlayFrameLayout; @Nullable private Player player; private boolean useController; @Nullable private PlayerControlView.VisibilityListener controllerVisibilityListener; private boolean useArtwork; @Nullable private Drawable defaultArtwork; private @ShowBuffering int showBuffering; private boolean keepContentOnPlayerReset; @Nullable private ErrorMessageProvider<? super PlaybackException> errorMessageProvider; @Nullable private CharSequence customErrorMessage; private int controllerShowTimeoutMs; private boolean controllerAutoShow; private boolean controllerHideDuringAds; private boolean controllerHideOnTouch; private int textureViewRotation; private boolean isTouching; public PlayerView(Context context) { this(context, /* attrs= */ null); } public PlayerView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, /* defStyleAttr= */ 0); } @SuppressWarnings({"nullness:argument", "nullness:method.invocation"}) public PlayerView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); componentListener = new ComponentListener(); if (isInEditMode()) { contentFrame = null; shutterView = null; surfaceView = null; surfaceViewIgnoresVideoAspectRatio = false; artworkView = null; subtitleView = null; bufferingView = null; errorMessageView = null; controller = null; adOverlayFrameLayout = null; overlayFrameLayout = null; ImageView logo = new ImageView(context); if (Util.SDK_INT >= 23) { configureEditModeLogoV23(context, getResources(), logo); } else { configureEditModeLogo(context, getResources(), logo); } addView(logo); return; } boolean shutterColorSet = false; int shutterColor = 0; int playerLayoutId = R.layout.exo_player_view; boolean useArtwork = true; int defaultArtworkId = 0; boolean useController = true; int surfaceType = SURFACE_TYPE_SURFACE_VIEW; int resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT; int controllerShowTimeoutMs = PlayerControlView.DEFAULT_SHOW_TIMEOUT_MS; boolean controllerHideOnTouch = true; boolean controllerAutoShow = true; boolean controllerHideDuringAds = true; int showBuffering = SHOW_BUFFERING_NEVER; if (attrs != null) { TypedArray a = context .getTheme() .obtainStyledAttributes( attrs, R.styleable.PlayerView, defStyleAttr, /* defStyleRes= */ 0); try { shutterColorSet = a.hasValue(R.styleable.PlayerView_shutter_background_color); shutterColor = a.getColor(R.styleable.PlayerView_shutter_background_color, shutterColor); playerLayoutId = a.getResourceId(R.styleable.PlayerView_player_layout_id, playerLayoutId); useArtwork = a.getBoolean(R.styleable.PlayerView_use_artwork, useArtwork); defaultArtworkId = a.getResourceId(R.styleable.PlayerView_default_artwork, defaultArtworkId); useController = a.getBoolean(R.styleable.PlayerView_use_controller, useController); surfaceType = a.getInt(R.styleable.PlayerView_surface_type, surfaceType); resizeMode = a.getInt(R.styleable.PlayerView_resize_mode, resizeMode); controllerShowTimeoutMs = a.getInt(R.styleable.PlayerView_show_timeout, controllerShowTimeoutMs); controllerHideOnTouch = a.getBoolean(R.styleable.PlayerView_hide_on_touch, controllerHideOnTouch); controllerAutoShow = a.getBoolean(R.styleable.PlayerView_auto_show, controllerAutoShow); showBuffering = a.getInteger(R.styleable.PlayerView_show_buffering, showBuffering); keepContentOnPlayerReset = a.getBoolean( R.styleable.PlayerView_keep_content_on_player_reset, keepContentOnPlayerReset); controllerHideDuringAds = a.getBoolean(R.styleable.PlayerView_hide_during_ads, controllerHideDuringAds); } finally { a.recycle(); } } LayoutInflater.from(context).inflate(playerLayoutId, this); setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); // Content frame. contentFrame = findViewById(R.id.exo_content_frame); if (contentFrame != null) { setResizeModeRaw(contentFrame, resizeMode); } // Shutter view. shutterView = findViewById(R.id.exo_shutter); if (shutterView != null && shutterColorSet) { shutterView.setBackgroundColor(shutterColor); } // Create a surface view and insert it into the content frame, if there is one. boolean surfaceViewIgnoresVideoAspectRatio = false; if (contentFrame != null && surfaceType != SURFACE_TYPE_NONE) { ViewGroup.LayoutParams params = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); switch (surfaceType) { case SURFACE_TYPE_TEXTURE_VIEW: surfaceView = new TextureView(context); break; case SURFACE_TYPE_SPHERICAL_GL_SURFACE_VIEW: try { Class<?> clazz = Class.forName( "com.google.android.exoplayer2.video.spherical.SphericalGLSurfaceView"); surfaceView = (View) clazz.getConstructor(Context.class).newInstance(context); } catch (Exception e) { throw new IllegalStateException( "spherical_gl_surface_view requires an ExoPlayer dependency", e); } surfaceViewIgnoresVideoAspectRatio = true; break; case SURFACE_TYPE_VIDEO_DECODER_GL_SURFACE_VIEW: try { Class<?> clazz = Class.forName("com.google.android.exoplayer2.video.VideoDecoderGLSurfaceView"); surfaceView = (View) clazz.getConstructor(Context.class).newInstance(context); } catch (Exception e) { throw new IllegalStateException( "video_decoder_gl_surface_view requires an ExoPlayer dependency", e); } break; default: surfaceView = new SurfaceView(context); break; } surfaceView.setLayoutParams(params); // We don't want surfaceView to be clickable separately to the PlayerView itself, but we // do want to register as an OnClickListener so that surfaceView implementations can propagate // click events up to the PlayerView by calling their own performClick method. surfaceView.setOnClickListener(componentListener); surfaceView.setClickable(false); contentFrame.addView(surfaceView, 0); } else { surfaceView = null; } this.surfaceViewIgnoresVideoAspectRatio = surfaceViewIgnoresVideoAspectRatio; // Ad overlay frame layout. adOverlayFrameLayout = findViewById(R.id.exo_ad_overlay); // Overlay frame layout. overlayFrameLayout = findViewById(R.id.exo_overlay); // Artwork view. artworkView = findViewById(R.id.exo_artwork); this.useArtwork = useArtwork && artworkView != null; if (defaultArtworkId != 0) { defaultArtwork = ContextCompat.getDrawable(getContext(), defaultArtworkId); } // Subtitle view. subtitleView = findViewById(R.id.exo_subtitles); if (subtitleView != null) { subtitleView.setUserDefaultStyle(); subtitleView.setUserDefaultTextSize(); } // Buffering view. bufferingView = findViewById(R.id.exo_buffering); if (bufferingView != null) { bufferingView.setVisibility(View.GONE); } this.showBuffering = showBuffering; // Error message view. errorMessageView = findViewById(R.id.exo_error_message); if (errorMessageView != null) { errorMessageView.setVisibility(View.GONE); } // Playback control view. PlayerControlView customController = findViewById(R.id.exo_controller); View controllerPlaceholder = findViewById(R.id.exo_controller_placeholder); if (customController != null) { this.controller = customController; } else if (controllerPlaceholder != null) { // Propagate attrs as playbackAttrs so that PlayerControlView's custom attributes are // transferred, but standard attributes (e.g. background) are not. this.controller = new PlayerControlView(context, null, 0, attrs); controller.setId(R.id.exo_controller); controller.setLayoutParams(controllerPlaceholder.getLayoutParams()); ViewGroup parent = ((ViewGroup) controllerPlaceholder.getParent()); int controllerIndex = parent.indexOfChild(controllerPlaceholder); parent.removeView(controllerPlaceholder); parent.addView(controller, controllerIndex); } else { this.controller = null; } this.controllerShowTimeoutMs = controller != null ? controllerShowTimeoutMs : 0; this.controllerHideOnTouch = controllerHideOnTouch; this.controllerAutoShow = controllerAutoShow; this.controllerHideDuringAds = controllerHideDuringAds; this.useController = useController && controller != null; if (controller != null) { controller.hide(); controller.addVisibilityListener(/* listener= */ componentListener); } if (useController) { setClickable(true); } updateContentDescription(); } /** * Switches the view targeted by a given {@link Player}. * * @param player The player whose target view is being switched. * @param oldPlayerView The old view to detach from the player. * @param newPlayerView The new view to attach to the player. */ public static void switchTargetView( Player player, @Nullable PlayerView oldPlayerView, @Nullable PlayerView newPlayerView) { if (oldPlayerView == newPlayerView) { return; } // We attach the new view before detaching the old one because this ordering allows the player // to swap directly from one surface to another, without transitioning through a state where no // surface is attached. This is significantly more efficient and achieves a more seamless // transition when using platform provided video decoders. if (newPlayerView != null) { newPlayerView.setPlayer(player); } if (oldPlayerView != null) { oldPlayerView.setPlayer(null); } } /** Returns the player currently set on this view, or null if no player is set. */ @Nullable public Player getPlayer() { return player; } /** * Sets the {@link Player} to use. * * <p>To transition a {@link Player} from targeting one view to another, it's recommended to use * {@link #switchTargetView(Player, PlayerView, PlayerView)} rather than this method. If you do * wish to use this method directly, be sure to attach the player to the new view <em>before</em> * calling {@code setPlayer(null)} to detach it from the old one. This ordering is significantly * more efficient and may allow for more seamless transitions. * * @param player The {@link Player} to use, or {@code null} to detach the current player. Only * players which are accessed on the main thread are supported ({@code * player.getApplicationLooper() == Looper.getMainLooper()}). */ public void setPlayer(@Nullable Player player) { Assertions.checkState(Looper.myLooper() == Looper.getMainLooper()); Assertions.checkArgument( player == null || player.getApplicationLooper() == Looper.getMainLooper()); if (this.player == player) { return; } @Nullable Player oldPlayer = this.player; if (oldPlayer != null) { oldPlayer.removeListener(componentListener); if (oldPlayer.isCommandAvailable(COMMAND_SET_VIDEO_SURFACE)) { if (surfaceView instanceof TextureView) { oldPlayer.clearVideoTextureView((TextureView) surfaceView); } else if (surfaceView instanceof SurfaceView) { oldPlayer.clearVideoSurfaceView((SurfaceView) surfaceView); } } } if (subtitleView != null) { subtitleView.setCues(null); } this.player = player; if (useController()) { controller.setPlayer(player); } updateBuffering(); updateErrorMessage(); updateForCurrentTrackSelections(/* isNewPlayer= */ true); if (player != null) { if (player.isCommandAvailable(COMMAND_SET_VIDEO_SURFACE)) { if (surfaceView instanceof TextureView) { player.setVideoTextureView((TextureView) surfaceView); } else if (surfaceView instanceof SurfaceView) { player.setVideoSurfaceView((SurfaceView) surfaceView); } updateAspectRatio(); } if (subtitleView != null && player.isCommandAvailable(COMMAND_GET_TEXT)) { subtitleView.setCues(player.getCurrentCues().cues); } player.addListener(componentListener); maybeShowController(false); } else { hideController(); } } @Override public void setVisibility(int visibility) { super.setVisibility(visibility); if (surfaceView instanceof SurfaceView) { // Work around https://github.com/google/ExoPlayer/issues/3160. surfaceView.setVisibility(visibility); } } /** * Sets the {@link ResizeMode}. * * @param resizeMode The {@link ResizeMode}. */ public void setResizeMode(@ResizeMode int resizeMode) { Assertions.checkStateNotNull(contentFrame); contentFrame.setResizeMode(resizeMode); } /** Returns the {@link ResizeMode}. */ public @ResizeMode int getResizeMode() { Assertions.checkStateNotNull(contentFrame); return contentFrame.getResizeMode(); } /** Returns whether artwork is displayed if present in the media. */ public boolean getUseArtwork() { return useArtwork; } /** * Sets whether artwork is displayed if present in the media. * * @param useArtwork Whether artwork is displayed. */ public void setUseArtwork(boolean useArtwork) { Assertions.checkState(!useArtwork || artworkView != null); if (this.useArtwork != useArtwork) { this.useArtwork = useArtwork; updateForCurrentTrackSelections(/* isNewPlayer= */ false); } } /** Returns the default artwork to display. */ @Nullable public Drawable getDefaultArtwork() { return defaultArtwork; } /** * Sets the default artwork to display if {@code useArtwork} is {@code true} and no artwork is * present in the media. * * @param defaultArtwork the default artwork to display */ public void setDefaultArtwork(@Nullable Drawable defaultArtwork) { if (this.defaultArtwork != defaultArtwork) { this.defaultArtwork = defaultArtwork; updateForCurrentTrackSelections(/* isNewPlayer= */ false); } } /** Returns whether the playback controls can be shown. */ public boolean getUseController() { return useController; } /** * Sets whether the playback controls can be shown. If set to {@code false} the playback controls * are never visible and are disconnected from the player. * * <p>This call will update whether the view is clickable. After the call, the view will be * clickable if playback controls can be shown or if the view has a registered click listener. * * @param useController Whether the playback controls can be shown. */ public void setUseController(boolean useController) { Assertions.checkState(!useController || controller != null); setClickable(useController || hasOnClickListeners()); if (this.useController == useController) { return; } this.useController = useController; if (useController()) { controller.setPlayer(player); } else if (controller != null) { controller.hide(); controller.setPlayer(/* player= */ null); } updateContentDescription(); } /** * Sets the background color of the {@code exo_shutter} view. * * @param color The background color. */ public void setShutterBackgroundColor(int color) { if (shutterView != null) { shutterView.setBackgroundColor(color); } } /** * Sets whether the currently displayed video frame or media artwork is kept visible when the * player is reset. A player reset is defined to mean the player being re-prepared with different * media, the player transitioning to unprepared media or an empty list of media items, or the * player being replaced or cleared by calling {@link #setPlayer(Player)}. * * <p>If enabled, the currently displayed video frame or media artwork will be kept visible until * the player set on the view has been successfully prepared with new media and loaded enough of * it to have determined the available tracks. Hence enabling this option allows transitioning * from playing one piece of media to another, or from using one player instance to another, * without clearing the view's content. * * <p>If disabled, the currently displayed video frame or media artwork will be hidden as soon as * the player is reset. Note that the video frame is hidden by making {@code exo_shutter} visible. * Hence the video frame will not be hidden if using a custom layout that omits this view. * * @param keepContentOnPlayerReset Whether the currently displayed video frame or media artwork is * kept visible when the player is reset. */ public void setKeepContentOnPlayerReset(boolean keepContentOnPlayerReset) { if (this.keepContentOnPlayerReset != keepContentOnPlayerReset) { this.keepContentOnPlayerReset = keepContentOnPlayerReset; updateForCurrentTrackSelections(/* isNewPlayer= */ false); } } /** * Sets whether a buffering spinner is displayed when the player is in the buffering state. The * buffering spinner is not displayed by default. * * @param showBuffering The mode that defines when the buffering spinner is displayed. One of * {@link #SHOW_BUFFERING_NEVER}, {@link #SHOW_BUFFERING_WHEN_PLAYING} and {@link * #SHOW_BUFFERING_ALWAYS}. */ public void setShowBuffering(@ShowBuffering int showBuffering) { if (this.showBuffering != showBuffering) { this.showBuffering = showBuffering; updateBuffering(); } } /** * Sets the optional {@link ErrorMessageProvider}. * * @param errorMessageProvider The error message provider. */ public void setErrorMessageProvider( @Nullable ErrorMessageProvider<? super PlaybackException> errorMessageProvider) { if (this.errorMessageProvider != errorMessageProvider) { this.errorMessageProvider = errorMessageProvider; updateErrorMessage(); } } /** * Sets a custom error message to be displayed by the view. The error message will be displayed * permanently, unless it is cleared by passing {@code null} to this method. * * @param message The message to display, or {@code null} to clear a previously set message. */ public void setCustomErrorMessage(@Nullable CharSequence message) { Assertions.checkState(errorMessageView != null); customErrorMessage = message; updateErrorMessage(); } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (player != null && player.isPlayingAd()) { return super.dispatchKeyEvent(event); } boolean isDpadKey = isDpadKey(event.getKeyCode()); boolean handled = false; if (isDpadKey && useController() && !controller.isVisible()) { // Handle the key event by showing the controller. maybeShowController(true); handled = true; } else if (dispatchMediaKeyEvent(event) || super.dispatchKeyEvent(event)) { // The key event was handled as a media key or by the super class. We should also show the // controller, or extend its show timeout if already visible. maybeShowController(true); handled = true; } else if (isDpadKey && useController()) { // The key event wasn't handled, but we should extend the controller's show timeout. maybeShowController(true); } return handled; } /** * Called to process media key events. Any {@link KeyEvent} can be passed but only media key * events will be handled. Does nothing if playback controls are disabled. * * @param event A key event. * @return Whether the key event was handled. */ public boolean dispatchMediaKeyEvent(KeyEvent event) { return useController() && controller.dispatchMediaKeyEvent(event); } /** Returns whether the controller is currently visible. */ public boolean isControllerVisible() { return controller != null && controller.isVisible(); } /** * Shows the playback controls. Does nothing if playback controls are disabled. * * <p>The playback controls are automatically hidden during playback after {{@link * #getControllerShowTimeoutMs()}}. They are shown indefinitely when playback has not started yet, * is paused, has ended or failed. */ public void showController() { showController(shouldShowControllerIndefinitely()); } /** Hides the playback controls. Does nothing if playback controls are disabled. */ public void hideController() { if (controller != null) { controller.hide(); } } /** * Returns the playback controls timeout. The playback controls are automatically hidden after * this duration of time has elapsed without user input and with playback or buffering in * progress. * * @return The timeout in milliseconds. A non-positive value will cause the controller to remain * visible indefinitely. */ public int getControllerShowTimeoutMs() { return controllerShowTimeoutMs; } /** * Sets the playback controls timeout. The playback controls are automatically hidden after this * duration of time has elapsed without user input and with playback or buffering in progress. * * @param controllerShowTimeoutMs The timeout in milliseconds. A non-positive value will cause the * controller to remain visible indefinitely. */ public void setControllerShowTimeoutMs(int controllerShowTimeoutMs) { Assertions.checkStateNotNull(controller); this.controllerShowTimeoutMs = controllerShowTimeoutMs; if (controller.isVisible()) { // Update the controller's timeout if necessary. showController(); } } /** Returns whether the playback controls are hidden by touch events. */ public boolean getControllerHideOnTouch() { return controllerHideOnTouch; } /** * Sets whether the playback controls are hidden by touch events. * * @param controllerHideOnTouch Whether the playback controls are hidden by touch events. */ public void setControllerHideOnTouch(boolean controllerHideOnTouch) { Assertions.checkStateNotNull(controller); this.controllerHideOnTouch = controllerHideOnTouch; updateContentDescription(); } /** * Returns whether the playback controls are automatically shown when playback starts, pauses, * ends, or fails. If set to false, the playback controls can be manually operated with {@link * #showController()} and {@link #hideController()}. */ public boolean getControllerAutoShow() { return controllerAutoShow; } /** * Sets whether the playback controls are automatically shown when playback starts, pauses, ends, * or fails. If set to false, the playback controls can be manually operated with {@link * #showController()} and {@link #hideController()}. * * @param controllerAutoShow Whether the playback controls are allowed to show automatically. */ public void setControllerAutoShow(boolean controllerAutoShow) { this.controllerAutoShow = controllerAutoShow; } /** * Sets whether the playback controls are hidden when ads are playing. Controls are always shown * during ads if they are enabled and the player is paused. * * @param controllerHideDuringAds Whether the playback controls are hidden when ads are playing. */ public void setControllerHideDuringAds(boolean controllerHideDuringAds) { this.controllerHideDuringAds = controllerHideDuringAds; } /** * Sets the {@link PlayerControlView.VisibilityListener}. * * @param listener The listener to be notified about visibility changes, or null to remove the * current listener. */ public void setControllerVisibilityListener( @Nullable PlayerControlView.VisibilityListener listener) { Assertions.checkStateNotNull(controller); if (this.controllerVisibilityListener == listener) { return; } if (this.controllerVisibilityListener != null) { controller.removeVisibilityListener(this.controllerVisibilityListener); } this.controllerVisibilityListener = listener; if (listener != null) { controller.addVisibilityListener(listener); } } /** * Sets whether the rewind button is shown. * * @param showRewindButton Whether the rewind button is shown. */ public void setShowRewindButton(boolean showRewindButton) { Assertions.checkStateNotNull(controller); controller.setShowRewindButton(showRewindButton); } /** * Sets whether the fast forward button is shown. * * @param showFastForwardButton Whether the fast forward button is shown. */ public void setShowFastForwardButton(boolean showFastForwardButton) { Assertions.checkStateNotNull(controller); controller.setShowFastForwardButton(showFastForwardButton); } /** * Sets whether the previous button is shown. * * @param showPreviousButton Whether the previous button is shown. */ public void setShowPreviousButton(boolean showPreviousButton) { Assertions.checkStateNotNull(controller); controller.setShowPreviousButton(showPreviousButton); } /** * Sets whether the next button is shown. * * @param showNextButton Whether the next button is shown. */ public void setShowNextButton(boolean showNextButton) { Assertions.checkStateNotNull(controller); controller.setShowNextButton(showNextButton); } /** * Sets which repeat toggle modes are enabled. * * @param repeatToggleModes A set of {@link RepeatModeUtil.RepeatToggleModes}. */ public void setRepeatToggleModes(@RepeatModeUtil.RepeatToggleModes int repeatToggleModes) { Assertions.checkStateNotNull(controller); controller.setRepeatToggleModes(repeatToggleModes); } /** * Sets whether the shuffle button is shown. * * @param showShuffleButton Whether the shuffle button is shown. */ public void setShowShuffleButton(boolean showShuffleButton) { Assertions.checkStateNotNull(controller); controller.setShowShuffleButton(showShuffleButton); } /** * Sets whether the time bar should show all windows, as opposed to just the current one. * * @param showMultiWindowTimeBar Whether to show all windows. */ public void setShowMultiWindowTimeBar(boolean showMultiWindowTimeBar) { Assertions.checkStateNotNull(controller); controller.setShowMultiWindowTimeBar(showMultiWindowTimeBar); } /** * Sets the millisecond positions of extra ad markers relative to the start of the window (or * timeline, if in multi-window mode) and whether each extra ad has been played or not. The * markers are shown in addition to any ad markers for ads in the player's timeline. * * @param extraAdGroupTimesMs The millisecond timestamps of the extra ad markers to show, or * {@code null} to show no extra ad markers. * @param extraPlayedAdGroups Whether each ad has been played, or {@code null} to show no extra ad * markers. */ public void setExtraAdGroupMarkers( @Nullable long[] extraAdGroupTimesMs, @Nullable boolean[] extraPlayedAdGroups) { Assertions.checkStateNotNull(controller); controller.setExtraAdGroupMarkers(extraAdGroupTimesMs, extraPlayedAdGroups); } /** * Sets the {@link AspectRatioFrameLayout.AspectRatioListener}. * * @param listener The listener to be notified about aspect ratios changes of the video content or * the content frame. */ public void setAspectRatioListener( @Nullable AspectRatioFrameLayout.AspectRatioListener listener) { Assertions.checkStateNotNull(contentFrame); contentFrame.setAspectRatioListener(listener); } /** * Gets the view onto which video is rendered. This is a: * * <ul> * <li>{@link SurfaceView} by default, or if the {@code surface_type} attribute is set to {@code * surface_view}. * <li>{@link TextureView} if {@code surface_type} is {@code texture_view}. * <li>{@code SphericalGLSurfaceView} if {@code surface_type} is {@code * spherical_gl_surface_view}. * <li>{@code VideoDecoderGLSurfaceView} if {@code surface_type} is {@code * video_decoder_gl_surface_view}. * <li>{@code null} if {@code surface_type} is {@code none}. * </ul> * * @return The {@link SurfaceView}, {@link TextureView}, {@code SphericalGLSurfaceView}, {@code * VideoDecoderGLSurfaceView} or {@code null}. */ @Nullable public View getVideoSurfaceView() { return surfaceView; } /** * Gets the overlay {@link FrameLayout}, which can be populated with UI elements to show on top of * the player. * * @return The overlay {@link FrameLayout}, or {@code null} if the layout has been customized and * the overlay is not present. */ @Nullable public FrameLayout getOverlayFrameLayout() { return overlayFrameLayout; } /** * Gets the {@link SubtitleView}. * * @return The {@link SubtitleView}, or {@code null} if the layout has been customized and the * subtitle view is not present. */ @Nullable public SubtitleView getSubtitleView() { return subtitleView; } @Override public boolean performClick() { toggleControllerVisibility(); return super.performClick(); } @Override public boolean onTrackballEvent(MotionEvent ev) { if (!useController() || player == null) { return false; } maybeShowController(true); return true; } /** * Should be called when the player is visible to the user, if the {@code surface_type} extends * {@link GLSurfaceView}. It is the counterpart to {@link #onPause()}. * * <p>This method should typically be called in {@code Activity.onStart()}, or {@code * Activity.onResume()} for API versions &lt;= 23. */ public void onResume() { if (surfaceView instanceof GLSurfaceView) { ((GLSurfaceView) surfaceView).onResume(); } } /** * Should be called when the player is no longer visible to the user, if the {@code surface_type} * extends {@link GLSurfaceView}. It is the counterpart to {@link #onResume()}. * * <p>This method should typically be called in {@code Activity.onStop()}, or {@code * Activity.onPause()} for API versions &lt;= 23. */ public void onPause() { if (surfaceView instanceof GLSurfaceView) { ((GLSurfaceView) surfaceView).onPause(); } } /** * Called when there's a change in the desired aspect ratio of the content frame. The default * implementation sets the aspect ratio of the content frame to the specified value. * * @param contentFrame The content frame, or {@code null}. * @param aspectRatio The aspect ratio to apply. */ protected void onContentAspectRatioChanged( @Nullable AspectRatioFrameLayout contentFrame, float aspectRatio) { if (contentFrame != null) { contentFrame.setAspectRatio(aspectRatio); } } // AdsLoader.AdViewProvider implementation. @Override public ViewGroup getAdViewGroup() { return Assertions.checkStateNotNull( adOverlayFrameLayout, "exo_ad_overlay must be present for ad playback"); } @Override public List<AdOverlayInfo> getAdOverlayInfos() { List<AdOverlayInfo> overlayViews = new ArrayList<>(); if (overlayFrameLayout != null) { overlayViews.add( new AdOverlayInfo( overlayFrameLayout, AdOverlayInfo.PURPOSE_NOT_VISIBLE, /* detailedReason= */ "Transparent overlay does not impact viewability")); } if (controller != null) { overlayViews.add(new AdOverlayInfo(controller, AdOverlayInfo.PURPOSE_CONTROLS)); } return ImmutableList.copyOf(overlayViews); } // Internal methods. @EnsuresNonNullIf(expression = "controller", result = true) private boolean useController() { if (useController) { Assertions.checkStateNotNull(controller); return true; } return false; } @EnsuresNonNullIf(expression = "artworkView", result = true) private boolean useArtwork() { if (useArtwork) { Assertions.checkStateNotNull(artworkView); return true; } return false; } private void toggleControllerVisibility() { if (!useController() || player == null) { return; } if (!controller.isVisible()) { maybeShowController(true); } else if (controllerHideOnTouch) { controller.hide(); } } /** Shows the playback controls, but only if forced or shown indefinitely. */ private void maybeShowController(boolean isForced) { if (isPlayingAd() && controllerHideDuringAds) { return; } if (useController()) { boolean wasShowingIndefinitely = controller.isVisible() && controller.getShowTimeoutMs() <= 0; boolean shouldShowIndefinitely = shouldShowControllerIndefinitely(); if (isForced || wasShowingIndefinitely || shouldShowIndefinitely) { showController(shouldShowIndefinitely); } } } private boolean shouldShowControllerIndefinitely() { if (player == null) { return true; } int playbackState = player.getPlaybackState(); return controllerAutoShow && (playbackState == Player.STATE_IDLE || playbackState == Player.STATE_ENDED || !player.getPlayWhenReady()); } private void showController(boolean showIndefinitely) { if (!useController()) { return; } controller.setShowTimeoutMs(showIndefinitely ? 0 : controllerShowTimeoutMs); controller.show(); } private boolean isPlayingAd() { return player != null && player.isPlayingAd() && player.getPlayWhenReady(); } private void updateForCurrentTrackSelections(boolean isNewPlayer) { @Nullable Player player = this.player; if (player == null || !player.isCommandAvailable(Player.COMMAND_GET_TRACKS) || player.getCurrentTracks().isEmpty()) { if (!keepContentOnPlayerReset) { hideArtwork(); closeShutter(); } return; } if (isNewPlayer && !keepContentOnPlayerReset) { // Hide any video from the previous player. closeShutter(); } if (player.getCurrentTracks().isTypeSelected(C.TRACK_TYPE_VIDEO)) { // Video enabled, so artwork must be hidden. If the shutter is closed, it will be opened // in onRenderedFirstFrame(). hideArtwork(); return; } // Video disabled so the shutter must be closed. closeShutter(); // Display artwork if enabled and available, else hide it. if (useArtwork()) { if (setArtworkFromMediaMetadata(player.getMediaMetadata())) { return; } if (setDrawableArtwork(defaultArtwork)) { return; } } // Artwork disabled or unavailable. hideArtwork(); } private void updateAspectRatio() { VideoSize videoSize = player != null ? player.getVideoSize() : VideoSize.UNKNOWN; int width = videoSize.width; int height = videoSize.height; int unappliedRotationDegrees = videoSize.unappliedRotationDegrees; float videoAspectRatio = (height == 0 || width == 0) ? 0 : (width * videoSize.pixelWidthHeightRatio) / height; if (surfaceView instanceof TextureView) { // Try to apply rotation transformation when our surface is a TextureView. if (videoAspectRatio > 0 && (unappliedRotationDegrees == 90 || unappliedRotationDegrees == 270)) { // We will apply a rotation 90/270 degree to the output texture of the TextureView. // In this case, the output video's width and height will be swapped. videoAspectRatio = 1 / videoAspectRatio; } if (textureViewRotation != 0) { surfaceView.removeOnLayoutChangeListener(componentListener); } textureViewRotation = unappliedRotationDegrees; if (textureViewRotation != 0) { // The texture view's dimensions might be changed after layout step. // So add an OnLayoutChangeListener to apply rotation after layout step. surfaceView.addOnLayoutChangeListener(componentListener); } applyTextureViewRotation((TextureView) surfaceView, textureViewRotation); } onContentAspectRatioChanged( contentFrame, surfaceViewIgnoresVideoAspectRatio ? 0 : videoAspectRatio); } @RequiresNonNull("artworkView") private boolean setArtworkFromMediaMetadata(MediaMetadata mediaMetadata) { if (mediaMetadata.artworkData == null) { return false; } Bitmap bitmap = BitmapFactory.decodeByteArray( mediaMetadata.artworkData, /* offset= */ 0, mediaMetadata.artworkData.length); return setDrawableArtwork(new BitmapDrawable(getResources(), bitmap)); } @RequiresNonNull("artworkView") private boolean setDrawableArtwork(@Nullable Drawable drawable) { if (drawable != null) { int drawableWidth = drawable.getIntrinsicWidth(); int drawableHeight = drawable.getIntrinsicHeight(); if (drawableWidth > 0 && drawableHeight > 0) { float artworkAspectRatio = (float) drawableWidth / drawableHeight; onContentAspectRatioChanged(contentFrame, artworkAspectRatio); artworkView.setImageDrawable(drawable); artworkView.setVisibility(VISIBLE); return true; } } return false; } private void hideArtwork() { if (artworkView != null) { artworkView.setImageResource(android.R.color.transparent); // Clears any bitmap reference. artworkView.setVisibility(INVISIBLE); } } private void closeShutter() { if (shutterView != null) { shutterView.setVisibility(View.VISIBLE); } } private void updateBuffering() { if (bufferingView != null) { boolean showBufferingSpinner = player != null && player.getPlaybackState() == Player.STATE_BUFFERING && (showBuffering == SHOW_BUFFERING_ALWAYS || (showBuffering == SHOW_BUFFERING_WHEN_PLAYING && player.getPlayWhenReady())); bufferingView.setVisibility(showBufferingSpinner ? View.VISIBLE : View.GONE); } } private void updateErrorMessage() { if (errorMessageView != null) { if (customErrorMessage != null) { errorMessageView.setText(customErrorMessage); errorMessageView.setVisibility(View.VISIBLE); return; } @Nullable PlaybackException error = player != null ? player.getPlayerError() : null; if (error != null && errorMessageProvider != null) { CharSequence errorMessage = errorMessageProvider.getErrorMessage(error).second; errorMessageView.setText(errorMessage); errorMessageView.setVisibility(View.VISIBLE); } else { errorMessageView.setVisibility(View.GONE); } } } private void updateContentDescription() { if (controller == null || !useController) { setContentDescription(/* contentDescription= */ null); } else if (controller.getVisibility() == View.VISIBLE) { setContentDescription( /* contentDescription= */ controllerHideOnTouch ? getResources().getString(R.string.exo_controls_hide) : null); } else { setContentDescription( /* contentDescription= */ getResources().getString(R.string.exo_controls_show)); } } private void updateControllerVisibility() { if (isPlayingAd() && controllerHideDuringAds) { hideController(); } else { maybeShowController(false); } } @RequiresApi(23) private static void configureEditModeLogoV23( Context context, Resources resources, ImageView logo) { logo.setImageDrawable(getDrawable(context, resources, R.drawable.exo_edit_mode_logo)); logo.setBackgroundColor(resources.getColor(R.color.exo_edit_mode_background_color, null)); } private static void configureEditModeLogo(Context context, Resources resources, ImageView logo) { logo.setImageDrawable(getDrawable(context, resources, R.drawable.exo_edit_mode_logo)); logo.setBackgroundColor(resources.getColor(R.color.exo_edit_mode_background_color)); } @SuppressWarnings("ResourceType") private static void setResizeModeRaw(AspectRatioFrameLayout aspectRatioFrame, int resizeMode) { aspectRatioFrame.setResizeMode(resizeMode); } /** Applies a texture rotation to a {@link TextureView}. */ private static void applyTextureViewRotation(TextureView textureView, int textureViewRotation) { Matrix transformMatrix = new Matrix(); float textureViewWidth = textureView.getWidth(); float textureViewHeight = textureView.getHeight(); if (textureViewWidth != 0 && textureViewHeight != 0 && textureViewRotation != 0) { float pivotX = textureViewWidth / 2; float pivotY = textureViewHeight / 2; transformMatrix.postRotate(textureViewRotation, pivotX, pivotY); // After rotation, scale the rotated texture to fit the TextureView size. RectF originalTextureRect = new RectF(0, 0, textureViewWidth, textureViewHeight); RectF rotatedTextureRect = new RectF(); transformMatrix.mapRect(rotatedTextureRect, originalTextureRect); transformMatrix.postScale( textureViewWidth / rotatedTextureRect.width(), textureViewHeight / rotatedTextureRect.height(), pivotX, pivotY); } textureView.setTransform(transformMatrix); } @SuppressLint("InlinedApi") private boolean isDpadKey(int keyCode) { return keyCode == KeyEvent.KEYCODE_DPAD_UP || keyCode == KeyEvent.KEYCODE_DPAD_UP_RIGHT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT || keyCode == KeyEvent.KEYCODE_DPAD_DOWN_RIGHT || keyCode == KeyEvent.KEYCODE_DPAD_DOWN || keyCode == KeyEvent.KEYCODE_DPAD_DOWN_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_UP_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_CENTER; } private final class ComponentListener implements Player.Listener, OnLayoutChangeListener, OnClickListener, PlayerControlView.VisibilityListener { private final Period period; private @Nullable Object lastPeriodUidWithTracks; public ComponentListener() { period = new Period(); } // Player.Listener implementation @Override public void onCues(CueGroup cueGroup) { if (subtitleView != null) { subtitleView.setCues(cueGroup.cues); } } @Override public void onVideoSizeChanged(VideoSize videoSize) { updateAspectRatio(); } @Override public void onRenderedFirstFrame() { if (shutterView != null) { shutterView.setVisibility(INVISIBLE); } } @Override public void onTracksChanged(Tracks tracks) { // Suppress the update if transitioning to an unprepared period within the same window. This // is necessary to avoid closing the shutter when such a transition occurs. See: // https://github.com/google/ExoPlayer/issues/5507. Player player = Assertions.checkNotNull(PlayerView.this.player); Timeline timeline = player.getCurrentTimeline(); if (timeline.isEmpty()) { lastPeriodUidWithTracks = null; } else if (!player.getCurrentTracks().isEmpty()) { lastPeriodUidWithTracks = timeline.getPeriod(player.getCurrentPeriodIndex(), period, /* setIds= */ true).uid; } else if (lastPeriodUidWithTracks != null) { int lastPeriodIndexWithTracks = timeline.getIndexOfPeriod(lastPeriodUidWithTracks); if (lastPeriodIndexWithTracks != C.INDEX_UNSET) { int lastWindowIndexWithTracks = timeline.getPeriod(lastPeriodIndexWithTracks, period).windowIndex; if (player.getCurrentMediaItemIndex() == lastWindowIndexWithTracks) { // We're in the same media item. Suppress the update. return; } } lastPeriodUidWithTracks = null; } updateForCurrentTrackSelections(/* isNewPlayer= */ false); } @Override public void onPlaybackStateChanged(@Player.State int playbackState) { updateBuffering(); updateErrorMessage(); updateControllerVisibility(); } @Override public void onPlayWhenReadyChanged( boolean playWhenReady, @Player.PlayWhenReadyChangeReason int reason) { updateBuffering(); updateControllerVisibility(); } @Override public void onPositionDiscontinuity( Player.PositionInfo oldPosition, Player.PositionInfo newPosition, @DiscontinuityReason int reason) { if (isPlayingAd() && controllerHideDuringAds) { hideController(); } } // OnLayoutChangeListener implementation @Override public void onLayoutChange( View view, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { applyTextureViewRotation((TextureView) view, textureViewRotation); } // OnClickListener implementation @Override public void onClick(View view) { toggleControllerVisibility(); } // PlayerControlView.VisibilityListener implementation @Override public void onVisibilityChange(int visibility) { updateContentDescription(); } } }
google/ExoPlayer
library/ui/src/main/java/com/google/android/exoplayer2/ui/PlayerView.java
41,705
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.ui; import android.animation.Animator; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.Context; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.StatFs; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextUtils; import android.text.style.RelativeSizeSpan; import android.util.LongSparseArray; import android.util.SparseArray; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.FrameLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.core.graphics.ColorUtils; import androidx.core.math.MathUtils; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.BotWebViewVibrationEffect; import org.telegram.messenger.BuildVars; import org.telegram.messenger.CacheByChatsController; import org.telegram.messenger.Emoji; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.FilePathDatabase; import org.telegram.messenger.FilesMigrationService; import org.telegram.messenger.ImageLoader; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MediaDataController; import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesStorage; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.SharedConfig; import org.telegram.messenger.Utilities; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.ActionBar; import org.telegram.ui.ActionBar.ActionBarMenu; import org.telegram.ui.ActionBar.ActionBarMenuItem; import org.telegram.ui.ActionBar.ActionBarMenuSubItem; import org.telegram.ui.ActionBar.ActionBarPopupWindow; import org.telegram.ui.ActionBar.AlertDialog; import org.telegram.ui.ActionBar.BackDrawable; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.BottomSheet; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.ThemeDescription; import org.telegram.ui.Cells.CheckBoxCell; import org.telegram.ui.Cells.HeaderCell; import org.telegram.ui.Cells.TextCell; import org.telegram.ui.Cells.TextCheckBoxCell; import org.telegram.ui.Cells.TextInfoPrivacyCell; import org.telegram.ui.Cells.TextSettingsCell; import org.telegram.ui.Components.AlertsCreator; import org.telegram.ui.Components.AnimatedFloat; import org.telegram.ui.Components.AnimatedTextView; import org.telegram.ui.Components.BackupImageView; import org.telegram.ui.Components.CacheChart; import org.telegram.ui.Components.CheckBox2; import org.telegram.ui.Components.CubicBezierInterpolator; import org.telegram.ui.Components.FlickerLoadingView; import org.telegram.ui.Components.HideViewAfterAnimation; import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.ListView.AdapterWithDiffUtils; import org.telegram.ui.Components.LoadingDrawable; import org.telegram.ui.Components.NestedSizeNotifierLayout; import org.telegram.ui.Components.RLottieImageView; import org.telegram.ui.Components.RecyclerListView; import org.telegram.ui.Components.SlideChooseView; import org.telegram.ui.Components.StorageDiagramView; import org.telegram.ui.Components.StorageUsageView; import org.telegram.ui.Components.TypefaceSpan; import org.telegram.ui.Components.UndoView; import org.telegram.ui.Storage.CacheModel; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Locale; import java.util.Objects; public class CacheControlActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate { private static final int VIEW_TYPE_TEXT_SETTINGS = 0; private static final int VIEW_TYPE_INFO = 1; private static final int VIEW_TYPE_STORAGE = 2; private static final int VIEW_TYPE_HEADER = 3; private static final int VIEW_TYPE_CHOOSER = 4; private static final int VIEW_TYPE_CHAT = 5; private static final int VIEW_FLICKER_LOADING_DIALOG = 6; private static final int VIEW_TYPE_KEEP_MEDIA_CELL = 7; private static final int VIEW_TYPE_CACHE_VIEW_PAGER = 8; private static final int VIEW_TYPE_CHART = 9; private static final int VIEW_TYPE_CHART_HEADER = 10; private static final int VIEW_TYPE_SECTION = 11; private static final int VIEW_TYPE_SECTION_LOADING = 12; private static final int VIEW_TYPE_CLEAR_CACHE_BUTTON = 13; private static final int VIEW_TYPE_MAX_CACHE_SIZE = 14; public static final int KEEP_MEDIA_TYPE_USER = 0; public static final int KEEP_MEDIA_TYPE_GROUP = 1; public static final int KEEP_MEDIA_TYPE_CHANNEL = 2; public static final int KEEP_MEDIA_TYPE_STORIES = 3; public static final long UNKNOWN_CHATS_DIALOG_ID = Long.MAX_VALUE; private ListAdapter listAdapter; private RecyclerListView listView; @SuppressWarnings("FieldCanBeLocal") private LinearLayoutManager layoutManager; AlertDialog progressDialog; private boolean[] selected = new boolean[] { true, true, true, true, true, true, true, true, true, true, true }; private long databaseSize = -1; private long cacheSize = -1, cacheEmojiSize = -1, cacheTempSize = -1; private long documentsSize = -1; private long audioSize = -1; private long storiesSize = -1; private long musicSize = -1; private long photoSize = -1; private long videoSize = -1; private long logsSize = -1; private long stickersCacheSize = -1; private long totalSize = -1; private long totalDeviceSize = -1; private long totalDeviceFreeSize = -1; private long migrateOldFolderRow = -1; private boolean calculating = true; private boolean collapsed = true; private CachedMediaLayout cachedMediaLayout; private int[] percents; private float[] tempSizes; private int sectionsStartRow = -1; private int sectionsEndRow = -1; private CacheChart cacheChart; private CacheChartHeader cacheChartHeader; private ClearCacheButtonInternal clearCacheButton; public static volatile boolean canceled = false; private View bottomSheetView; private BottomSheet bottomSheet; private View actionTextView; private UndoView cacheRemovedTooltip; long fragmentCreateTime; private boolean updateDatabaseSize; public final static int TYPE_PHOTOS = 0; public final static int TYPE_VIDEOS = 1; public final static int TYPE_DOCUMENTS = 2; public final static int TYPE_MUSIC = 3; public final static int TYPE_VOICE = 4; public final static int TYPE_ANIMATED_STICKERS_CACHE = 5; public final static int TYPE_OTHER = 6; public final static int TYPE_STORIES = 7; private static final int delete_id = 1; private static final int other_id = 2; private static final int clear_database_id = 3; private static final int reset_database_id = 4; private boolean loadingDialogs; private NestedSizeNotifierLayout nestedSizeNotifierLayout; private ActionBarMenuSubItem clearDatabaseItem; private ActionBarMenuSubItem resetDatabaseItem; private void updateDatabaseItemSize() { if (clearDatabaseItem != null) { SpannableStringBuilder string = new SpannableStringBuilder(); string.append(LocaleController.getString("ClearLocalDatabase", R.string.ClearLocalDatabase)); // string.append("\t"); // SpannableString databaseSizeString = new SpannableString(AndroidUtilities.formatFileSize(databaseSize)); // databaseSizeString.setSpan(new ForegroundColorSpan(Theme.getColor(Theme.key_windowBackgroundWhiteBlueText)), 0, databaseSizeString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // string.append(databaseSizeString); clearDatabaseItem.setText(string); } } private static long lastTotalSizeCalculatedTime; private static Long lastTotalSizeCalculated; private static Long lastDeviceTotalSize, lastDeviceTotalFreeSize; public static void calculateTotalSize(Utilities.Callback<Long> onDone) { if (onDone == null) { return; } if (lastTotalSizeCalculated != null) { onDone.run(lastTotalSizeCalculated); if (System.currentTimeMillis() - lastTotalSizeCalculatedTime < 5000) { return; } } Utilities.cacheClearQueue.postRunnable(() -> { canceled = false; long cacheSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 5); long cacheTempSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 4); long photoSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE), 0); photoSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE_PUBLIC), 0); long videoSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO), 0); videoSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO_PUBLIC), 0); long documentsSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT), 1); documentsSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES), 1); long musicSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT), 2); musicSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES), 2); long stickersCacheSize = getDirectorySize(new File(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), "acache"), 0); stickersCacheSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 3); long audioSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_AUDIO), 0); long storiesSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_STORIES), 0); long logsSize = getDirectorySize(AndroidUtilities.getLogsDir(), 1); if (!BuildVars.DEBUG_VERSION && logsSize < 1024 * 1024 * 256) { logsSize = 0; } final long totalSize = lastTotalSizeCalculated = cacheSize + cacheTempSize + videoSize + audioSize + photoSize + documentsSize + musicSize + stickersCacheSize + storiesSize + logsSize; lastTotalSizeCalculatedTime = System.currentTimeMillis(); if (!canceled) { AndroidUtilities.runOnUIThread(() -> { onDone.run(totalSize); }); } }); } public static void resetCalculatedTotalSIze() { lastTotalSizeCalculated = null; } public static void getDeviceTotalSize(Utilities.Callback2<Long, Long> onDone) { if (lastDeviceTotalSize != null && lastDeviceTotalFreeSize != null) { if (onDone != null) { onDone.run(lastDeviceTotalSize, lastDeviceTotalFreeSize); } return; } Utilities.cacheClearQueue.postRunnable(() -> { File path; if (Build.VERSION.SDK_INT >= 19) { ArrayList<File> storageDirs = AndroidUtilities.getRootDirs(); String dir = (path = storageDirs.get(0)).getAbsolutePath(); if (!TextUtils.isEmpty(SharedConfig.storageCacheDir)) { for (int a = 0, N = storageDirs.size(); a < N; a++) { File file = storageDirs.get(a); if (file.getAbsolutePath().startsWith(SharedConfig.storageCacheDir) && file.canWrite()) { path = file; break; } } } } else { path = new File(SharedConfig.storageCacheDir); } try { StatFs stat = new StatFs(path.getPath()); long blockSize; long blockSizeExternal; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blockSize = stat.getBlockSizeLong(); } else { blockSize = stat.getBlockSize(); } long availableBlocks; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { availableBlocks = stat.getAvailableBlocksLong(); } else { availableBlocks = stat.getAvailableBlocks(); } long blocksTotal; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blocksTotal = stat.getBlockCountLong(); } else { blocksTotal = stat.getBlockCount(); } AndroidUtilities.runOnUIThread(() -> { lastDeviceTotalSize = blocksTotal * blockSize; lastDeviceTotalFreeSize = availableBlocks * blockSize; if (onDone != null) { onDone.run(lastDeviceTotalSize, lastDeviceTotalFreeSize); } }); } catch (Exception e) { FileLog.e(e); } }); } @Override public boolean onFragmentCreate() { super.onFragmentCreate(); canceled = false; getNotificationCenter().addObserver(this, NotificationCenter.didClearDatabase); databaseSize = MessagesStorage.getInstance(currentAccount).getDatabaseSize(); loadingDialogs = true; Utilities.globalQueue.postRunnable(() -> { cacheSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 5); if (canceled) { return; } cacheTempSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 4); if (canceled) { return; } photoSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE), 0); photoSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE_PUBLIC), 0); if (canceled) { return; } videoSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO), 0); videoSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO_PUBLIC), 0); if (canceled) { return; } logsSize = getDirectorySize(AndroidUtilities.getLogsDir(), 1); if (!BuildVars.DEBUG_VERSION && logsSize < 1024 * 1024 * 256) { logsSize = 0; } if (canceled) { return; } documentsSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT), 1); documentsSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES), 1); if (canceled) { return; } musicSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT), 2); musicSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES), 2); if (canceled) { return; } stickersCacheSize = getDirectorySize(new File(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), "acache"), 0); if (canceled) { return; } cacheEmojiSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 3); if (canceled) { return; } stickersCacheSize += cacheEmojiSize; audioSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_AUDIO), 0); storiesSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_STORIES), 0); if (canceled) { return; } totalSize = lastTotalSizeCalculated = cacheSize + cacheTempSize + videoSize + logsSize + audioSize + photoSize + documentsSize + musicSize + storiesSize + stickersCacheSize; lastTotalSizeCalculatedTime = System.currentTimeMillis(); File path; if (Build.VERSION.SDK_INT >= 19) { ArrayList<File> storageDirs = AndroidUtilities.getRootDirs(); String dir = (path = storageDirs.get(0)).getAbsolutePath(); if (!TextUtils.isEmpty(SharedConfig.storageCacheDir)) { for (int a = 0, N = storageDirs.size(); a < N; a++) { File file = storageDirs.get(a); if (file.getAbsolutePath().startsWith(SharedConfig.storageCacheDir)) { path = file; break; } } } } else { path = new File(SharedConfig.storageCacheDir); } try { StatFs stat = new StatFs(path.getPath()); long blockSize; long blockSizeExternal; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blockSize = stat.getBlockSizeLong(); } else { blockSize = stat.getBlockSize(); } long availableBlocks; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { availableBlocks = stat.getAvailableBlocksLong(); } else { availableBlocks = stat.getAvailableBlocks(); } long blocksTotal; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blocksTotal = stat.getBlockCountLong(); } else { blocksTotal = stat.getBlockCount(); } totalDeviceSize = blocksTotal * blockSize; totalDeviceFreeSize = availableBlocks * blockSize; } catch (Exception e) { FileLog.e(e); } AndroidUtilities.runOnUIThread(() -> { resumeDelayedFragmentAnimation(); calculating = false; updateRows(true); updateChart(); }); loadDialogEntities(); }); fragmentCreateTime = System.currentTimeMillis(); updateRows(false); updateChart(); return true; } private void updateChart() { if (cacheChart != null) { if (!calculating && totalSize > 0) { CacheChart.SegmentSize[] segments = new CacheChart.SegmentSize[11]; for (int i = 0; i < itemInners.size(); ++i) { ItemInner item = itemInners.get(i); if (item.viewType == VIEW_TYPE_SECTION) { if (item.index < 0) { if (collapsed) { segments[10] = CacheChart.SegmentSize.of(item.size, selected[10]); } } else { segments[item.index] = CacheChart.SegmentSize.of(item.size, selected[item.index]); } } } if (System.currentTimeMillis() - fragmentCreateTime < 80) { cacheChart.loadingFloat.set(0, true); } cacheChart.setSegments(totalSize, true, segments); } else if (calculating) { cacheChart.setSegments(-1, true); } else { cacheChart.setSegments(0, true); } } if (clearCacheButton != null && !calculating) { clearCacheButton.updateSize(); } } private void loadDialogEntities() { getFileLoader().getFileDatabase().getQueue().postRunnable(() -> { getFileLoader().getFileDatabase().ensureDatabaseCreated(); CacheModel cacheModel = new CacheModel(false); LongSparseArray<DialogFileEntities> dilogsFilesEntities = new LongSparseArray<>(); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), TYPE_OTHER, dilogsFilesEntities, cacheModel); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE), TYPE_PHOTOS, dilogsFilesEntities, cacheModel); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE_PUBLIC), TYPE_PHOTOS, dilogsFilesEntities, cacheModel); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO), TYPE_VIDEOS, dilogsFilesEntities, cacheModel); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO_PUBLIC), TYPE_VIDEOS, dilogsFilesEntities, cacheModel); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_AUDIO), TYPE_VOICE, dilogsFilesEntities, cacheModel); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_STORIES), TYPE_OTHER, dilogsFilesEntities, cacheModel); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT), TYPE_DOCUMENTS, dilogsFilesEntities, cacheModel); fillDialogsEntitiesRecursive(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES), TYPE_DOCUMENTS, dilogsFilesEntities, cacheModel); ArrayList<DialogFileEntities> entities = new ArrayList<>(); ArrayList<Long> unknownUsers = new ArrayList<>(); ArrayList<Long> unknownChats = new ArrayList<>(); for (int i = 0; i < dilogsFilesEntities.size(); i++) { DialogFileEntities dialogEntities = dilogsFilesEntities.valueAt(i); entities.add(dialogEntities); if (getMessagesController().getUserOrChat(entities.get(i).dialogId) == null) { if (dialogEntities.dialogId > 0) { unknownUsers.add(dialogEntities.dialogId); } else { unknownChats.add(dialogEntities.dialogId); } } } cacheModel.sortBySize(); getMessagesStorage().getStorageQueue().postRunnable(() -> { ArrayList<TLRPC.User> users = new ArrayList<>(); ArrayList<TLRPC.Chat> chats = new ArrayList<>(); if (!unknownUsers.isEmpty()) { try { getMessagesStorage().getUsersInternal(TextUtils.join(",", unknownUsers), users); } catch (Exception e) { FileLog.e(e); } } if (!unknownChats.isEmpty()) { try { getMessagesStorage().getChatsInternal(TextUtils.join(",", unknownChats), chats); } catch (Exception e) { FileLog.e(e); } } for (int i = 0; i < entities.size(); i++) { if (entities.get(i).totalSize <= 0) { entities.remove(i); i--; } } sort(entities); AndroidUtilities.runOnUIThread(() -> { loadingDialogs = false; getMessagesController().putUsers(users, true); getMessagesController().putChats(chats, true); DialogFileEntities unknownChatsEntity = null; for (int i = 0; i < entities.size(); i++) { DialogFileEntities dialogEntities = entities.get(i); boolean changed = false; if (getMessagesController().getUserOrChat(dialogEntities.dialogId) == null) { dialogEntities.dialogId = UNKNOWN_CHATS_DIALOG_ID; if (unknownChatsEntity != null) { changed = true; unknownChatsEntity.merge(dialogEntities); entities.remove(i); i--; } else { unknownChatsEntity = dialogEntities; } if (changed) { sort(entities); } } } cacheModel.setEntities(entities); if (!canceled) { setCacheModel(cacheModel); updateRows(); updateChart(); if (cacheChartHeader != null && !calculating && System.currentTimeMillis() - fragmentCreateTime > 120) { cacheChartHeader.setData( totalSize > 0, totalDeviceSize <= 0 ? 0 : (float) totalSize / totalDeviceSize, totalDeviceFreeSize <= 0 || totalDeviceSize <= 0 ? 0 : (float) (totalDeviceSize - totalDeviceFreeSize) / totalDeviceSize ); } } }); }); }); } private void sort(ArrayList<DialogFileEntities> entities) { Collections.sort(entities, (o1, o2) -> { if (o2.totalSize > o1.totalSize) { return 1; } else if (o2.totalSize < o1.totalSize) { return -1; } return 0; }); } CacheModel cacheModel; public void setCacheModel(CacheModel cacheModel) { this.cacheModel = cacheModel; if (cachedMediaLayout != null) { cachedMediaLayout.setCacheModel(cacheModel); } } public void fillDialogsEntitiesRecursive(final File fromFolder, int type, LongSparseArray<DialogFileEntities> dilogsFilesEntities, CacheModel cacheModel) { if (fromFolder == null) { return; } File[] files = fromFolder.listFiles(); if (files == null) { return; } for (final File fileEntry : files) { if (canceled) { return; } if (fileEntry.isDirectory()) { fillDialogsEntitiesRecursive(fileEntry, type, dilogsFilesEntities, cacheModel); } else { if (fileEntry.getName().equals(".nomedia")) { continue; } FilePathDatabase.FileMeta fileMetadata = getFileLoader().getFileDatabase().getFileDialogId(fileEntry, null); int addToType = type; String fileName = fileEntry.getName().toLowerCase(); if (fileName.endsWith(".mp3") || fileName.endsWith(".m4a") ) { addToType = TYPE_MUSIC; } CacheModel.FileInfo fileInfo = new CacheModel.FileInfo(fileEntry); fileInfo.size = fileEntry.length(); if (fileMetadata != null) { fileInfo.dialogId = fileMetadata.dialogId; fileInfo.messageId = fileMetadata.messageId; fileInfo.messageType = fileMetadata.messageType; if (fileInfo.messageType == MessageObject.TYPE_STORY && fileInfo.size > 0) { addToType = TYPE_STORIES; } } fileInfo.type = addToType; if (fileInfo.dialogId != 0) { DialogFileEntities dilogEntites = dilogsFilesEntities.get(fileInfo.dialogId, null); if (dilogEntites == null) { dilogEntites = new DialogFileEntities(fileInfo.dialogId); dilogsFilesEntities.put(fileInfo.dialogId, dilogEntites); } dilogEntites.addFile(fileInfo, addToType); } if (cacheModel != null && addToType != TYPE_OTHER) { cacheModel.add(addToType, fileInfo); } //TODO measure for other accounts // for (int i = 0; i < UserConfig.MAX_ACCOUNT_COUNT; i++) { // if (i != currentAccount && UserConfig.getInstance(currentAccount).isClientActivated()) { // FileLoader.getInstance(currentAccount).getFileDatabase().getFileDialogId(fileEntry); // } // } } } } private ArrayList<ItemInner> oldItems = new ArrayList<>(); private ArrayList<ItemInner> itemInners = new ArrayList<>(); private String formatPercent(float k) { return formatPercent(k, true); } private String formatPercent(float k, boolean minimize) { if (minimize && k < 0.001f) { return String.format("<%.1f%%", 0.1f); } final float p = Math.round(k * 100f); if (minimize && p <= 0) { return String.format("<%d%%", 1); } return String.format("%d%%", (int) p); } private CharSequence getCheckBoxTitle(CharSequence header, int percent) { return getCheckBoxTitle(header, percent, false); } private CharSequence getCheckBoxTitle(CharSequence header, int percent, boolean addArrow) { String percentString = percent <= 0 ? String.format("<%.1f%%", 1f) : String.format("%d%%", percent); SpannableString percentStr = new SpannableString(percentString); percentStr.setSpan(new RelativeSizeSpan(.834f), 0, percentStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); percentStr.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)), 0, percentStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); SpannableStringBuilder string = new SpannableStringBuilder(header); string.append(" "); string.append(percentStr); return string; } private void updateRows() { updateRows(true); } private void updateRows(boolean animated) { if (animated && System.currentTimeMillis() - fragmentCreateTime < 80) { animated = false; } oldItems.clear(); oldItems.addAll(itemInners); itemInners.clear(); itemInners.add(new ItemInner(VIEW_TYPE_CHART, null, null)); itemInners.add(new ItemInner(VIEW_TYPE_CHART_HEADER, null, null)); sectionsStartRow = itemInners.size(); boolean hasCache = false; if (calculating) { itemInners.add(new ItemInner(VIEW_TYPE_SECTION_LOADING, null, null)); itemInners.add(new ItemInner(VIEW_TYPE_SECTION_LOADING, null, null)); itemInners.add(new ItemInner(VIEW_TYPE_SECTION_LOADING, null, null)); itemInners.add(new ItemInner(VIEW_TYPE_SECTION_LOADING, null, null)); itemInners.add(new ItemInner(VIEW_TYPE_SECTION_LOADING, null, null)); hasCache = true; } else { ArrayList<ItemInner> sections = new ArrayList<>(); if (photoSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalPhotoCache), 0, photoSize, Theme.key_statisticChartLine_lightblue)); } if (videoSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalVideoCache), 1, videoSize, Theme.key_statisticChartLine_blue)); } if (documentsSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalDocumentCache), 2, documentsSize, Theme.key_statisticChartLine_green)); } if (musicSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalMusicCache), 3, musicSize, Theme.key_statisticChartLine_purple)); } if (audioSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalAudioCache), 4, audioSize, Theme.key_statisticChartLine_lightgreen)); } if (storiesSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalStoriesCache), 5, storiesSize, Theme.key_statisticChartLine_red)); } if (stickersCacheSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalStickersCache), 6, stickersCacheSize, Theme.key_statisticChartLine_orange)); } if (cacheSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalProfilePhotosCache), 7, cacheSize, Theme.key_statisticChartLine_cyan)); } if (cacheTempSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalMiscellaneousCache), 8, cacheTempSize, Theme.key_statisticChartLine_purple)); } if (logsSize > 0) { sections.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalLogsCache), 9, logsSize, Theme.key_statisticChartLine_golden)); } if (!sections.isEmpty()) { Collections.sort(sections, (a, b) -> Long.compare(b.size, a.size)); sections.get(sections.size() - 1).last = true; hasCache = true; if (tempSizes == null) { tempSizes = new float[11]; } for (int i = 0; i < tempSizes.length; ++i) { tempSizes[i] = (float) size(i); } if (percents == null) { percents = new int[11]; } AndroidUtilities.roundPercents(tempSizes, percents); final int MAX_NOT_COLLAPSED = 4; if (sections.size() > MAX_NOT_COLLAPSED + 1) { itemInners.addAll(sections.subList(0, MAX_NOT_COLLAPSED)); int sumPercents = 0; long sum = 0; for (int i = MAX_NOT_COLLAPSED; i < sections.size(); ++i) { sections.get(i).pad = true; sum += sections.get(i).size; sumPercents += percents[sections.get(i).index]; } percents[10] = sumPercents; itemInners.add(ItemInner.asCheckBox(LocaleController.getString(R.string.LocalOther), -1, sum, Theme.key_statisticChartLine_golden)); if (!collapsed) { itemInners.addAll(sections.subList(MAX_NOT_COLLAPSED, sections.size())); } } else { itemInners.addAll(sections); } } } if (hasCache) { sectionsEndRow = itemInners.size(); itemInners.add(new ItemInner(VIEW_TYPE_CLEAR_CACHE_BUTTON, null, null)); itemInners.add(ItemInner.asInfo(LocaleController.getString("StorageUsageInfo", R.string.StorageUsageInfo))); } else { sectionsEndRow = -1; } itemInners.add(new ItemInner(VIEW_TYPE_HEADER, LocaleController.getString("AutoDeleteCachedMedia", R.string.AutoDeleteCachedMedia), null)); itemInners.add(new ItemInner(VIEW_TYPE_KEEP_MEDIA_CELL, KEEP_MEDIA_TYPE_USER)); itemInners.add(new ItemInner(VIEW_TYPE_KEEP_MEDIA_CELL, KEEP_MEDIA_TYPE_GROUP)); itemInners.add(new ItemInner(VIEW_TYPE_KEEP_MEDIA_CELL, KEEP_MEDIA_TYPE_CHANNEL)); itemInners.add(new ItemInner(VIEW_TYPE_KEEP_MEDIA_CELL, KEEP_MEDIA_TYPE_STORIES)); itemInners.add(ItemInner.asInfo(LocaleController.getString("KeepMediaInfoPart", R.string.KeepMediaInfoPart))); if (totalDeviceSize > 0) { itemInners.add(new ItemInner(VIEW_TYPE_HEADER, LocaleController.getString("MaxCacheSize", R.string.MaxCacheSize), null)); itemInners.add(new ItemInner(VIEW_TYPE_MAX_CACHE_SIZE)); itemInners.add(ItemInner.asInfo(LocaleController.getString("MaxCacheSizeInfo", R.string.MaxCacheSizeInfo))); } if (hasCache && cacheModel != null && !cacheModel.isEmpty()) { itemInners.add(new ItemInner(VIEW_TYPE_CACHE_VIEW_PAGER, null, null)); } if (listAdapter != null) { if (animated) { listAdapter.setItems(oldItems, itemInners); } else { listAdapter.notifyDataSetChanged(); } } if (cachedMediaLayout != null) { cachedMediaLayout.update(); } } @Override public boolean needDelayOpenAnimation() { return true; } @Override public void onFragmentDestroy() { super.onFragmentDestroy(); getNotificationCenter().removeObserver(this, NotificationCenter.didClearDatabase); try { if (progressDialog != null) { progressDialog.dismiss(); } } catch (Exception e) { } progressDialog = null; canceled = true; } private static long getDirectorySize(File dir, int documentsMusicType) { if (dir == null || canceled) { return 0; } long size = 0; if (dir.isDirectory()) { size = Utilities.getDirSize(dir.getAbsolutePath(), documentsMusicType, false); } else if (dir.isFile()) { size += dir.length(); } return size; } private void cleanupFolders(Utilities.Callback2<Float, Boolean> onProgress, Runnable onDone) { if (cacheModel != null) { cacheModel.clearSelection(); } if (cachedMediaLayout != null) { cachedMediaLayout.updateVisibleRows(); cachedMediaLayout.showActionMode(false); } // progressDialog = new AlertDialog(getParentActivity(), AlertDialog.ALERT_TYPE_SPINNER); // progressDialog.setCanCancel(false); // progressDialog.showDelayed(500); getFileLoader().cancelLoadAllFiles(); getFileLoader().getFileLoaderQueue().postRunnable(() -> Utilities.globalQueue.postRunnable(() -> { cleanupFoldersInternal(onProgress, onDone); })); setCacheModel(null); loadingDialogs = true; // updateRows(); } private static int LISTDIR_DOCTYPE_ALL = 0; private static int LISTDIR_DOCTYPE_OTHER_THAN_MUSIC = 1; private static int LISTDIR_DOCTYPE_MUSIC = 2; private static int LISTDIR_DOCTYPE2_EMOJI = 3; private static int LISTDIR_DOCTYPE2_TEMP = 4; private static int LISTDIR_DOCTYPE2_OTHER = 5; public static int countDirJava(String fileName, int docType) { int count = 0; File dir = new File(fileName); if (dir.exists()) { File[] entries = dir.listFiles(); if (entries == null) return count; for (int i = 0; i < entries.length; ++i) { File entry = entries[i]; String name = entry.getName(); if (".".equals(name)) { continue; } if (docType > 0 && name.length() >= 4) { String namelc = name.toLowerCase(); boolean isMusic = namelc.endsWith(".mp3") || namelc.endsWith(".m4a"); boolean isEmoji = namelc.endsWith(".tgs") || namelc.endsWith(".webm"); boolean isTemp = namelc.endsWith(".tmp") || namelc.endsWith(".temp") || namelc.endsWith(".preload"); if ( isMusic && docType == LISTDIR_DOCTYPE_OTHER_THAN_MUSIC || !isMusic && docType == LISTDIR_DOCTYPE_MUSIC || isEmoji && docType == LISTDIR_DOCTYPE2_OTHER || !isEmoji && docType == LISTDIR_DOCTYPE2_EMOJI || isTemp && docType == LISTDIR_DOCTYPE2_OTHER || !isTemp && docType == LISTDIR_DOCTYPE2_TEMP ) { continue; } } if (entry.isDirectory()) { count += countDirJava(fileName + "/" + name, docType); } else { count++; } } } return count; } public static void cleanDirJava(String fileName, int docType, int[] p, Utilities.Callback<Float> onProgress) { int count = countDirJava(fileName, docType); if (p == null) { p = new int[] { 0 }; } File dir = new File(fileName); if (dir.exists()) { File[] entries = dir.listFiles(); if (entries == null) return; for (int i = 0; i < entries.length; ++i) { File entry = entries[i]; String name = entry.getName(); if (".".equals(name)) { continue; } if (docType > 0 && name.length() >= 4) { String namelc = name.toLowerCase(); boolean isMusic = namelc.endsWith(".mp3") || namelc.endsWith(".m4a"); boolean isEmoji = namelc.endsWith(".tgs") || namelc.endsWith(".webm"); boolean isTemp = namelc.endsWith(".tmp") || namelc.endsWith(".temp") || namelc.endsWith(".preload"); if ( isMusic && docType == LISTDIR_DOCTYPE_OTHER_THAN_MUSIC || !isMusic && docType == LISTDIR_DOCTYPE_MUSIC || isEmoji && docType == LISTDIR_DOCTYPE2_OTHER || !isEmoji && docType == LISTDIR_DOCTYPE2_EMOJI || isTemp && docType == LISTDIR_DOCTYPE2_OTHER || !isTemp && docType == LISTDIR_DOCTYPE2_TEMP ) { continue; } } if (entry.isDirectory()) { if ("drafts".equals(entry.getName())) { continue; } cleanDirJava(fileName + "/" + name, docType, p, onProgress); } else { entry.delete(); p[0]++; onProgress.run(p[0] / (float) count); } } } } private void cleanupFoldersInternal(Utilities.Callback2<Float, Boolean> onProgress, Runnable onDone) { boolean imagesCleared = false; long clearedSize = 0; boolean allItemsClear = true; final int[] clearDirI = new int[] { 0 }; int clearDirCount = (selected[0] ? 2 : 0) + (selected[1] ? 2 : 0) + (selected[2] ? 2 : 0) + (selected[3] ? 2 : 0) + (selected[4] ? 1 : 0) + (selected[5] ? 2 : 0) + (selected[6] ? 1 : 0) + (selected[7] ? 1 : 0) + (selected[8] ? 1 : 0) + (selected[9] ? 1 : 0); long time = System.currentTimeMillis(); Utilities.Callback<Float> updateProgress = t -> { onProgress.run(clearDirI[0] / (float) clearDirCount + (1f / clearDirCount) * MathUtils.clamp(t, 0, 1), false); }; Runnable next = () -> { final long now = System.currentTimeMillis(); onProgress.run(clearDirI[0] / (float) clearDirCount, now - time > 250); }; for (int a = 0; a < 10; a++) { if (!selected[a]) { allItemsClear = false; continue; } int type = -1; int documentsMusicType = 0; if (a == 0) { type = FileLoader.MEDIA_DIR_IMAGE; clearedSize += photoSize; } else if (a == 1) { type = FileLoader.MEDIA_DIR_VIDEO; clearedSize += videoSize; } else if (a == 2) { type = FileLoader.MEDIA_DIR_DOCUMENT; documentsMusicType = 1; clearedSize += documentsSize; } else if (a == 3) { type = FileLoader.MEDIA_DIR_DOCUMENT; documentsMusicType = 2; clearedSize += musicSize; } else if (a == 4) { type = FileLoader.MEDIA_DIR_AUDIO; clearedSize += audioSize; } else if (a == 5) { type = FileLoader.MEDIA_DIR_STORIES; clearedSize += storiesSize; } else if (a == 6) { type = 100; clearedSize += stickersCacheSize; } else if (a == 7) { clearedSize += cacheSize; documentsMusicType = 5; type = FileLoader.MEDIA_DIR_CACHE; } else if (a == 8) { clearedSize += cacheTempSize; documentsMusicType = 4; type = FileLoader.MEDIA_DIR_CACHE; } else if (a == 9) { clearedSize += logsSize; documentsMusicType = 1; type = 0; } if (type == -1) { continue; } File file; if (a == 9) { file = AndroidUtilities.getLogsDir(); } else if (type == 100) { file = new File(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), "acache"); } else { file = FileLoader.checkDirectory(type); } if (file != null) { cleanDirJava(file.getAbsolutePath(), documentsMusicType, null, updateProgress); } clearDirI[0]++; next.run(); if (type == 100) { file = FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE); if (file != null) { cleanDirJava(file.getAbsolutePath(), 3, null, updateProgress); } clearDirI[0]++; next.run(); } if (type == FileLoader.MEDIA_DIR_IMAGE || type == FileLoader.MEDIA_DIR_VIDEO) { int publicDirectoryType; if (type == FileLoader.MEDIA_DIR_IMAGE) { publicDirectoryType = FileLoader.MEDIA_DIR_IMAGE_PUBLIC; } else { publicDirectoryType = FileLoader.MEDIA_DIR_VIDEO_PUBLIC; } file = FileLoader.checkDirectory(publicDirectoryType); if (file != null) { cleanDirJava(file.getAbsolutePath(), documentsMusicType, null, updateProgress); } clearDirI[0]++; next.run(); } if (type == FileLoader.MEDIA_DIR_DOCUMENT) { file = FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES); if (file != null) { cleanDirJava(file.getAbsolutePath(), documentsMusicType, null, updateProgress); } clearDirI[0]++; next.run(); } if (a == 9) { logsSize = getDirectorySize(AndroidUtilities.getLogsDir(), 1); } else if (type == FileLoader.MEDIA_DIR_CACHE) { cacheSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 5); cacheTempSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 4); imagesCleared = true; } else if (type == FileLoader.MEDIA_DIR_AUDIO) { audioSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_AUDIO), documentsMusicType); } else if (type == FileLoader.MEDIA_DIR_STORIES) { storiesSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_STORIES), documentsMusicType); } else if (type == FileLoader.MEDIA_DIR_DOCUMENT) { if (documentsMusicType == 1) { documentsSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT), documentsMusicType); documentsSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES), documentsMusicType); } else { musicSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_DOCUMENT), documentsMusicType); musicSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_FILES), documentsMusicType); } } else if (type == FileLoader.MEDIA_DIR_IMAGE) { imagesCleared = true; photoSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE), documentsMusicType); photoSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_IMAGE_PUBLIC), documentsMusicType); } else if (type == FileLoader.MEDIA_DIR_VIDEO) { videoSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO), documentsMusicType); videoSize += getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_VIDEO_PUBLIC), documentsMusicType); } else if (type == 100) { imagesCleared = true; stickersCacheSize = getDirectorySize(new File(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), "acache"), documentsMusicType); cacheEmojiSize = getDirectorySize(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), 3); stickersCacheSize += cacheEmojiSize; } } final boolean imagesClearedFinal = imagesCleared; totalSize = lastTotalSizeCalculated = cacheSize + cacheTempSize + logsSize + videoSize + audioSize + photoSize + documentsSize + musicSize + stickersCacheSize + storiesSize; lastTotalSizeCalculatedTime = System.currentTimeMillis(); Arrays.fill(selected, true); File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) { blockSize = stat.getBlockSizeLong(); } else { blockSize = stat.getBlockSize(); } long availableBlocks; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) { availableBlocks = stat.getAvailableBlocksLong(); } else { availableBlocks = stat.getAvailableBlocks(); } long blocksTotal; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) { blocksTotal = stat.getBlockCountLong(); } else { blocksTotal = stat.getBlockCount(); } totalDeviceSize = blocksTotal * blockSize; totalDeviceFreeSize = availableBlocks * blockSize; long finalClearedSize = clearedSize; if (allItemsClear) { FileLoader.getInstance(currentAccount).clearFilePaths(); } FileLoader.getInstance(currentAccount).checkCurrentDownloadsFiles(); AndroidUtilities.runOnUIThread(() -> { if (imagesClearedFinal) { ImageLoader.getInstance().clearMemory(); } try { if (progressDialog != null) { progressDialog.dismiss(); progressDialog = null; } } catch (Exception e) { FileLog.e(e); } getMediaDataController().ringtoneDataStore.checkRingtoneSoundsLoaded(); AndroidUtilities.runOnUIThread(() -> { cacheRemovedTooltip.setInfoText(LocaleController.formatString("CacheWasCleared", R.string.CacheWasCleared, AndroidUtilities.formatFileSize(finalClearedSize))); cacheRemovedTooltip.showWithAction(0, UndoView.ACTION_CACHE_WAS_CLEARED, null, null); }, 150); MediaDataController.getInstance(currentAccount).checkAllMedia(true); loadDialogEntities(); if (onDone != null) { onDone.run(); } }); } private boolean changeStatusBar; @Override public void onTransitionAnimationProgress(boolean isOpen, float progress) { if (progress > .5f && !changeStatusBar) { changeStatusBar = true; NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.needCheckSystemBarColors); } super.onTransitionAnimationProgress(isOpen, progress); } @Override public boolean isLightStatusBar() { if (!changeStatusBar) { return super.isLightStatusBar(); } return AndroidUtilities.computePerceivedBrightness(Theme.getColor(Theme.key_windowBackgroundGray)) > 0.721f; } private long size(int type) { switch (type) { case 0: return photoSize; case 1: return videoSize; case 2: return documentsSize; case 3: return musicSize; case 4: return audioSize; case 5: return storiesSize; case 6: return stickersCacheSize; case 7: return cacheSize; case 8: return cacheTempSize; case 9: return logsSize; default: return 0; } } private int sectionsSelected() { int count = 0; for (int i = 0; i < 10; ++i) { if (selected[i] && size(i) > 0) { count++; } } return count; } private ActionBarMenu actionMode; private AnimatedTextView actionModeTitle; private AnimatedTextView actionModeSubtitle; private TextView actionModeClearButton; @Override public View createView(Context context) { actionBar.setBackgroundDrawable(null); actionBar.setCastShadows(false); actionBar.setAddToContainer(false); actionBar.setOccupyStatusBar(true); actionBar.setTitleColor(ColorUtils.setAlphaComponent(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText), 0)); actionBar.setItemsColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText), false); actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_listSelector), false); actionBar.setBackButtonDrawable(new BackDrawable(false)); actionBar.setAllowOverlayTitle(false); actionBar.setTitle(LocaleController.getString("StorageUsage", R.string.StorageUsage)); actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override public void onItemClick(int id) { if (id == -1) { if (actionBar.isActionModeShowed()) { if (cacheModel != null) { cacheModel.clearSelection(); } if (cachedMediaLayout != null) { cachedMediaLayout.showActionMode(false); cachedMediaLayout.updateVisibleRows(); } return; } finishFragment(); } else if (id == delete_id) { clearSelectedFiles(); } else if (id == clear_database_id) { clearDatabase(false); } else if (id == reset_database_id) { clearDatabase(true); } } }); actionMode = actionBar.createActionMode(); FrameLayout actionModeLayout = new FrameLayout(context); actionMode.addView(actionModeLayout, LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, 72, 0, 0, 0)); actionModeTitle = new AnimatedTextView(context, true, true, true); actionModeTitle.setAnimationProperties(.35f, 0, 350, CubicBezierInterpolator.EASE_OUT_QUINT); actionModeTitle.setTextSize(AndroidUtilities.dp(18)); actionModeTitle.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); actionModeTitle.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); actionModeLayout.addView(actionModeTitle, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.LEFT | Gravity.CENTER_VERTICAL, 0, -11, 18, 0)); actionModeSubtitle = new AnimatedTextView(context, true, true, true); actionModeSubtitle.setAnimationProperties(.35f, 0, 350, CubicBezierInterpolator.EASE_OUT_QUINT); actionModeSubtitle.setTextSize(AndroidUtilities.dp(14)); actionModeSubtitle.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText)); actionModeLayout.addView(actionModeSubtitle, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.LEFT | Gravity.CENTER_VERTICAL, 0, 10, 18, 0)); actionModeClearButton = new TextView(context); actionModeClearButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); actionModeClearButton.setPadding(AndroidUtilities.dp(14), 0, AndroidUtilities.dp(14), 0); actionModeClearButton.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText)); actionModeClearButton.setBackground(Theme.AdaptiveRipple.filledRectByKey(Theme.key_featuredStickers_addButton, 6)); actionModeClearButton.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); actionModeClearButton.setGravity(Gravity.CENTER); actionModeClearButton.setText(LocaleController.getString("CacheClear", R.string.CacheClear)); actionModeClearButton.setOnClickListener(e -> clearSelectedFiles()); if (LocaleController.isRTL) { actionModeLayout.addView(actionModeClearButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 28, Gravity.LEFT | Gravity.CENTER_VERTICAL, 0, 0, 0, 0)); } else { actionModeLayout.addView(actionModeClearButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 28, Gravity.RIGHT | Gravity.CENTER_VERTICAL, 0, 0, 14, 0)); } ActionBarMenuItem otherItem = actionBar.createMenu().addItem(other_id, R.drawable.ic_ab_other); clearDatabaseItem = otherItem.addSubItem(clear_database_id, R.drawable.msg_delete, LocaleController.getString("ClearLocalDatabase", R.string.ClearLocalDatabase)); clearDatabaseItem.setIconColor(Theme.getColor(Theme.key_text_RedRegular)); clearDatabaseItem.setTextColor(Theme.getColor(Theme.key_text_RedBold)); clearDatabaseItem.setSelectorColor(Theme.multAlpha(Theme.getColor(Theme.key_text_RedRegular), .12f)); if (BuildVars.DEBUG_PRIVATE_VERSION) { resetDatabaseItem = otherItem.addSubItem(reset_database_id, R.drawable.msg_delete, "Full Reset Database"); resetDatabaseItem.setIconColor(Theme.getColor(Theme.key_text_RedRegular)); resetDatabaseItem.setTextColor(Theme.getColor(Theme.key_text_RedBold)); resetDatabaseItem.setSelectorColor(Theme.multAlpha(Theme.getColor(Theme.key_text_RedRegular), .12f)); } updateDatabaseItemSize(); listAdapter = new ListAdapter(context); nestedSizeNotifierLayout = new NestedSizeNotifierLayout(context) { @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); boolean show = !isPinnedToTop(); if (!show && actionBarShadowAlpha != 0) { actionBarShadowAlpha -= 16f / 100f; invalidate(); } else if (show && actionBarShadowAlpha != 1f) { actionBarShadowAlpha += 16f / 100f; invalidate(); } actionBarShadowAlpha = Utilities.clamp(actionBarShadowAlpha, 1f, 0); if (parentLayout != null) { parentLayout.drawHeaderShadow(canvas, (int) (0xFF * actionBarShownT * actionBarShadowAlpha), AndroidUtilities.statusBarHeight + ActionBar.getCurrentActionBarHeight()); } } }; fragmentView = nestedSizeNotifierLayout; FrameLayout frameLayout = nestedSizeNotifierLayout; frameLayout.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray)); listView = new RecyclerListView(context) { @Override protected void dispatchDraw(Canvas canvas) { if (sectionsStartRow >= 0 && sectionsEndRow >= 0) { drawSectionBackgroundExclusive(canvas, sectionsStartRow - 1, sectionsEndRow, Theme.getColor(Theme.key_windowBackgroundWhite)); } super.dispatchDraw(canvas); } @Override protected boolean allowSelectChildAtPosition(View child) { return child != cacheChart; } }; listView.setVerticalScrollBarEnabled(false); listView.setClipToPadding(false); listView.setPadding(0, AndroidUtilities.statusBarHeight + ActionBar.getCurrentActionBarHeight() / 2, 0, 0); listView.setLayoutManager(layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)); frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); listView.setAdapter(listAdapter); DefaultItemAnimator itemAnimator = new DefaultItemAnimator() { @Override protected void onMoveAnimationUpdate(RecyclerView.ViewHolder holder) { listView.invalidate(); } }; itemAnimator.setDurations(350); itemAnimator.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); itemAnimator.setDelayAnimations(false); itemAnimator.setSupportsChangeAnimations(false); listView.setItemAnimator(itemAnimator); listView.setOnItemClickListener((view, position, x, y) -> { if (getParentActivity() == null) { return; } if (position < 0 || position >= itemInners.size()) { return; } ItemInner item = itemInners.get(position); // if (position == databaseRow) { // clearDatabase(); // } else if (item.viewType == VIEW_TYPE_SECTION && view instanceof CheckBoxCell) { if (item.index < 0) { collapsed = !collapsed; updateRows(); updateChart(); return; } toggleSection(item, view); } else if (item.entities != null) { // if (view instanceof UserCell && selectedDialogs.size() > 0) { // selectDialog((UserCell) view, itemInners.get(position).entities.dialogId); // return; // } showClearCacheDialog(item.entities); } else if (item.keepMediaType >= 0) { KeepMediaPopupView windowLayout = new KeepMediaPopupView(this, view.getContext()); ActionBarPopupWindow popupWindow = AlertsCreator.createSimplePopup(CacheControlActivity.this, windowLayout, view, x, y); windowLayout.update(itemInners.get(position).keepMediaType); windowLayout.setParentWindow(popupWindow); windowLayout.setCallback((type, keepMedia) -> { AndroidUtilities.updateVisibleRows(listView); }); } }); listView.addOnScrollListener(new RecyclerView.OnScrollListener() { boolean pinned; @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); updateActionBar(layoutManager.findFirstVisibleItemPosition() > 0 || actionBar.isActionModeShowed()); if (pinned != nestedSizeNotifierLayout.isPinnedToTop()) { pinned = nestedSizeNotifierLayout.isPinnedToTop(); nestedSizeNotifierLayout.invalidate(); } } }); frameLayout.addView(actionBar, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); cacheRemovedTooltip = new UndoView(context); frameLayout.addView(cacheRemovedTooltip, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 8, 0, 8, 8)); nestedSizeNotifierLayout.setTargetListView(listView); return fragmentView; } private void clearSelectedFiles() { if (cacheModel.getSelectedFiles() == 0 || getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setTitle(LocaleController.getString("ClearCache", R.string.ClearCache)); builder.setMessage(LocaleController.getString("ClearCacheForChats", R.string.ClearCacheForChats)); builder.setPositiveButton(LocaleController.getString("Clear", R.string.Clear), (di, which) -> { DialogFileEntities mergedEntities = cacheModel.removeSelectedFiles(); if (mergedEntities.totalSize > 0) { cleanupDialogFiles(mergedEntities, null, null); } cacheModel.clearSelection(); if (cachedMediaLayout != null) { cachedMediaLayout.update(); cachedMediaLayout.showActionMode(false); } updateRows(); updateChart(); }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); AlertDialog dialog = builder.create(); showDialog(dialog); TextView button = (TextView) dialog.getButton(DialogInterface.BUTTON_POSITIVE); if (button != null) { button.setTextColor(Theme.getColor(Theme.key_text_RedBold)); } } private ValueAnimator actionBarAnimator; private float actionBarShownT; private boolean actionBarShown; private float actionBarShadowAlpha = 1f; private void updateActionBar(boolean show) { if (show != actionBarShown) { if (actionBarAnimator != null) { actionBarAnimator.cancel(); } actionBarAnimator = ValueAnimator.ofFloat(actionBarShownT, (actionBarShown = show) ? 1f : 0f); actionBarAnimator.addUpdateListener(anm -> { actionBarShownT = (float) anm.getAnimatedValue(); actionBar.setTitleColor(ColorUtils.setAlphaComponent(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText), (int) (255 * actionBarShownT))); actionBar.setBackgroundColor(ColorUtils.setAlphaComponent(Theme.getColor(Theme.key_windowBackgroundWhite), (int) (255 * actionBarShownT))); fragmentView.invalidate(); }); actionBarAnimator.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); actionBarAnimator.setDuration(380); actionBarAnimator.start(); } } private void showClearCacheDialog(DialogFileEntities entities) { if (totalSize <= 0 || getParentActivity() == null) { return; } bottomSheet = new DilogCacheBottomSheet(CacheControlActivity.this, entities, entities.createCacheModel(), new DilogCacheBottomSheet.Delegate() { @Override public void onAvatarClick() { bottomSheet.dismiss(); Bundle args = new Bundle(); if (entities.dialogId > 0) { args.putLong("user_id", entities.dialogId); } else { args.putLong("chat_id", -entities.dialogId); } presentFragment(new ProfileActivity(args, null)); } @Override public void cleanupDialogFiles(DialogFileEntities entities, StorageDiagramView.ClearViewData[] clearViewData, CacheModel cacheModel) { CacheControlActivity.this.cleanupDialogFiles(entities, clearViewData, cacheModel); } }); showDialog(bottomSheet); } private void cleanupDialogFiles(DialogFileEntities dialogEntities, StorageDiagramView.ClearViewData[] clearViewData, CacheModel dialogCacheModel) { final AlertDialog progressDialog = new AlertDialog(getParentActivity(), AlertDialog.ALERT_TYPE_SPINNER); progressDialog.setCanCancel(false); progressDialog.showDelayed(500); HashSet<CacheModel.FileInfo> filesToRemove = new HashSet<>(); long totalSizeBefore = totalSize; for (int a = 0; a < 8; a++) { if (clearViewData != null) { if (clearViewData[a] == null || !clearViewData[a].clear) { continue; } } FileEntities entitiesToDelete = dialogEntities.entitiesByType.get(a); if (entitiesToDelete == null) { continue; } filesToRemove.addAll(entitiesToDelete.files); dialogEntities.totalSize -= entitiesToDelete.totalSize; totalSize -= entitiesToDelete.totalSize; totalDeviceFreeSize += entitiesToDelete.totalSize; dialogEntities.entitiesByType.delete(a); if (a == TYPE_PHOTOS) { photoSize -= entitiesToDelete.totalSize; } else if (a == TYPE_VIDEOS) { videoSize -= entitiesToDelete.totalSize; } else if (a == TYPE_DOCUMENTS) { documentsSize -= entitiesToDelete.totalSize; } else if (a == TYPE_MUSIC) { musicSize -= entitiesToDelete.totalSize; } else if (a == TYPE_VOICE) { audioSize -= entitiesToDelete.totalSize; } else if (a == TYPE_ANIMATED_STICKERS_CACHE) { stickersCacheSize -= entitiesToDelete.totalSize; } else if (a == TYPE_STORIES) { for (int i = 0; i < entitiesToDelete.files.size(); i++) { CacheModel.FileInfo fileInfo = entitiesToDelete.files.get(i); int type = getTypeByPath(entitiesToDelete.files.get(i).file.getAbsolutePath()); if (type == TYPE_STORIES) { storiesSize -= fileInfo.size; } else if (type == TYPE_PHOTOS) { photoSize -= fileInfo.size; } else if (type == TYPE_VIDEOS) { videoSize -= fileInfo.size; } else { cacheSize -= fileInfo.size; } } // cacheSize -= entitiesToDelete.totalSize; }else { cacheSize -= entitiesToDelete.totalSize; } } if (dialogEntities.entitiesByType.size() == 0) { cacheModel.remove(dialogEntities); } updateRows(); if (dialogCacheModel != null) { for (CacheModel.FileInfo fileInfo : dialogCacheModel.selectedFiles) { if (!filesToRemove.contains(fileInfo)) { totalSize -= fileInfo.size; totalDeviceFreeSize += fileInfo.size; filesToRemove.add(fileInfo); dialogEntities.removeFile(fileInfo); if (fileInfo.type == TYPE_PHOTOS) { photoSize -= fileInfo.size; } else if (fileInfo.type == TYPE_VIDEOS) { videoSize -= fileInfo.size; } else if (fileInfo.type == TYPE_DOCUMENTS) { documentsSize -= fileInfo.size; } else if (fileInfo.type == TYPE_MUSIC) { musicSize -= fileInfo.size; } else if (fileInfo.type == TYPE_VOICE) { audioSize -= fileInfo.size; } } } } for (CacheModel.FileInfo fileInfo : filesToRemove) { this.cacheModel.onFileDeleted(fileInfo); } cacheRemovedTooltip.setInfoText(LocaleController.formatString("CacheWasCleared", R.string.CacheWasCleared, AndroidUtilities.formatFileSize(totalSizeBefore - totalSize))); cacheRemovedTooltip.showWithAction(0, UndoView.ACTION_CACHE_WAS_CLEARED, null, null); ArrayList<CacheModel.FileInfo> fileInfos = new ArrayList<>(filesToRemove); getFileLoader().getFileDatabase().removeFiles(fileInfos); getFileLoader().cancelLoadAllFiles(); getFileLoader().getFileLoaderQueue().postRunnable(() -> { for (int i = 0; i < fileInfos.size(); i++) { fileInfos.get(i).file.delete(); } AndroidUtilities.runOnUIThread(() -> { FileLoader.getInstance(currentAccount).checkCurrentDownloadsFiles(); try { progressDialog.dismiss(); } catch (Exception e) { FileLog.e(e); } }); }); } private int getTypeByPath(String absolutePath) { if (pathContains(absolutePath, FileLoader.MEDIA_DIR_STORIES)) { return TYPE_STORIES; } if (pathContains(absolutePath, FileLoader.MEDIA_DIR_IMAGE)) { return TYPE_PHOTOS; } if (pathContains(absolutePath, FileLoader.MEDIA_DIR_IMAGE_PUBLIC)) { return TYPE_PHOTOS; } if (pathContains(absolutePath, FileLoader.MEDIA_DIR_VIDEO)) { return TYPE_VIDEOS; } if (pathContains(absolutePath, FileLoader.MEDIA_DIR_VIDEO_PUBLIC)) { return TYPE_VIDEOS; } return TYPE_OTHER; } private boolean pathContains(String path, int mediaDirType) { if (path == null || FileLoader.checkDirectory(mediaDirType) == null) { return false; } return path.contains(FileLoader.checkDirectory(mediaDirType).getAbsolutePath()); } @RequiresApi(api = Build.VERSION_CODES.R) private void migrateOldFolder() { FilesMigrationService.checkBottomSheet(this); } private void clearDatabase(boolean fullReset) { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("LocalDatabaseClearTextTitle", R.string.LocalDatabaseClearTextTitle)); SpannableStringBuilder message = new SpannableStringBuilder(); message.append(LocaleController.getString("LocalDatabaseClearText", R.string.LocalDatabaseClearText)); message.append("\n\n"); message.append(AndroidUtilities.replaceTags(LocaleController.formatString("LocalDatabaseClearText2", R.string.LocalDatabaseClearText2, AndroidUtilities.formatFileSize(databaseSize)))); builder.setMessage(message); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); builder.setPositiveButton(LocaleController.getString("CacheClear", R.string.CacheClear), (dialogInterface, i) -> { if (getParentActivity() == null) { return; } progressDialog = new AlertDialog(getParentActivity(), AlertDialog.ALERT_TYPE_SPINNER); progressDialog.setCanCancel(false); progressDialog.showDelayed(500); MessagesController.getInstance(currentAccount).clearQueryTime(); if (fullReset) { getMessagesStorage().fullReset(); } else { getMessagesStorage().clearLocalDatabase(); } }); AlertDialog alertDialog = builder.create(); showDialog(alertDialog); TextView button = (TextView) alertDialog.getButton(DialogInterface.BUTTON_POSITIVE); if (button != null) { button.setTextColor(Theme.getColor(Theme.key_text_RedBold)); } } @Override public void onResume() { super.onResume(); listAdapter.notifyDataSetChanged(); if (!calculating) { // loadDialogEntities(); } } @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.didClearDatabase) { try { if (progressDialog != null) { progressDialog.dismiss(); } } catch (Exception e) { FileLog.e(e); } progressDialog = null; if (listAdapter != null) { databaseSize = MessagesStorage.getInstance(currentAccount).getDatabaseSize(); updateDatabaseSize = true; updateDatabaseItemSize(); updateRows(); } } } class CacheChartHeader extends FrameLayout { AnimatedTextView title; TextView[] subtitle = new TextView[3]; View bottomImage; RectF progressRect = new RectF(); LoadingDrawable loadingDrawable = new LoadingDrawable(); Float percent, usedPercent; AnimatedFloat percentAnimated = new AnimatedFloat(this, 450, CubicBezierInterpolator.EASE_OUT_QUINT); AnimatedFloat usedPercentAnimated = new AnimatedFloat(this, 450, CubicBezierInterpolator.EASE_OUT_QUINT); AnimatedFloat loadingFloat = new AnimatedFloat(this, 450, CubicBezierInterpolator.EASE_OUT_QUINT); Paint loadingBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG); Paint percentPaint = new Paint(Paint.ANTI_ALIAS_FLAG); Paint usedPercentPaint = new Paint(Paint.ANTI_ALIAS_FLAG); boolean firstSet = true; public CacheChartHeader(Context context) { super(context); title = new AnimatedTextView(context); title.setAnimationProperties(.35f, 0, 350, CubicBezierInterpolator.EASE_OUT_QUINT); title.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); title.setTextSize(AndroidUtilities.dp(20)); title.setText(LocaleController.getString("StorageUsage", R.string.StorageUsage)); title.setGravity(Gravity.CENTER); title.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); addView(title, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 26, Gravity.TOP | Gravity.CENTER_HORIZONTAL)); for (int i = 0; i < 3; ++i) { subtitle[i] = new TextView(context); subtitle[i].setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13); subtitle[i].setGravity(Gravity.CENTER); subtitle[i].setPadding(AndroidUtilities.dp(24), 0, AndroidUtilities.dp(24), 0); if (i == 0) { subtitle[i].setText(LocaleController.getString("StorageUsageCalculating", R.string.StorageUsageCalculating)); } else if (i == 1) { subtitle[i].setAlpha(0); subtitle[i].setText(LocaleController.getString("StorageUsageTelegram", R.string.StorageUsageTelegram)); subtitle[i].setVisibility(View.INVISIBLE); } else if (i == 2) { subtitle[i].setText(LocaleController.getString("StorageCleared2", R.string.StorageCleared2)); subtitle[i].setAlpha(0); subtitle[i].setVisibility(View.INVISIBLE); } subtitle[i].setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText4)); addView(subtitle[i], LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, i == 2 ? 12 : -6, 0, 0)); } bottomImage = new View(context) { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec) + getPaddingLeft() + getPaddingRight(), MeasureSpec.EXACTLY), heightMeasureSpec); } }; Drawable bottomImageDrawable = getContext().getResources().getDrawable(R.drawable.popup_fixed_alert2).mutate(); bottomImageDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhite), PorterDuff.Mode.MULTIPLY)); bottomImage.setBackground(bottomImageDrawable); MarginLayoutParams bottomImageParams = LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 24, Gravity.BOTTOM | Gravity.FILL_HORIZONTAL); bottomImageParams.leftMargin = -bottomImage.getPaddingLeft(); bottomImageParams.bottomMargin = -AndroidUtilities.dp(11); bottomImageParams.rightMargin = -bottomImage.getPaddingRight(); addView(bottomImage, bottomImageParams); int color = Theme.getColor(Theme.key_windowBackgroundWhiteGrayText4); loadingDrawable.setColors( Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), Theme.multAlpha(color, .2f) ); loadingDrawable.setRadiiDp(4); loadingDrawable.setCallback(this); } public void setData(boolean hasCache, float percent, float usedPercent) { title.setText( hasCache ? LocaleController.getString("StorageUsage", R.string.StorageUsage) : LocaleController.getString("StorageCleared", R.string.StorageCleared) ); if (hasCache) { if (percent < 0.01f) { subtitle[1].setText(LocaleController.formatString("StorageUsageTelegramLess", R.string.StorageUsageTelegramLess, formatPercent(percent))); } else { subtitle[1].setText(LocaleController.formatString("StorageUsageTelegram", R.string.StorageUsageTelegram, formatPercent(percent))); } switchSubtitle(1); } else { switchSubtitle(2); } bottomImage.animate().cancel(); if (firstSet) { bottomImage.setAlpha(hasCache ? 1 : 0); } else { bottomImage.animate().alpha(hasCache ? 1 : 0).setDuration(365).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).start(); } firstSet = false; this.percent = percent; this.usedPercent = usedPercent; invalidate(); } private void switchSubtitle(int type) { boolean animated = System.currentTimeMillis() - fragmentCreateTime > 40; updateViewVisible(subtitle[0], type == 0, animated); updateViewVisible(subtitle[1], type == 1, animated); updateViewVisible(subtitle[2], type == 2, animated); } private void updateViewVisible(View view, boolean show, boolean animated) { if (view == null) { return; } if (view.getParent() == null) { animated = false; } view.animate().setListener(null).cancel(); if (!animated) { view.setVisibility(show ? View.VISIBLE : View.INVISIBLE); view.setTag(show ? 1 : null); view.setAlpha(show ? 1f : 0f); view.setTranslationY(show ? 0 : AndroidUtilities.dp(8)); invalidate(); } else if (show) { if (view.getVisibility() != View.VISIBLE) { view.setVisibility(View.VISIBLE); view.setAlpha(0f); view.setTranslationY(AndroidUtilities.dp(8)); } view.animate().alpha(1f).translationY(0).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).setDuration(340).setUpdateListener(anm -> invalidate()).start(); } else { view.animate().alpha(0).translationY(AndroidUtilities.dp(8)).setListener(new HideViewAfterAnimation(view)).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).setDuration(340).setUpdateListener(anm -> invalidate()).start(); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int fullWidth = MeasureSpec.getSize(widthMeasureSpec); int width = (int) Math.min(AndroidUtilities.dp(174), fullWidth * .8); super.measureChildren(MeasureSpec.makeMeasureSpec(fullWidth, MeasureSpec.EXACTLY), heightMeasureSpec); int height = AndroidUtilities.dp(90 - 18); int maxSubtitleHeight = 0; for (int i = 0; i < subtitle.length; ++i) { maxSubtitleHeight = Math.max(maxSubtitleHeight, subtitle[i].getMeasuredHeight() - (i == 2 ? AndroidUtilities.dp(16) : 0)); } height += maxSubtitleHeight; setMeasuredDimension(fullWidth, height); progressRect.set( (fullWidth - width) / 2f, height - AndroidUtilities.dp(30), (fullWidth + width) / 2f, height - AndroidUtilities.dp(30 - 4) ); } @Override protected void dispatchDraw(Canvas canvas) { float barAlpha = 1f - subtitle[2].getAlpha(); float loading = this.loadingFloat.set(this.percent == null ? 1f : 0f); float percent = this.percentAnimated.set(this.percent == null ? 0 : this.percent); float usedPercent = this.usedPercentAnimated.set(this.usedPercent == null ? 0 : this.usedPercent); loadingBackgroundPaint.setColor(Theme.getColor(Theme.key_actionBarActionModeDefaultSelector)); loadingBackgroundPaint.setAlpha((int) (loadingBackgroundPaint.getAlpha() * barAlpha)); AndroidUtilities.rectTmp.set( Math.max( progressRect.left + (1f - loading) * Math.max(AndroidUtilities.dp(4), usedPercent * progressRect.width()), progressRect.left + (1f - loading) * Math.max(AndroidUtilities.dp(4), percent * progressRect.width()) ) + AndroidUtilities.dp(1), progressRect.top, progressRect.right, progressRect.bottom ); if (AndroidUtilities.rectTmp.left < AndroidUtilities.rectTmp.right && AndroidUtilities.rectTmp.width() > AndroidUtilities.dp(3)) { drawRoundRect(canvas, AndroidUtilities.rectTmp, AndroidUtilities.dp(AndroidUtilities.lerp(1, 2, loading)), AndroidUtilities.dp(2), loadingBackgroundPaint); } loadingDrawable.setBounds(progressRect); loadingDrawable.setAlpha((int) (0xFF * barAlpha * loading)); loadingDrawable.draw(canvas); usedPercentPaint.setColor(ColorUtils.blendARGB(Theme.getColor(Theme.key_radioBackgroundChecked), Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), .75f)); usedPercentPaint.setAlpha((int) (usedPercentPaint.getAlpha() * barAlpha)); AndroidUtilities.rectTmp.set( progressRect.left + (1f - loading) * Math.max(AndroidUtilities.dp(4), percent * progressRect.width()) + AndroidUtilities.dp(1), progressRect.top, progressRect.left + (1f - loading) * Math.max(AndroidUtilities.dp(4), usedPercent * progressRect.width()), progressRect.bottom ); if (AndroidUtilities.rectTmp.width() > AndroidUtilities.dp(3)) { drawRoundRect(canvas, AndroidUtilities.rectTmp, AndroidUtilities.dp(1), AndroidUtilities.dp(usedPercent > .97f ? 2 : 1), usedPercentPaint); } percentPaint.setColor(Theme.getColor(Theme.key_radioBackgroundChecked)); percentPaint.setAlpha((int) (percentPaint.getAlpha() * barAlpha)); AndroidUtilities.rectTmp.set(progressRect.left, progressRect.top, progressRect.left + (1f - loading) * Math.max(AndroidUtilities.dp(4), percent * progressRect.width()), progressRect.bottom); drawRoundRect(canvas, AndroidUtilities.rectTmp, AndroidUtilities.dp(2), AndroidUtilities.dp(percent > .97f ? 2 : 1), percentPaint); if (loading > 0 || this.percentAnimated.isInProgress()) { invalidate(); } super.dispatchDraw(canvas); } private Path roundPath; private float[] radii; private void drawRoundRect(Canvas canvas, RectF rect, float left, float right, Paint paint) { if (roundPath == null) { roundPath = new Path(); } else { roundPath.rewind(); } if (radii == null) { radii = new float[8]; } radii[0] = radii[1] = radii[6] = radii[7] = left; radii[2] = radii[3] = radii[4] = radii[5] = right; roundPath.addRoundRect(rect, radii, Path.Direction.CW); canvas.drawPath(roundPath, paint); } } private class ClearingCacheView extends FrameLayout { RLottieImageView imageView; AnimatedTextView percentsTextView; ProgressView progressView; TextView title, subtitle; public ClearingCacheView(Context context) { super(context); imageView = new RLottieImageView(context); imageView.setAutoRepeat(true); imageView.setAnimation(R.raw.utyan_cache, 150, 150); addView(imageView, LayoutHelper.createFrame(150, 150, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 16, 0, 0)); imageView.playAnimation(); percentsTextView = new AnimatedTextView(context, false, true, true); percentsTextView.setAnimationProperties(.35f, 0, 120, CubicBezierInterpolator.EASE_OUT); percentsTextView.setGravity(Gravity.CENTER_HORIZONTAL); percentsTextView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); percentsTextView.setTextSize(AndroidUtilities.dp(24)); percentsTextView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); addView(percentsTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 32, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 16 + 150 + 16 - 6, 0, 0)); progressView = new ProgressView(context); addView(progressView, LayoutHelper.createFrame(240, 5, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 16 + 150 + 16 + 28 + 16, 0, 0)); title = new TextView(context); title.setGravity(Gravity.CENTER_HORIZONTAL); title.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); title.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); title.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); title.setText(LocaleController.getString("ClearingCache", R.string.ClearingCache)); addView(title, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 16 + 150 + 16 + 28 + 16 + 5 + 30, 0, 0)); subtitle = new TextView(context); subtitle.setGravity(Gravity.CENTER_HORIZONTAL); subtitle.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); subtitle.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); subtitle.setText(LocaleController.getString("ClearingCacheDescription", R.string.ClearingCacheDescription)); addView(subtitle, LayoutHelper.createFrame(240, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 16 + 150 + 16 + 28 + 16 + 5 + 30 + 18 + 10, 0, 0)); setProgress(0); } public void setProgress(float t) { percentsTextView.cancelAnimation(); percentsTextView.setText(String.format("%d%%", (int) Math.ceil(MathUtils.clamp(t, 0, 1) * 100)), !LocaleController.isRTL); progressView.setProgress(t); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure( MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(350), MeasureSpec.EXACTLY) ); } class ProgressView extends View { Paint in = new Paint(Paint.ANTI_ALIAS_FLAG), out = new Paint(Paint.ANTI_ALIAS_FLAG); public ProgressView(Context context) { super(context); in.setColor(Theme.getColor(Theme.key_switchTrackChecked)); out.setColor(Theme.multAlpha(Theme.getColor(Theme.key_switchTrackChecked), .2f)); } float progress; AnimatedFloat progressT = new AnimatedFloat(this, 350, CubicBezierInterpolator.EASE_OUT); public void setProgress(float t) { this.progress = t; invalidate(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); AndroidUtilities.rectTmp.set(0, 0, getMeasuredWidth(), getMeasuredHeight()); canvas.drawRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(3), AndroidUtilities.dp(3), out); AndroidUtilities.rectTmp.set(0, 0, getMeasuredWidth() * progressT.set(this.progress), getMeasuredHeight()); canvas.drawRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(3), AndroidUtilities.dp(3), in); } } } private class ClearCacheButtonInternal extends ClearCacheButton { public ClearCacheButtonInternal(Context context) { super(context); ((MarginLayoutParams) button.getLayoutParams()).topMargin = AndroidUtilities.dp(5); button.setOnClickListener(e -> { AlertDialog dialog = new AlertDialog.Builder(getContext()) .setTitle(LocaleController.getString("ClearCache", R.string.ClearCache) + (TextUtils.isEmpty(valueTextView.getText()) ? "" : " (" + valueTextView.getText() + ")")) .setMessage(LocaleController.getString("StorageUsageInfo", R.string.StorageUsageInfo)) .setPositiveButton(textView.getText(), (di, v) -> doClearCache()) .setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null) .create(); showDialog(dialog); View clearButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE); if (clearButton instanceof TextView) { ((TextView) clearButton).setTextColor(Theme.getColor(Theme.key_text_RedRegular)); clearButton.setBackground(Theme.getRoundRectSelectorDrawable(AndroidUtilities.dp(6), Theme.multAlpha(Theme.getColor(Theme.key_text_RedRegular), .12f))); } }); } private void doClearCache() { BottomSheet bottomSheet = new BottomSheet(getContext(), false) { @Override protected boolean canDismissWithTouchOutside() { return false; } }; bottomSheet.fixNavigationBar(); bottomSheet.setCanDismissWithSwipe(false); bottomSheet.setCancelable(false); ClearingCacheView cacheView = new ClearingCacheView(getContext()); bottomSheet.setCustomView(cacheView); final boolean[] done = new boolean[] { false }; final float[] progress = new float[] { 0 }; final boolean[] nextSection = new boolean[] { false }; Runnable updateProgress = () -> { cacheView.setProgress(progress[0]); if (nextSection[0]) { updateRows(); } }; final long[] start = new long[] { -1 }; AndroidUtilities.runOnUIThread(() -> { if (!done[0]) { start[0] = System.currentTimeMillis(); showDialog(bottomSheet); } }, 150); cleanupFolders( (progressValue, next) -> { progress[0] = progressValue; nextSection[0] = next; AndroidUtilities.cancelRunOnUIThread(updateProgress); AndroidUtilities.runOnUIThread(updateProgress); }, () -> AndroidUtilities.runOnUIThread(() -> { done[0] = true; cacheView.setProgress(1F); if (start[0] > 0) { AndroidUtilities.runOnUIThread(bottomSheet::dismiss, Math.max(0, 1000 - (System.currentTimeMillis() - start[0]))); } else { bottomSheet.dismiss(); } }) ); } public void updateSize() { long size = ( (selected[0] ? photoSize : 0) + (selected[1] ? videoSize : 0) + (selected[2] ? documentsSize : 0) + (selected[3] ? musicSize : 0) + (selected[4] ? audioSize : 0) + (selected[5] ? storiesSize : 0) + (selected[6] ? stickersCacheSize : 0) + (selected[7] ? cacheSize : 0) + (selected[8] ? cacheTempSize : 0) + (selected[9] ? logsSize : 0) ); setSize( isAllSectionsSelected(), size ); } } private boolean isAllSectionsSelected() { for (int i = 0; i < itemInners.size(); ++i) { ItemInner item = itemInners.get(i); if (item.viewType != VIEW_TYPE_SECTION) { continue; } int index = item.index; if (index < 0) { index = selected.length - 1; } if (!selected[index]) { return false; } } return true; } public static class ClearCacheButton extends FrameLayout { FrameLayout button; AnimatedTextView.AnimatedTextDrawable textView; AnimatedTextView.AnimatedTextDrawable valueTextView; TextView rtlTextView; public ClearCacheButton(Context context) { super(context); button = new FrameLayout(context) { @Override protected void dispatchDraw(Canvas canvas) { final int margin = AndroidUtilities.dp(8); int x = (getMeasuredWidth() - margin - (int) valueTextView.getCurrentWidth() + (int) textView.getCurrentWidth()) / 2; if (LocaleController.isRTL) { super.dispatchDraw(canvas); } else { textView.setBounds(0, 0, x, getHeight()); textView.draw(canvas); valueTextView.setBounds(x + AndroidUtilities.dp(8), 0, getWidth(), getHeight()); valueTextView.draw(canvas); } } @Override protected boolean verifyDrawable(@NonNull Drawable who) { return who == valueTextView || who == textView || super.verifyDrawable(who); } @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setClassName("android.widget.Button"); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { super.onInterceptTouchEvent(ev); return true; } }; button.setBackground(Theme.AdaptiveRipple.filledRectByKey(Theme.key_featuredStickers_addButton, 8)); button.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); if (LocaleController.isRTL) { rtlTextView = new TextView(context); rtlTextView.setText(LocaleController.getString("ClearCache", R.string.ClearCache)); rtlTextView.setGravity(Gravity.CENTER); rtlTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); rtlTextView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); rtlTextView.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText)); button.addView(rtlTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER)); } textView = new AnimatedTextView.AnimatedTextDrawable(true, true, true); textView.setAnimationProperties(.25f, 0, 300, CubicBezierInterpolator.EASE_OUT_QUINT); textView.setCallback(button); textView.setTextSize(AndroidUtilities.dp(14)); textView.setText(LocaleController.getString("ClearCache", R.string.ClearCache)); textView.setGravity(Gravity.RIGHT); textView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); textView.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText)); valueTextView = new AnimatedTextView.AnimatedTextDrawable(true, true, true); valueTextView.setAnimationProperties(.25f, 0, 300, CubicBezierInterpolator.EASE_OUT_QUINT); valueTextView.setCallback(button); valueTextView.setTextSize(AndroidUtilities.dp(14)); valueTextView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); valueTextView.setTextColor(Theme.blendOver(Theme.getColor(Theme.key_featuredStickers_addButton), Theme.multAlpha(Theme.getColor(Theme.key_featuredStickers_buttonText), .7f))); valueTextView.setText(""); button.setContentDescription(TextUtils.concat(textView.getText(), "\t", valueTextView.getText())); setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); addView(button, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.FILL, 16, 16, 16, 16)); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure( MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), heightMeasureSpec ); } public void setSize(boolean allSelected, long size) { textView.setText(( allSelected ? LocaleController.getString("ClearCache", R.string.ClearCache) : LocaleController.getString("ClearSelectedCache", R.string.ClearSelectedCache) )); valueTextView.setText(size <= 0 ? "" : AndroidUtilities.formatFileSize(size)); setDisabled(size <= 0); button.invalidate(); button.setContentDescription(TextUtils.concat(textView.getText(), "\t", valueTextView.getText())); } public void setDisabled(boolean disabled) { button.animate().cancel(); button.animate().alpha(disabled ? .65f : 1f).start(); button.setClickable(!disabled); } } private boolean isOtherSelected() { boolean[] indexes = new boolean[CacheControlActivity.this.selected.length]; for (int i = 0; i < itemInners.size(); ++i) { ItemInner item2 = itemInners.get(i); if (item2.viewType == VIEW_TYPE_SECTION && !item2.pad && item2.index >= 0) { indexes[item2.index] = true; } } for (int i = 0; i < indexes.length; ++i) { if (!indexes[i] && !CacheControlActivity.this.selected[i]) { return false; } } return true; } private void toggleSection(ItemInner item, View cell) { if (item.index < 0) { toggleOtherSelected(cell); return; } if (selected[item.index] && sectionsSelected() <= 1) { BotWebViewVibrationEffect.APP_ERROR.vibrate(); if (cell != null) { AndroidUtilities.shakeViewSpring(cell, -3); } return; } if (cell instanceof CheckBoxCell) { ((CheckBoxCell) cell).setChecked(selected[item.index] = !selected[item.index], true); } else { selected[item.index] = !selected[item.index]; int position = itemInners.indexOf(item); if (position >= 0) { for (int i = 0; i < listView.getChildCount(); ++i) { View child = listView.getChildAt(i); if (child instanceof CheckBoxCell && position == listView.getChildAdapterPosition(child)) { ((CheckBoxCell) child).setChecked(selected[item.index], true); } } } } if (item.pad) { for (int i = 0; i < listView.getChildCount(); ++i) { View child = listView.getChildAt(i); if (child instanceof CheckBoxCell) { int pos = listView.getChildAdapterPosition(child); if (pos >= 0 && pos < itemInners.size() && itemInners.get(pos).index < 0) { ((CheckBoxCell) child).setChecked(isOtherSelected(), true); break; } } } } updateChart(); } private void toggleOtherSelected(View cell) { boolean selected = isOtherSelected(); if (selected) { boolean hasNonOtherSelected = false; for (int i = 0; i < itemInners.size(); ++i) { ItemInner item2 = itemInners.get(i); if (item2.viewType == VIEW_TYPE_SECTION && !item2.pad && item2.index >= 0 && CacheControlActivity.this.selected[item2.index]) { hasNonOtherSelected = true; break; } } if (!hasNonOtherSelected) { BotWebViewVibrationEffect.APP_ERROR.vibrate(); if (cell != null) { AndroidUtilities.shakeViewSpring(cell, -3); } return; } } if (collapsed) { boolean[] indexes = new boolean[CacheControlActivity.this.selected.length]; for (int i = 0; i < itemInners.size(); ++i) { ItemInner item2 = itemInners.get(i); if (item2.viewType == VIEW_TYPE_SECTION && !item2.pad && item2.index >= 0) { indexes[item2.index] = true; } } for (int i = 0; i < indexes.length; ++i) { if (!indexes[i]) { CacheControlActivity.this.selected[i] = !selected; } } } else { for (int i = 0; i < itemInners.size(); ++i) { ItemInner item2 = itemInners.get(i); if (item2.viewType == VIEW_TYPE_SECTION && item2.pad && item2.index >= 0) { CacheControlActivity.this.selected[item2.index] = !selected; } } } for (int i = 0; i < listView.getChildCount(); ++i) { View child = listView.getChildAt(i); if (child instanceof CheckBoxCell) { int pos = listView.getChildAdapterPosition(child); if (pos >= 0) { ItemInner item2 = itemInners.get(pos); if (item2.viewType == VIEW_TYPE_SECTION) { if (item2.index < 0) { ((CheckBoxCell) child).setChecked(!selected, true); } else { ((CheckBoxCell) child).setChecked(CacheControlActivity.this.selected[item2.index], true); } } } } } updateChart(); } private class ListAdapter extends AdapterWithDiffUtils { private Context mContext; public ListAdapter(Context context) { mContext = context; } @Override public boolean isEnabled(RecyclerView.ViewHolder holder) { int position = holder.getAdapterPosition(); return position == migrateOldFolderRow || (holder.getItemViewType() == VIEW_TYPE_STORAGE && (totalSize > 0) && !calculating) || holder.getItemViewType() == VIEW_TYPE_CHAT || holder.getItemViewType() == VIEW_TYPE_KEEP_MEDIA_CELL || holder.getItemViewType() == VIEW_TYPE_SECTION; } @Override public int getItemCount() { return itemInners.size(); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view; switch (viewType) { case VIEW_TYPE_TEXT_SETTINGS: view = new TextSettingsCell(mContext); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); break; case VIEW_TYPE_STORAGE: view = new StorageUsageView(mContext); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); break; case VIEW_TYPE_HEADER: view = new HeaderCell(mContext); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); break; case VIEW_TYPE_CHOOSER: SlideChooseView slideChooseView = new SlideChooseView(mContext); view = slideChooseView; view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); slideChooseView.setCallback(index -> { if (index == 0) { SharedConfig.setKeepMedia(3); } else if (index == 1) { SharedConfig.setKeepMedia(0); } else if (index == 2) { SharedConfig.setKeepMedia(1); } else if (index == 3) { SharedConfig.setKeepMedia(2); } }); int keepMedia = SharedConfig.keepMedia; int index; if (keepMedia == 3) { index = 0; } else { index = keepMedia + 1; } slideChooseView.setOptions(index, LocaleController.formatPluralString("Days", 3), LocaleController.formatPluralString("Weeks", 1), LocaleController.formatPluralString("Months", 1), LocaleController.getString("KeepMediaForever", R.string.KeepMediaForever)); break; case VIEW_TYPE_CHAT: UserCell userCell = new UserCell(getContext(), getResourceProvider()); userCell.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); view = userCell; break; case VIEW_FLICKER_LOADING_DIALOG: FlickerLoadingView flickerLoadingView = new FlickerLoadingView(getContext()); flickerLoadingView.setIsSingleCell(true); flickerLoadingView.setItemsCount(3); flickerLoadingView.setIgnoreHeightCheck(true); flickerLoadingView.setViewType(FlickerLoadingView.DIALOG_CACHE_CONTROL); flickerLoadingView.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); view = flickerLoadingView; break; case VIEW_TYPE_KEEP_MEDIA_CELL: view = new TextCell(mContext); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); break; case VIEW_TYPE_CHART: view = cacheChart = new CacheChart(mContext) { @Override protected void onSectionClick(int index) { // if (index == 8) { // index = -1; // } // for (int i = 0; i < itemInners.size(); ++i) { // ItemInner item = itemInners.get(i); // if (item != null && item.index == index) { // toggleSection(item, null); // return; // } // } } @Override protected void onSectionDown(int index, boolean down) { if (!down) { listView.removeHighlightRow(); return; } if (index == 8) { index = -1; } int position = -1; for (int i = 0; i < itemInners.size(); ++i) { ItemInner item2 = itemInners.get(i); if (item2 != null && item2.viewType == VIEW_TYPE_SECTION && item2.index == index) { position = i; break; } } if (position >= 0) { final int finalPosition = position; listView.highlightRow(() -> finalPosition, 0); } else { listView.removeHighlightRow(); } } }; break; case VIEW_TYPE_CHART_HEADER: view = cacheChartHeader = new CacheChartHeader(mContext); break; case VIEW_TYPE_SECTION_LOADING: FlickerLoadingView flickerLoadingView2 = new FlickerLoadingView(getContext()); flickerLoadingView2.setIsSingleCell(true); flickerLoadingView2.setItemsCount(1); flickerLoadingView2.setIgnoreHeightCheck(true); flickerLoadingView2.setViewType(FlickerLoadingView.CHECKBOX_TYPE); flickerLoadingView2.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); view = flickerLoadingView2; break; case VIEW_TYPE_SECTION: view = new CheckBoxCell(mContext, 4, 21, getResourceProvider()); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); break; case VIEW_TYPE_INFO: default: view = new TextInfoPrivacyCell(mContext); break; case VIEW_TYPE_CACHE_VIEW_PAGER: view = cachedMediaLayout = new CachedMediaLayout(mContext, CacheControlActivity.this) { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(heightMeasureSpec) - (ActionBar.getCurrentActionBarHeight() / 2), MeasureSpec.EXACTLY)); } @Override protected void showActionMode(boolean show) { if (show) { updateActionBar(true); actionBar.showActionMode(); } else { actionBar.hideActionMode(); } } @Override protected boolean actionModeIsVisible() { return actionBar.isActionModeShowed(); } }; cachedMediaLayout.setDelegate(new CachedMediaLayout.Delegate() { @Override public void onItemSelected(DialogFileEntities entities, CacheModel.FileInfo fileInfo, boolean longPress) { if (entities != null) { if ((cacheModel.getSelectedFiles() > 0 || longPress)) { cacheModel.toggleSelect(entities); cachedMediaLayout.updateVisibleRows(); updateActionMode(); } else { showClearCacheDialog(entities); } return; } if (fileInfo != null) { cacheModel.toggleSelect(fileInfo); cachedMediaLayout.updateVisibleRows(); updateActionMode(); } } @Override public void clear() { clearSelectedFiles(); } @Override public void clearSelection() { if (cacheModel != null && cacheModel.getSelectedFiles() > 0) { cacheModel.clearSelection(); if (cachedMediaLayout != null) { cachedMediaLayout.showActionMode(false); cachedMediaLayout.updateVisibleRows(); } return; } } }); cachedMediaLayout.setCacheModel(cacheModel); nestedSizeNotifierLayout.setChildLayout(cachedMediaLayout); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); view.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); break; case VIEW_TYPE_CLEAR_CACHE_BUTTON: view = clearCacheButton = new ClearCacheButtonInternal(mContext); break; case VIEW_TYPE_MAX_CACHE_SIZE: SlideChooseView slideChooseView2 = new SlideChooseView(mContext); view = slideChooseView2; view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); float totalSizeInGb = (int) (totalDeviceSize / 1024L / 1024L) / 1000.0f; ArrayList<Integer> options = new ArrayList<>(); // if (BuildVars.DEBUG_PRIVATE_VERSION) { // options.add(1); // } if (totalSizeInGb <= 17) { options.add(2); } if (totalSizeInGb > 5) { options.add(5); } if (totalSizeInGb > 16) { options.add(16); } if (totalSizeInGb > 32) { options.add(32); } options.add(Integer.MAX_VALUE); String[] values = new String[options.size()]; for (int i = 0; i < options.size(); i++) { if (options.get(i) == 1) { values[i] = String.format("300 MB"); } else if (options.get(i) == Integer.MAX_VALUE) { values[i] = LocaleController.getString("NoLimit", R.string.NoLimit); } else { values[i] = String.format("%d GB", options.get(i)); } } slideChooseView2.setCallback(i -> { SharedConfig.getPreferences().edit().putInt("cache_limit", options.get(i)).apply(); }); int currentLimit = SharedConfig.getPreferences().getInt("cache_limit", Integer.MAX_VALUE); int i = options.indexOf(currentLimit); if (i < 0) { i = options.size() - 1; } slideChooseView2.setOptions(i, values); break; } return new RecyclerListView.Holder(view); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { final ItemInner item = itemInners.get(position); switch (holder.getItemViewType()) { case VIEW_TYPE_CHART: updateChart(); break; case VIEW_TYPE_CHART_HEADER: if (cacheChartHeader != null && !calculating) { cacheChartHeader.setData( totalSize > 0, totalDeviceSize <= 0 ? 0 : (float) totalSize / totalDeviceSize, totalDeviceFreeSize <= 0 || totalDeviceSize <= 0 ? 0 : (float) (totalDeviceSize - totalDeviceFreeSize) / totalDeviceSize ); } break; case VIEW_TYPE_SECTION: CheckBoxCell cell = (CheckBoxCell) holder.itemView; final boolean selected; if (item.index < 0) { selected = isOtherSelected(); } else { selected = CacheControlActivity.this.selected[item.index]; } cell.setText(getCheckBoxTitle(item.headerName, percents[item.index < 0 ? 9 : item.index], item.index < 0), AndroidUtilities.formatFileSize(item.size), selected, item.index < 0 ? !collapsed : !item.last); cell.setCheckBoxColor(item.colorKey, Theme.key_windowBackgroundWhiteGrayIcon, Theme.key_checkboxCheck); cell.setCollapsed(item.index < 0 ? collapsed : null); if (item.index == -1) { cell.setOnSectionsClickListener(e -> { collapsed = !collapsed; updateRows(); updateChart(); }, e -> toggleOtherSelected(cell)); } else { cell.setOnSectionsClickListener(null, null); } cell.setPad(item.pad ? 1 : 0); break; case VIEW_TYPE_KEEP_MEDIA_CELL: TextCell textCell2 = (TextCell) holder.itemView; CacheByChatsController cacheByChatsController = getMessagesController().getCacheByChatsController(); int keepMediaType = item.keepMediaType; int exceptionsCount = cacheByChatsController.getKeepMediaExceptions(itemInners.get(position).keepMediaType).size(); String subtitle = null; if (exceptionsCount > 0) { subtitle = LocaleController.formatPluralString("ExceptionShort", exceptionsCount, exceptionsCount); } String value = CacheByChatsController.getKeepMediaString(cacheByChatsController.getKeepMedia(keepMediaType)); if (itemInners.get(position).keepMediaType == KEEP_MEDIA_TYPE_USER) { textCell2.setTextAndValueAndColorfulIcon(LocaleController.getString("PrivateChats", R.string.PrivateChats), value, true, R.drawable.msg_filled_menu_users, getThemedColor(Theme.key_statisticChartLine_lightblue), true); } else if (itemInners.get(position).keepMediaType == KEEP_MEDIA_TYPE_GROUP) { textCell2.setTextAndValueAndColorfulIcon(LocaleController.getString("GroupChats", R.string.GroupChats), value, true, R.drawable.msg_filled_menu_groups, getThemedColor(Theme.key_statisticChartLine_green), true); } else if (itemInners.get(position).keepMediaType == KEEP_MEDIA_TYPE_CHANNEL) { textCell2.setTextAndValueAndColorfulIcon(LocaleController.getString("CacheChannels", R.string.CacheChannels), value, true, R.drawable.msg_filled_menu_channels, getThemedColor(Theme.key_statisticChartLine_golden), true); } else if (itemInners.get(position).keepMediaType == KEEP_MEDIA_TYPE_STORIES) { textCell2.setTextAndValueAndColorfulIcon(LocaleController.getString("CacheStories", R.string.CacheStories), value, false, R.drawable.msg_filled_stories, getThemedColor(Theme.key_statisticChartLine_red), false); } textCell2.setSubtitle(subtitle); break; case VIEW_TYPE_TEXT_SETTINGS: TextSettingsCell textCell = (TextSettingsCell) holder.itemView; // if (position == databaseRow) { // textCell.setTextAndValue(LocaleController.getString("ClearLocalDatabase", R.string.ClearLocalDatabase), AndroidUtilities.formatFileSize(databaseSize), updateDatabaseSize, false); // updateDatabaseSize = false; // } else if (position == migrateOldFolderRow) { textCell.setTextAndValue(LocaleController.getString("MigrateOldFolder", R.string.MigrateOldFolder), null, false); } break; case VIEW_TYPE_INFO: TextInfoPrivacyCell privacyCell = (TextInfoPrivacyCell) holder.itemView; // if (position == databaseInfoRow) { // privacyCell.setText(LocaleController.getString("LocalDatabaseInfo", R.string.LocalDatabaseInfo)); // privacyCell.setBackgroundDrawable(Theme.getThemedDrawable(mContext, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow)); // } else if (position == keepMediaInfoRow) { // privacyCell.setText(AndroidUtilities.replaceTags(LocaleController.getString("KeepMediaInfo", R.string.KeepMediaInfo))); // privacyCell.setBackgroundDrawable(Theme.getThemedDrawable(mContext, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow)); // } else { privacyCell.setText(AndroidUtilities.replaceTags(item.text)); privacyCell.setBackgroundDrawable(Theme.getThemedDrawableByKey(mContext, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow)); // } break; case VIEW_TYPE_STORAGE: StorageUsageView storageUsageView = (StorageUsageView) holder.itemView; storageUsageView.setStorageUsage(calculating, databaseSize, totalSize, totalDeviceFreeSize, totalDeviceSize); break; case VIEW_TYPE_HEADER: HeaderCell headerCell = (HeaderCell) holder.itemView; headerCell.setText(itemInners.get(position).headerName); headerCell.setTopMargin(itemInners.get(position).headerTopMargin); headerCell.setBottomMargin(itemInners.get(position).headerBottomMargin); break; } } @Override public int getItemViewType(int i) { return itemInners.get(i).viewType; } } private void updateActionMode() { if (cacheModel.getSelectedFiles() > 0) { if (cachedMediaLayout != null) { String filesString; if (!cacheModel.selectedDialogs.isEmpty()) { int filesInChats = 0; for (CacheControlActivity.DialogFileEntities entity : cacheModel.entities) { if (cacheModel.selectedDialogs.contains(entity.dialogId)) { filesInChats += entity.filesCount; } } int filesNotInChat = cacheModel.getSelectedFiles() - filesInChats; if (filesNotInChat > 0) { filesString = String.format("%s, %s", LocaleController.formatPluralString("Chats", cacheModel.selectedDialogs.size(), cacheModel.selectedDialogs.size()), LocaleController.formatPluralString("Files", filesNotInChat, filesNotInChat) ); } else { filesString = LocaleController.formatPluralString("Chats", cacheModel.selectedDialogs.size(), cacheModel.selectedDialogs.size()); } } else { filesString = LocaleController.formatPluralString("Files", cacheModel.getSelectedFiles(), cacheModel.getSelectedFiles()); } String sizeString = AndroidUtilities.formatFileSize(cacheModel.getSelectedFilesSize()); actionModeTitle.setText(sizeString, !LocaleController.isRTL); actionModeSubtitle.setText(filesString, !LocaleController.isRTL); cachedMediaLayout.showActionMode(true); } } else { cachedMediaLayout.showActionMode(false); return; } } @Override public ArrayList<ThemeDescription> getThemeDescriptions() { ThemeDescription.ThemeDescriptionDelegate deldegagte = () -> { if (bottomSheet != null) { bottomSheet.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground)); } if (actionTextView != null) { actionTextView.setBackground(Theme.AdaptiveRipple.filledRectByKey(Theme.key_featuredStickers_addButton, 4)); } }; ArrayList<ThemeDescription> arrayList = new ArrayList<>(); arrayList.add(new ThemeDescription(listView, ThemeDescription.FLAG_CELLBACKGROUNDCOLOR, new Class[]{TextSettingsCell.class, SlideChooseView.class, StorageUsageView.class, HeaderCell.class}, null, null, null, Theme.key_windowBackgroundWhite)); arrayList.add(new ThemeDescription(fragmentView, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_windowBackgroundGray)); arrayList.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_actionBarDefault)); arrayList.add(new ThemeDescription(listView, ThemeDescription.FLAG_LISTGLOWCOLOR, null, null, null, null, Theme.key_actionBarDefault)); arrayList.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_ITEMSCOLOR, null, null, null, null, Theme.key_actionBarDefaultIcon)); arrayList.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_TITLECOLOR, null, null, null, null, Theme.key_actionBarDefaultTitle)); arrayList.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SELECTORCOLOR, null, null, null, null, Theme.key_actionBarDefaultSelector)); arrayList.add(new ThemeDescription(listView, ThemeDescription.FLAG_SELECTOR, null, null, null, null, Theme.key_listSelector)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{TextSettingsCell.class}, new String[]{"textView"}, null, null, null, Theme.key_windowBackgroundWhiteBlackText)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{TextSettingsCell.class}, new String[]{"valueTextView"}, null, null, null, Theme.key_windowBackgroundWhiteValueText)); arrayList.add(new ThemeDescription(listView, ThemeDescription.FLAG_BACKGROUNDFILTER, new Class[]{TextInfoPrivacyCell.class}, null, null, null, Theme.key_windowBackgroundGrayShadow)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{TextInfoPrivacyCell.class}, new String[]{"textView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText4)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{HeaderCell.class}, new String[]{"textView"}, null, null, null, Theme.key_windowBackgroundWhiteBlueHeader)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{StorageUsageView.class}, new String[]{"paintFill"}, null, null, null, Theme.key_player_progressBackground)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{StorageUsageView.class}, new String[]{"paintProgress"}, null, null, null, Theme.key_player_progress)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{StorageUsageView.class}, new String[]{"telegramCacheTextView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{StorageUsageView.class}, new String[]{"freeSizeTextView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{StorageUsageView.class}, new String[]{"calculationgTextView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{SlideChooseView.class}, null, null, null, Theme.key_switchTrack)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{SlideChooseView.class}, null, null, null, Theme.key_switchTrackChecked)); arrayList.add(new ThemeDescription(listView, 0, new Class[]{SlideChooseView.class}, null, null, null, Theme.key_windowBackgroundWhiteGrayText)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_windowBackgroundWhiteGrayText)); arrayList.add(new ThemeDescription(bottomSheetView, 0, new Class[]{CheckBoxCell.class}, new String[]{"textView"}, null, null, null, Theme.key_windowBackgroundWhiteBlackText)); arrayList.add(new ThemeDescription(bottomSheetView, 0, new Class[]{CheckBoxCell.class}, new String[]{"valueTextView"}, null, null, null, Theme.key_windowBackgroundWhiteValueText)); arrayList.add(new ThemeDescription(bottomSheetView, 0, new Class[]{CheckBoxCell.class}, Theme.dividerPaint, null, null, Theme.key_divider)); arrayList.add(new ThemeDescription(bottomSheetView, 0, new Class[]{StorageDiagramView.class}, null, null, null, Theme.key_windowBackgroundWhiteBlackText)); arrayList.add(new ThemeDescription(null, 0, new Class[]{TextCheckBoxCell.class}, new String[]{"textView"}, null, null, null, Theme.key_windowBackgroundWhiteBlackText)); arrayList.add(new ThemeDescription(null, 0, null, null, null, deldegagte, Theme.key_dialogBackground)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_blue)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_green)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_red)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_golden)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_lightblue)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_lightgreen)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_orange)); arrayList.add(new ThemeDescription(bottomSheetView, 0, null, null, null, null, Theme.key_statisticChartLine_indigo)); return arrayList; } public static class UserCell extends FrameLayout implements NotificationCenter.NotificationCenterDelegate { public DialogFileEntities dialogFileEntities; private Theme.ResourcesProvider resourcesProvider; private TextView textView; private AnimatedTextView valueTextView; private BackupImageView imageView; private boolean needDivider; private boolean canDisable; protected CheckBox2 checkBox; public UserCell(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); this.resourcesProvider = resourcesProvider; textView = new TextView(context); textView.setSingleLine(); textView.setLines(1); textView.setMaxLines(1); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); textView.setEllipsize(TextUtils.TruncateAt.END); // textView.setEllipsizeByGradient(true); textView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL); textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText, resourcesProvider)); addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 21 : 72, 0, LocaleController.isRTL ? 72 : 21, 0)); valueTextView = new AnimatedTextView(context, true, true, !LocaleController.isRTL); valueTextView.setAnimationProperties(.55f, 0, 320, CubicBezierInterpolator.EASE_OUT_QUINT); valueTextView.setTextSize(AndroidUtilities.dp(16)); valueTextView.setGravity((LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.CENTER_VERTICAL); valueTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteValueText, resourcesProvider)); addView(valueTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.TOP, LocaleController.isRTL ? 21 : 72, 0, LocaleController.isRTL ? 72 : 21, 0)); imageView = new BackupImageView(context); imageView.getAvatarDrawable().setScaleSize(.8f); addView(imageView, LayoutHelper.createFrame(38, 38, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL, 17, 0, 17, 0)); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), AndroidUtilities.dp(50) + (needDivider ? 1 : 0)); int availableWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - AndroidUtilities.dp(34); int width = availableWidth / 2; if (imageView.getVisibility() == VISIBLE) { imageView.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(38), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(38), MeasureSpec.EXACTLY)); } if (valueTextView.getVisibility() == VISIBLE) { valueTextView.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY)); width = availableWidth - valueTextView.getMeasuredWidth() - AndroidUtilities.dp(8); } else { width = availableWidth; } int padding = valueTextView.getMeasuredWidth() + AndroidUtilities.dp(12); if (LocaleController.isRTL) { ((MarginLayoutParams) textView.getLayoutParams()).leftMargin = padding; } else { ((MarginLayoutParams) textView.getLayoutParams()).rightMargin = padding; } textView.measure(MeasureSpec.makeMeasureSpec(width - padding, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY)); if (checkBox != null) { checkBox.measure( MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(24), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(24), MeasureSpec.EXACTLY) ); } } public BackupImageView getImageView() { return imageView; } public TextView getTextView() { return textView; } public void setCanDisable(boolean value) { canDisable = value; } public AnimatedTextView getValueTextView() { return valueTextView; } public void setTextColor(int color) { textView.setTextColor(color); } public void setTextValueColor(int color) { valueTextView.setTextColor(color); } public void setText(CharSequence text, boolean divider) { text = Emoji.replaceEmoji(text, textView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(16), false); textView.setText(text); valueTextView.setVisibility(INVISIBLE); needDivider = divider; setWillNotDraw(!divider); } public void setTextAndValue(CharSequence text, CharSequence value, boolean divider) { setTextAndValue(text, value, false, divider); } public void setTextAndValue(CharSequence text, CharSequence value, boolean animated, boolean divider) { text = Emoji.replaceEmoji(text, textView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(16), false); textView.setText(text); if (value != null) { valueTextView.setText(value, animated); valueTextView.setVisibility(VISIBLE); } else { valueTextView.setVisibility(INVISIBLE); } needDivider = divider; setWillNotDraw(!divider); requestLayout(); } public void setEnabled(boolean value, ArrayList<Animator> animators) { setEnabled(value); if (animators != null) { animators.add(ObjectAnimator.ofFloat(textView, "alpha", value ? 1.0f : 0.5f)); if (valueTextView.getVisibility() == VISIBLE) { animators.add(ObjectAnimator.ofFloat(valueTextView, "alpha", value ? 1.0f : 0.5f)); } } else { textView.setAlpha(value ? 1.0f : 0.5f); if (valueTextView.getVisibility() == VISIBLE) { valueTextView.setAlpha(value ? 1.0f : 0.5f); } } } @Override public void setEnabled(boolean value) { super.setEnabled(value); textView.setAlpha(value || !canDisable ? 1.0f : 0.5f); if (valueTextView.getVisibility() == VISIBLE) { valueTextView.setAlpha(value || !canDisable ? 1.0f : 0.5f); } } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); if (needDivider) { canvas.drawLine(LocaleController.isRTL ? 0 : AndroidUtilities.dp(72), getMeasuredHeight() - 1, getMeasuredWidth() - (LocaleController.isRTL ? AndroidUtilities.dp(72) : 0), getMeasuredHeight() - 1, Theme.dividerPaint); } } @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setText(textView.getText() + (valueTextView != null && valueTextView.getVisibility() == View.VISIBLE ? "\n" + valueTextView.getText() : "")); info.setEnabled(isEnabled()); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.emojiLoaded); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.emojiLoaded); } @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.emojiLoaded) { if (textView != null) { textView.invalidate(); } } } public void setChecked(boolean checked, boolean animated) { if (checkBox == null && !checked) { return; } if (checkBox == null) { checkBox = new CheckBox2(getContext(), 21, resourcesProvider); checkBox.setColor(-1, Theme.key_windowBackgroundWhite, Theme.key_checkboxCheck); checkBox.setDrawUnchecked(false); checkBox.setDrawBackgroundAsArc(3); addView(checkBox, LayoutHelper.createFrame(24, 24, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 38, 25, 38, 0)); } checkBox.setChecked(checked, animated); } } @Override public void onRequestPermissionsResultFragment(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == 4) { boolean allGranted = true; for (int a = 0; a < grantResults.length; a++) { if (grantResults[a] != PackageManager.PERMISSION_GRANTED) { allGranted = false; break; } } if (allGranted && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && FilesMigrationService.filesMigrationBottomSheet != null) { FilesMigrationService.filesMigrationBottomSheet.migrateOldFolder(); } } } public static class DialogFileEntities { public long dialogId; int filesCount; long totalSize; public final SparseArray<FileEntities> entitiesByType = new SparseArray<>(); public DialogFileEntities(long dialogId) { this.dialogId = dialogId; } public void addFile(CacheModel.FileInfo file, int type) { FileEntities entities = entitiesByType.get(type, null); if (entities == null) { entities = new FileEntities(); entitiesByType.put(type, entities); } entities.count++; long fileSize = file.size; entities.totalSize += fileSize; totalSize += fileSize; filesCount++; entities.files.add(file); } public void merge(DialogFileEntities dialogEntities) { for (int i = 0; i < dialogEntities.entitiesByType.size(); i++) { int type = dialogEntities.entitiesByType.keyAt(i); FileEntities entitesToMerge = dialogEntities.entitiesByType.valueAt(i); FileEntities entities = entitiesByType.get(type, null); if (entities == null) { entities = new FileEntities(); entitiesByType.put(type, entities); } entities.count += entitesToMerge.count; entities.totalSize += entitesToMerge.totalSize; totalSize += entitesToMerge.totalSize; entities.files.addAll(entitesToMerge.files); } filesCount += dialogEntities.filesCount; } public void removeFile(CacheModel.FileInfo fileInfo) { FileEntities entities = entitiesByType.get(fileInfo.type, null); if (entities == null) { return; } if (entities.files.remove(fileInfo)) { entities.count--; entities.totalSize -= fileInfo.size; totalSize -= fileInfo.size; filesCount--; } } public boolean isEmpty() { return totalSize <= 0; } public CacheModel createCacheModel() { CacheModel cacheModel = new CacheModel(true); if (entitiesByType.get(TYPE_PHOTOS) != null) { cacheModel.media.addAll(entitiesByType.get(TYPE_PHOTOS).files); } if (entitiesByType.get(TYPE_VIDEOS) != null) { cacheModel.media.addAll(entitiesByType.get(TYPE_VIDEOS).files); } if (entitiesByType.get(TYPE_DOCUMENTS) != null) { cacheModel.documents.addAll(entitiesByType.get(TYPE_DOCUMENTS).files); } if (entitiesByType.get(TYPE_MUSIC) != null) { cacheModel.music.addAll(entitiesByType.get(TYPE_MUSIC).files); } if (entitiesByType.get(TYPE_VOICE) != null) { cacheModel.voice.addAll(entitiesByType.get(TYPE_VOICE).files); } cacheModel.selectAllFiles(); cacheModel.sortBySize(); return cacheModel; } } public static class FileEntities { public long totalSize; public int count; public ArrayList<CacheModel.FileInfo> files = new ArrayList<>(); } public static class ItemInner extends AdapterWithDiffUtils.Item { int headerTopMargin = 15; int headerBottomMargin = 0; int keepMediaType = -1; CharSequence headerName; String text; DialogFileEntities entities; public int index; public long size; int colorKey; public boolean pad; boolean last; public ItemInner(int viewType, String headerName, DialogFileEntities dialogFileEntities) { super(viewType, true); this.headerName = headerName; this.entities = dialogFileEntities; } public ItemInner(int viewType, int keepMediaType) { super(viewType, true); this.keepMediaType = keepMediaType; } public ItemInner(int viewType, String headerName, int headerTopMargin, int headerBottomMargin, DialogFileEntities dialogFileEntities) { super(viewType, true); this.headerName = headerName; this.headerTopMargin = headerTopMargin; this.headerBottomMargin = headerBottomMargin; this.entities = dialogFileEntities; } private ItemInner(int viewType) { super(viewType, true); } public static ItemInner asCheckBox(CharSequence text, int index, long size, int colorKey) { return asCheckBox(text, index, size, colorKey, false); } public static ItemInner asCheckBox(CharSequence text, int index, long size, int colorKey, boolean last) { ItemInner item = new ItemInner(VIEW_TYPE_SECTION); item.index = index; item.headerName = text; item.size = size; item.colorKey = colorKey; item.last = last; return item; } public static ItemInner asInfo(String text) { ItemInner item = new ItemInner(VIEW_TYPE_INFO); item.text = text; return item; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ItemInner itemInner = (ItemInner) o; if (viewType == itemInner.viewType) { if (viewType == VIEW_TYPE_CHART || viewType == VIEW_TYPE_CHART_HEADER) { return true; } if (viewType == VIEW_TYPE_CHAT && entities != null && itemInner.entities != null) { return entities.dialogId == itemInner.entities.dialogId; } if (viewType == VIEW_TYPE_CACHE_VIEW_PAGER || viewType == VIEW_TYPE_CHOOSER || viewType == VIEW_TYPE_STORAGE || viewType == VIEW_TYPE_TEXT_SETTINGS || viewType == VIEW_TYPE_CLEAR_CACHE_BUTTON) { return true; } if (viewType == VIEW_TYPE_HEADER) { return Objects.equals(headerName, itemInner.headerName); } if (viewType == VIEW_TYPE_INFO) { return Objects.equals(text, itemInner.text); } if (viewType == VIEW_TYPE_SECTION) { return index == itemInner.index && size == itemInner.size; } if (viewType == VIEW_TYPE_KEEP_MEDIA_CELL) { return keepMediaType == itemInner.keepMediaType; } return false; } return false; } } AnimatedTextView selectedDialogsCountTextView; @Override public boolean isSwipeBackEnabled(MotionEvent event) { if (cachedMediaLayout != null && event != null) { cachedMediaLayout.getHitRect(AndroidUtilities.rectTmp2); if (!AndroidUtilities.rectTmp2.contains((int) event.getX(), (int) event.getY() - actionBar.getMeasuredHeight())) { return true; } else { return cachedMediaLayout.viewPagerFixed.isCurrentTabFirst(); } } return true; } @Override public boolean onBackPressed() { if (cacheModel != null && !cacheModel.selectedFiles.isEmpty()) { cacheModel.clearSelection(); if (cachedMediaLayout != null) { cachedMediaLayout.showActionMode(false); cachedMediaLayout.updateVisibleRows(); } return false; } return super.onBackPressed(); } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/ui/CacheControlActivity.java
41,706
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Grishka, 2013-2016. */ package org.telegram.messenger.voip; import android.Manifest; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.app.KeyguardManager; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothHeadset; import android.bluetooth.BluetoothProfile; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Icon; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.media.AudioAttributes; import android.media.AudioDeviceCallback; import android.media.AudioDeviceInfo; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioTrack; import android.media.MediaPlayer; import android.media.MediaRouter; import android.media.RingtoneManager; import android.media.SoundPool; import android.media.audiofx.AcousticEchoCanceler; import android.media.audiofx.NoiseSuppressor; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.PowerManager; import android.os.SystemClock; import android.os.Vibrator; import android.telecom.CallAudioState; import android.telecom.Connection; import android.telecom.DisconnectCause; import android.telecom.PhoneAccount; import android.telecom.PhoneAccountHandle; import android.telecom.TelecomManager; import android.telephony.TelephonyManager; import android.text.SpannableString; import android.text.TextUtils; import android.text.style.ForegroundColorSpan; import android.util.Log; import android.util.LruCache; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.widget.RemoteViews; import android.widget.Toast; import androidx.annotation.Nullable; import org.json.JSONObject; import org.telegram.messenger.AccountInstance; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.BuildVars; import org.telegram.messenger.ChatObject; import org.telegram.messenger.ContactsController; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.ImageLoader; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MediaController; import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesStorage; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.NotificationsController; import org.telegram.messenger.R; import org.telegram.messenger.SharedConfig; import org.telegram.messenger.StatsController; import org.telegram.messenger.UserConfig; import org.telegram.messenger.UserObject; import org.telegram.messenger.Utilities; import org.telegram.messenger.XiaomiUtilities; import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.BottomSheet; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.Components.AvatarDrawable; import org.telegram.ui.Components.JoinCallAlert; import org.telegram.ui.Components.voip.VoIPHelper; import org.telegram.ui.LaunchActivity; import org.telegram.ui.VoIPFeedbackActivity; import org.telegram.ui.VoIPFragment; import org.telegram.ui.VoIPPermissionActivity; import org.webrtc.VideoFrame; import org.webrtc.VideoSink; import org.webrtc.voiceengine.WebRtcAudioTrack; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Set; @SuppressLint("NewApi") public class VoIPService extends Service implements SensorEventListener, AudioManager.OnAudioFocusChangeListener, VoIPController.ConnectionStateListener, NotificationCenter.NotificationCenterDelegate { public static final int CALL_MIN_LAYER = 65; public static final int STATE_HANGING_UP = 10; public static final int STATE_EXCHANGING_KEYS = 12; public static final int STATE_WAITING = 13; public static final int STATE_REQUESTING = 14; public static final int STATE_WAITING_INCOMING = 15; public static final int STATE_RINGING = 16; public static final int STATE_BUSY = 17; public static final int STATE_WAIT_INIT = Instance.STATE_WAIT_INIT; public static final int STATE_WAIT_INIT_ACK = Instance.STATE_WAIT_INIT_ACK; public static final int STATE_ESTABLISHED = Instance.STATE_ESTABLISHED; public static final int STATE_FAILED = Instance.STATE_FAILED; public static final int STATE_RECONNECTING = Instance.STATE_RECONNECTING; public static final int STATE_CREATING = 6; public static final int STATE_ENDED = 11; public static final String ACTION_HEADSET_PLUG = "android.intent.action.HEADSET_PLUG"; private static final int ID_ONGOING_CALL_NOTIFICATION = 201; private static final int ID_INCOMING_CALL_NOTIFICATION = 202; public static final int QUALITY_SMALL = 0; public static final int QUALITY_MEDIUM = 1; public static final int QUALITY_FULL = 2; public static final int CAPTURE_DEVICE_CAMERA = 0; public static final int CAPTURE_DEVICE_SCREEN = 1; public static final int DISCARD_REASON_HANGUP = 1; public static final int DISCARD_REASON_DISCONNECT = 2; public static final int DISCARD_REASON_MISSED = 3; public static final int DISCARD_REASON_LINE_BUSY = 4; public static final int AUDIO_ROUTE_EARPIECE = 0; public static final int AUDIO_ROUTE_SPEAKER = 1; public static final int AUDIO_ROUTE_BLUETOOTH = 2; private static final boolean USE_CONNECTION_SERVICE = isDeviceCompatibleWithConnectionServiceAPI(); private int currentAccount = -1; private static final int PROXIMITY_SCREEN_OFF_WAKE_LOCK = 32; private static VoIPService sharedInstance; private static Runnable setModeRunnable; private static final Object sync = new Object(); private NetworkInfo lastNetInfo; private int currentState = 0; private boolean wasConnected; private boolean reconnectScreenCapture; private TLRPC.Chat chat; private boolean isVideoAvailable; private boolean notificationsDisabled; private boolean switchingCamera; private boolean isFrontFaceCamera = true; private boolean isPrivateScreencast; private String lastError; private PowerManager.WakeLock proximityWakelock; private PowerManager.WakeLock cpuWakelock; private boolean isProximityNear; private boolean isHeadsetPlugged; private int previousAudioOutput = -1; private ArrayList<StateListener> stateListeners = new ArrayList<>(); private MediaPlayer ringtonePlayer; private Vibrator vibrator; private SoundPool soundPool; private int spRingbackID; private int spFailedID; private int spEndId; private int spVoiceChatEndId; private int spVoiceChatStartId; private int spVoiceChatConnecting; private int spBusyId; private int spConnectingId; private int spPlayId; private int spStartRecordId; private int spAllowTalkId; private boolean needPlayEndSound; private boolean hasAudioFocus; private boolean micMute; private boolean unmutedByHold; private BluetoothAdapter btAdapter; private Instance.TrafficStats prevTrafficStats; private boolean isBtHeadsetConnected; private Runnable updateNotificationRunnable; private Runnable onDestroyRunnable; private Runnable switchingStreamTimeoutRunnable; private boolean playedConnectedSound; private boolean switchingStream; private boolean switchingAccount; public TLRPC.PhoneCall privateCall; public ChatObject.Call groupCall; public boolean currentGroupModeStreaming; private boolean createGroupCall; private int scheduleDate; private TLRPC.InputPeer groupCallPeer; public boolean hasFewPeers; private String joinHash; private int remoteVideoState = Instance.VIDEO_STATE_INACTIVE; private TLRPC.TL_dataJSON myParams; private int[] mySource = new int[2]; private NativeInstance[] tgVoip = new NativeInstance[2]; private long[] captureDevice = new long[2]; private boolean[] destroyCaptureDevice = {true, true}; private int[] videoState = {Instance.VIDEO_STATE_INACTIVE, Instance.VIDEO_STATE_INACTIVE}; private long callStartTime; private boolean playingSound; private boolean isOutgoing; public boolean videoCall; private Runnable timeoutRunnable; private Boolean mHasEarpiece; private boolean wasEstablished; private int signalBarCount; private int remoteAudioState = Instance.AUDIO_STATE_ACTIVE; private boolean audioConfigured; private int audioRouteToSet = AUDIO_ROUTE_BLUETOOTH; private boolean speakerphoneStateToSet; private CallConnection systemCallConnection; private int callDiscardReason; private boolean bluetoothScoActive; private boolean bluetoothScoConnecting; private boolean needSwitchToBluetoothAfterScoActivates; private boolean didDeleteConnectionServiceContact; private Runnable connectingSoundRunnable; public String currentBluetoothDeviceName; public final SharedUIParams sharedUIParams = new SharedUIParams(); private TLRPC.User user; private int callReqId; private byte[] g_a; private byte[] a_or_b; private byte[] g_a_hash; private byte[] authKey; private long keyFingerprint; private boolean forceRating; public static TLRPC.PhoneCall callIShouldHavePutIntoIntent; public static NativeInstance.AudioLevelsCallback audioLevelsCallback; private boolean needSendDebugLog; private boolean needRateCall; private long lastTypingTimeSend; private boolean endCallAfterRequest; private ArrayList<TLRPC.PhoneCall> pendingUpdates = new ArrayList<>(); private Runnable delayedStartOutgoingCall; private boolean startedRinging; private int classGuid; private HashMap<String, Integer> currentStreamRequestTimestamp = new HashMap<>(); public boolean micSwitching; private Runnable afterSoundRunnable = new Runnable() { @Override public void run() { AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); am.abandonAudioFocus(VoIPService.this); am.unregisterMediaButtonEventReceiver(new ComponentName(VoIPService.this, VoIPMediaButtonReceiver.class)); if (audioDeviceCallback != null) { am.unregisterAudioDeviceCallback(audioDeviceCallback); } if (!USE_CONNECTION_SERVICE && sharedInstance == null) { if (isBtHeadsetConnected) { am.stopBluetoothSco(); am.setBluetoothScoOn(false); bluetoothScoActive = false; bluetoothScoConnecting = false; } am.setSpeakerphoneOn(false); } Utilities.globalQueue.postRunnable(() -> soundPool.release()); Utilities.globalQueue.postRunnable(setModeRunnable = () -> { synchronized (sync) { if (setModeRunnable == null) { return; } setModeRunnable = null; } try { am.setMode(AudioManager.MODE_NORMAL); } catch (SecurityException x) { if (BuildVars.LOGS_ENABLED) { FileLog.e("Error setting audio more to normal", x); } } }); } }; boolean fetchingBluetoothDeviceName; private BluetoothProfile.ServiceListener serviceListener = new BluetoothProfile.ServiceListener() { @Override public void onServiceDisconnected(int profile) { } @Override public void onServiceConnected(int profile, BluetoothProfile proxy) { try { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) { for (BluetoothDevice device : proxy.getConnectedDevices()) { if (proxy.getConnectionState(device) != BluetoothProfile.STATE_CONNECTED) { continue; } currentBluetoothDeviceName = device.getName(); break; } } BluetoothAdapter.getDefaultAdapter().closeProfileProxy(profile, proxy); fetchingBluetoothDeviceName = false; } catch (Throwable e) { FileLog.e(e); } } }; private AudioDeviceCallback audioDeviceCallback; private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (ACTION_HEADSET_PLUG.equals(intent.getAction())) { isHeadsetPlugged = intent.getIntExtra("state", 0) == 1; if (isHeadsetPlugged && proximityWakelock != null && proximityWakelock.isHeld()) { proximityWakelock.release(); } if (isHeadsetPlugged) { AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); if (am.isSpeakerphoneOn()) { previousAudioOutput = 0; } else if (am.isBluetoothScoOn()) { previousAudioOutput = 2; } else { previousAudioOutput = 1; } setAudioOutput(1); } else { if (previousAudioOutput >= 0) { setAudioOutput(previousAudioOutput); previousAudioOutput = -1; } } isProximityNear = false; updateOutputGainControlState(); } else if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) { updateNetworkType(); } else if (BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED.equals(intent.getAction())) { if (BuildVars.LOGS_ENABLED) { FileLog.e("bt headset state = " + intent.getIntExtra(BluetoothProfile.EXTRA_STATE, 0)); } updateBluetoothHeadsetState(intent.getIntExtra(BluetoothProfile.EXTRA_STATE, BluetoothProfile.STATE_DISCONNECTED) == BluetoothProfile.STATE_CONNECTED); } else if (AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED.equals(intent.getAction())) { int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, AudioManager.SCO_AUDIO_STATE_DISCONNECTED); if (BuildVars.LOGS_ENABLED) { FileLog.e("Bluetooth SCO state updated: " + state); } if (state == AudioManager.SCO_AUDIO_STATE_DISCONNECTED && isBtHeadsetConnected) { if (!btAdapter.isEnabled() || btAdapter.getProfileConnectionState(BluetoothProfile.HEADSET) != BluetoothProfile.STATE_CONNECTED) { updateBluetoothHeadsetState(false); return; } } bluetoothScoConnecting = state == AudioManager.SCO_AUDIO_STATE_CONNECTING; bluetoothScoActive = state == AudioManager.SCO_AUDIO_STATE_CONNECTED; if (bluetoothScoActive) { fetchBluetoothDeviceName(); if (needSwitchToBluetoothAfterScoActivates) { needSwitchToBluetoothAfterScoActivates = false; AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); am.setSpeakerphoneOn(false); am.setBluetoothScoOn(true); } } for (VoIPService.StateListener l : stateListeners) { l.onAudioSettingsChanged(); } } else if (TelephonyManager.ACTION_PHONE_STATE_CHANGED.equals(intent.getAction())) { String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE); if (TelephonyManager.EXTRA_STATE_OFFHOOK.equals(state)) { hangUp(); } } else if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) { for (int i = 0; i< stateListeners.size(); i++) { stateListeners.get(i).onScreenOnChange(true); } } else if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) { for (int i = 0; i< stateListeners.size(); i++) { stateListeners.get(i).onScreenOnChange(false); } } } }; public boolean isFrontFaceCamera() { return isFrontFaceCamera; } public boolean isScreencast() { return isPrivateScreencast; } public void setMicMute(boolean mute, boolean hold, boolean send) { if (micMute == mute || micSwitching) { return; } micMute = mute; if (groupCall != null) { if (!send) { TLRPC.TL_groupCallParticipant self = groupCall.participants.get(getSelfId()); if (self != null && self.muted && !self.can_self_unmute) { send = true; } } if (send) { editCallMember(UserConfig.getInstance(currentAccount).getCurrentUser(), mute, null, null, null, null); Utilities.globalQueue.postRunnable(updateNotificationRunnable = () -> { if (updateNotificationRunnable == null) { return; } updateNotificationRunnable = null; showNotification(chat.title, getRoundAvatarBitmap(chat)); }); } } unmutedByHold = !micMute && hold; if (tgVoip[CAPTURE_DEVICE_CAMERA] != null) { tgVoip[CAPTURE_DEVICE_CAMERA].setMuteMicrophone(mute); } for (StateListener l : stateListeners) { l.onAudioSettingsChanged(); } } public boolean mutedByAdmin() { ChatObject.Call call = groupCall; if (call != null) { long selfId = getSelfId(); TLRPC.TL_groupCallParticipant participant = call.participants.get(selfId); if (participant != null && !participant.can_self_unmute && participant.muted && !ChatObject.canManageCalls(chat)) { return true; } } return false; } private final HashMap<String, TLRPC.TL_groupCallParticipant> waitingFrameParticipant = new HashMap<>(); private final LruCache<String, ProxyVideoSink> proxyVideoSinkLruCache = new LruCache<String, ProxyVideoSink>(6) { @Override protected void entryRemoved(boolean evicted, String key, ProxyVideoSink oldValue, ProxyVideoSink newValue) { super.entryRemoved(evicted, key, oldValue, newValue); tgVoip[CAPTURE_DEVICE_CAMERA].removeIncomingVideoOutput(oldValue.nativeInstance); } }; public boolean hasVideoCapturer() { return captureDevice[CAPTURE_DEVICE_CAMERA] != 0; } public void checkVideoFrame(TLRPC.TL_groupCallParticipant participant, boolean screencast) { String endpointId = screencast ? participant.presentationEndpoint : participant.videoEndpoint; if (endpointId == null) { return; } if ((screencast && participant.hasPresentationFrame != ChatObject.VIDEO_FRAME_NO_FRAME) || (!screencast && participant.hasCameraFrame != ChatObject.VIDEO_FRAME_NO_FRAME)) { return; } if (proxyVideoSinkLruCache.get(endpointId) != null || (remoteSinks.get(endpointId) != null && waitingFrameParticipant.get(endpointId) == null)) { if (screencast) { participant.hasPresentationFrame = ChatObject.VIDEO_FRAME_HAS_FRAME; } else { participant.hasCameraFrame = ChatObject.VIDEO_FRAME_HAS_FRAME; } return; } if (waitingFrameParticipant.containsKey(endpointId)) { waitingFrameParticipant.put(endpointId, participant); if (screencast) { participant.hasPresentationFrame = ChatObject.VIDEO_FRAME_REQUESTING; } else { participant.hasCameraFrame = ChatObject.VIDEO_FRAME_REQUESTING; } return; } if (screencast) { participant.hasPresentationFrame = ChatObject.VIDEO_FRAME_REQUESTING; } else { participant.hasCameraFrame = ChatObject.VIDEO_FRAME_REQUESTING; } waitingFrameParticipant.put(endpointId, participant); addRemoteSink(participant, screencast, new VideoSink() { @Override public void onFrame(VideoFrame frame) { VideoSink thisSink = this; if (frame != null && frame.getBuffer().getHeight() != 0 && frame.getBuffer().getWidth() != 0) { AndroidUtilities.runOnUIThread(() -> { TLRPC.TL_groupCallParticipant currentParticipant = waitingFrameParticipant.remove(endpointId); ProxyVideoSink proxyVideoSink = remoteSinks.get(endpointId); if (proxyVideoSink != null && proxyVideoSink.target == thisSink) { proxyVideoSinkLruCache.put(endpointId, proxyVideoSink); remoteSinks.remove(endpointId); proxyVideoSink.setTarget(null); } if (currentParticipant != null) { if (screencast) { currentParticipant.hasPresentationFrame = ChatObject.VIDEO_FRAME_HAS_FRAME; } else { currentParticipant.hasCameraFrame = ChatObject.VIDEO_FRAME_HAS_FRAME; } } if (groupCall != null) { groupCall.updateVisibleParticipants(); } }); } } }, null); } public void clearRemoteSinks() { proxyVideoSinkLruCache.evictAll(); } public void setAudioRoute(int route) { if (route == AUDIO_ROUTE_SPEAKER) { setAudioOutput(0); } else if (route == AUDIO_ROUTE_EARPIECE) { setAudioOutput(1); } else if (route == AUDIO_ROUTE_BLUETOOTH) { setAudioOutput(2); } } public static class ProxyVideoSink implements VideoSink { private VideoSink target; private VideoSink background; private long nativeInstance; @Override synchronized public void onFrame(VideoFrame frame) { if (target != null) { target.onFrame(frame); } if (background != null) { background.onFrame(frame); } } synchronized public void setTarget(VideoSink newTarget) { if (target != newTarget) { if (target != null) { target.setParentSink(null); } target = newTarget; if (target != null) { target.setParentSink(this); } } } synchronized public void setBackground(VideoSink newBackground) { if (background != null) { background.setParentSink(null); } background = newBackground; if (background != null) { background.setParentSink(this); } } synchronized public void removeTarget(VideoSink target) { if (this.target == target) { this.target = null; } } synchronized public void removeBackground(VideoSink background) { if (this.background == background) { this.background = null; } } synchronized public void swap() { if (target != null && background != null) { target = background; background = null; } } } private ProxyVideoSink[] localSink = new ProxyVideoSink[2]; private ProxyVideoSink[] remoteSink = new ProxyVideoSink[2]; private ProxyVideoSink[] currentBackgroundSink = new ProxyVideoSink[2]; private String[] currentBackgroundEndpointId = new String[2]; private HashMap<String, ProxyVideoSink> remoteSinks = new HashMap<>(); @Nullable @Override public IBinder onBind(Intent intent) { return null; } @SuppressLint({"MissingPermission", "InlinedApi"}) @Override public int onStartCommand(Intent intent, int flags, int startId) { if (sharedInstance != null) { if (BuildVars.LOGS_ENABLED) { FileLog.e("Tried to start the VoIP service when it's already started"); } return START_NOT_STICKY; } currentAccount = intent.getIntExtra("account", -1); if (currentAccount == -1) { throw new IllegalStateException("No account specified when starting VoIP service"); } classGuid = ConnectionsManager.generateClassGuid(); long userID = intent.getLongExtra("user_id", 0); long chatID = intent.getLongExtra("chat_id", 0); createGroupCall = intent.getBooleanExtra("createGroupCall", false); hasFewPeers = intent.getBooleanExtra("hasFewPeers", false); joinHash = intent.getStringExtra("hash"); long peerChannelId = intent.getLongExtra("peerChannelId", 0); long peerChatId = intent.getLongExtra("peerChatId", 0); long peerUserId = intent.getLongExtra("peerUserId", 0); if (peerChatId != 0) { groupCallPeer = new TLRPC.TL_inputPeerChat(); groupCallPeer.chat_id = peerChatId; groupCallPeer.access_hash = intent.getLongExtra("peerAccessHash", 0); } else if (peerChannelId != 0) { groupCallPeer = new TLRPC.TL_inputPeerChannel(); groupCallPeer.channel_id = peerChannelId; groupCallPeer.access_hash = intent.getLongExtra("peerAccessHash", 0); } else if (peerUserId != 0) { groupCallPeer = new TLRPC.TL_inputPeerUser(); groupCallPeer.user_id = peerUserId; groupCallPeer.access_hash = intent.getLongExtra("peerAccessHash", 0); } scheduleDate = intent.getIntExtra("scheduleDate", 0); isOutgoing = intent.getBooleanExtra("is_outgoing", false); videoCall = intent.getBooleanExtra("video_call", false); isVideoAvailable = intent.getBooleanExtra("can_video_call", false); notificationsDisabled = intent.getBooleanExtra("notifications_disabled", false); if (userID != 0) { user = MessagesController.getInstance(currentAccount).getUser(userID); } if (chatID != 0) { chat = MessagesController.getInstance(currentAccount).getChat(chatID); if (ChatObject.isChannel(chat)) { MessagesController.getInstance(currentAccount).startShortPoll(chat, classGuid, false); } } loadResources(); for (int a = 0; a < localSink.length; a++) { localSink[a] = new ProxyVideoSink(); remoteSink[a] = new ProxyVideoSink(); } try { AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); isHeadsetPlugged = am.isWiredHeadsetOn(); } catch (Exception e) { FileLog.e(e); } if (chat != null && !createGroupCall) { ChatObject.Call call = MessagesController.getInstance(currentAccount).getGroupCall(chat.id, false); if (call == null) { FileLog.w("VoIPService: trying to open group call without call " + chat.id); stopSelf(); return START_NOT_STICKY; } } if (videoCall) { if (Build.VERSION.SDK_INT < 23 || checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { captureDevice[CAPTURE_DEVICE_CAMERA] = NativeInstance.createVideoCapturer(localSink[CAPTURE_DEVICE_CAMERA], isFrontFaceCamera ? 1 : 0); if (chatID != 0) { videoState[CAPTURE_DEVICE_CAMERA] = Instance.VIDEO_STATE_PAUSED; } else { videoState[CAPTURE_DEVICE_CAMERA] = Instance.VIDEO_STATE_ACTIVE; } } else { videoState[CAPTURE_DEVICE_CAMERA] = Instance.VIDEO_STATE_PAUSED; } if (!isBtHeadsetConnected && !isHeadsetPlugged) { setAudioOutput(0); } } if (user == null && chat == null) { if (BuildVars.LOGS_ENABLED) { FileLog.w("VoIPService: user == null AND chat == null"); } stopSelf(); return START_NOT_STICKY; } sharedInstance = this; synchronized (sync) { if (setModeRunnable != null) { Utilities.globalQueue.cancelRunnable(setModeRunnable); setModeRunnable = null; } } if (isOutgoing) { if (user != null) { dispatchStateChanged(STATE_REQUESTING); if (USE_CONNECTION_SERVICE) { TelecomManager tm = (TelecomManager) getSystemService(TELECOM_SERVICE); Bundle extras = new Bundle(); Bundle myExtras = new Bundle(); extras.putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, addAccountToTelecomManager()); myExtras.putInt("call_type", 1); extras.putBundle(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, myExtras); ContactsController.getInstance(currentAccount).createOrUpdateConnectionServiceContact(user.id, user.first_name, user.last_name); tm.placeCall(Uri.fromParts("tel", "+99084" + user.id, null), extras); } else { delayedStartOutgoingCall = () -> { delayedStartOutgoingCall = null; startOutgoingCall(); }; AndroidUtilities.runOnUIThread(delayedStartOutgoingCall, 2000); } } else { micMute = true; startGroupCall(0, null, false); if (!isBtHeadsetConnected && !isHeadsetPlugged) { setAudioOutput(0); } } if (intent.getBooleanExtra("start_incall_activity", false)) { Intent intent1 = new Intent(this, LaunchActivity.class).setAction(user != null ? "voip" : "voip_chat").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (chat != null) { intent1.putExtra("currentAccount", currentAccount); } startActivity(intent1); } } else { NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.closeInCallActivity); privateCall = callIShouldHavePutIntoIntent; videoCall = privateCall != null && privateCall.video; if (videoCall) { isVideoAvailable = true; } if (videoCall && !isBtHeadsetConnected && !isHeadsetPlugged) { setAudioOutput(0); } callIShouldHavePutIntoIntent = null; if (USE_CONNECTION_SERVICE) { acknowledgeCall(false); showNotification(); } else { acknowledgeCall(true); } } initializeAccountRelatedThings(); AndroidUtilities.runOnUIThread(() -> NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.voipServiceCreated)); return START_NOT_STICKY; } public static boolean hasRtmpStream() { return getSharedInstance() != null && getSharedInstance().groupCall != null && getSharedInstance().groupCall.call.rtmp_stream; } public static VoIPService getSharedInstance() { return sharedInstance; } public TLRPC.User getUser() { return user; } public TLRPC.Chat getChat() { return chat; } public void setNoiseSupressionEnabled(boolean enabled) { if (tgVoip[CAPTURE_DEVICE_CAMERA] == null) { return; } tgVoip[CAPTURE_DEVICE_CAMERA].setNoiseSuppressionEnabled(enabled); } public void setGroupCallHash(String hash) { if (!currentGroupModeStreaming || TextUtils.isEmpty(hash) || hash.equals(joinHash)) { return; } joinHash = hash; createGroupInstance(CAPTURE_DEVICE_CAMERA, false); } public long getCallerId() { if (user != null) { return user.id; } else { return -chat.id; } } public void hangUp(int discard, Runnable onDone) { declineIncomingCall(currentState == STATE_RINGING || (currentState == STATE_WAITING && isOutgoing) ? DISCARD_REASON_MISSED : DISCARD_REASON_HANGUP, onDone); if (groupCall != null) { if (discard == 2) { return; } if (discard == 1) { TLRPC.ChatFull chatFull = MessagesController.getInstance(currentAccount).getChatFull(chat.id); if (chatFull != null) { chatFull.flags &=~ 2097152; chatFull.call = null; NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.groupCallUpdated, chat.id, groupCall.call.id, false); } TLRPC.TL_phone_discardGroupCall req = new TLRPC.TL_phone_discardGroupCall(); req.call = groupCall.getInputGroupCall(); ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> { if (response instanceof TLRPC.TL_updates) { TLRPC.TL_updates updates = (TLRPC.TL_updates) response; MessagesController.getInstance(currentAccount).processUpdates(updates, false); } }); } else { TLRPC.TL_phone_leaveGroupCall req = new TLRPC.TL_phone_leaveGroupCall(); req.call = groupCall.getInputGroupCall(); req.source = mySource[CAPTURE_DEVICE_CAMERA]; ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> { if (response instanceof TLRPC.TL_updates) { TLRPC.TL_updates updates = (TLRPC.TL_updates) response; MessagesController.getInstance(currentAccount).processUpdates(updates, false); } }); } } } private void startOutgoingCall() { if (USE_CONNECTION_SERVICE && systemCallConnection != null) { systemCallConnection.setDialing(); } configureDeviceForCall(); showNotification(); startConnectingSound(); dispatchStateChanged(STATE_REQUESTING); AndroidUtilities.runOnUIThread(() -> NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.didStartedCall)); final byte[] salt = new byte[256]; Utilities.random.nextBytes(salt); TLRPC.TL_messages_getDhConfig req = new TLRPC.TL_messages_getDhConfig(); req.random_length = 256; final MessagesStorage messagesStorage = MessagesStorage.getInstance(currentAccount); req.version = messagesStorage.getLastSecretVersion(); callReqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> { callReqId = 0; if (endCallAfterRequest) { callEnded(); return; } if (error == null) { TLRPC.messages_DhConfig res = (TLRPC.messages_DhConfig) response; if (response instanceof TLRPC.TL_messages_dhConfig) { if (!Utilities.isGoodPrime(res.p, res.g)) { callFailed(); return; } messagesStorage.setSecretPBytes(res.p); messagesStorage.setSecretG(res.g); messagesStorage.setLastSecretVersion(res.version); messagesStorage.saveSecretParams(messagesStorage.getLastSecretVersion(), messagesStorage.getSecretG(), messagesStorage.getSecretPBytes()); } final byte[] salt1 = new byte[256]; for (int a = 0; a < 256; a++) { salt1[a] = (byte) ((byte) (Utilities.random.nextDouble() * 256) ^ res.random[a]); } BigInteger i_g_a = BigInteger.valueOf(messagesStorage.getSecretG()); i_g_a = i_g_a.modPow(new BigInteger(1, salt1), new BigInteger(1, messagesStorage.getSecretPBytes())); byte[] g_a = i_g_a.toByteArray(); if (g_a.length > 256) { byte[] correctedAuth = new byte[256]; System.arraycopy(g_a, 1, correctedAuth, 0, 256); g_a = correctedAuth; } TLRPC.TL_phone_requestCall reqCall = new TLRPC.TL_phone_requestCall(); reqCall.user_id = MessagesController.getInstance(currentAccount).getInputUser(user); reqCall.protocol = new TLRPC.TL_phoneCallProtocol(); reqCall.video = videoCall; reqCall.protocol.udp_p2p = true; reqCall.protocol.udp_reflector = true; reqCall.protocol.min_layer = CALL_MIN_LAYER; reqCall.protocol.max_layer = Instance.getConnectionMaxLayer(); reqCall.protocol.library_versions.addAll(Instance.AVAILABLE_VERSIONS); VoIPService.this.g_a = g_a; reqCall.g_a_hash = Utilities.computeSHA256(g_a, 0, g_a.length); reqCall.random_id = Utilities.random.nextInt(); ConnectionsManager.getInstance(currentAccount).sendRequest(reqCall, (response12, error12) -> AndroidUtilities.runOnUIThread(() -> { if (error12 == null) { privateCall = ((TLRPC.TL_phone_phoneCall) response12).phone_call; a_or_b = salt1; dispatchStateChanged(STATE_WAITING); if (endCallAfterRequest) { hangUp(); return; } if (pendingUpdates.size() > 0 && privateCall != null) { for (TLRPC.PhoneCall call : pendingUpdates) { onCallUpdated(call); } pendingUpdates.clear(); } timeoutRunnable = () -> { timeoutRunnable = null; TLRPC.TL_phone_discardCall req1 = new TLRPC.TL_phone_discardCall(); req1.peer = new TLRPC.TL_inputPhoneCall(); req1.peer.access_hash = privateCall.access_hash; req1.peer.id = privateCall.id; req1.reason = new TLRPC.TL_phoneCallDiscardReasonMissed(); ConnectionsManager.getInstance(currentAccount).sendRequest(req1, (response1, error1) -> { if (BuildVars.LOGS_ENABLED) { if (error1 != null) { FileLog.e("error on phone.discardCall: " + error1); } else { FileLog.d("phone.discardCall " + response1); } } AndroidUtilities.runOnUIThread(VoIPService.this::callFailed); }, ConnectionsManager.RequestFlagFailOnServerErrors); }; AndroidUtilities.runOnUIThread(timeoutRunnable, MessagesController.getInstance(currentAccount).callReceiveTimeout); } else { if (error12.code == 400 && "PARTICIPANT_VERSION_OUTDATED".equals(error12.text)) { callFailed(Instance.ERROR_PEER_OUTDATED); } else if (error12.code == 403) { callFailed(Instance.ERROR_PRIVACY); } else if (error12.code == 406) { callFailed(Instance.ERROR_LOCALIZED); } else { if (BuildVars.LOGS_ENABLED) { FileLog.e("Error on phone.requestCall: " + error12); } callFailed(); } } }), ConnectionsManager.RequestFlagFailOnServerErrors); } else { if (BuildVars.LOGS_ENABLED) { FileLog.e("Error on getDhConfig " + error); } callFailed(); } }, ConnectionsManager.RequestFlagFailOnServerErrors); } private void acknowledgeCall(final boolean startRinging) { if (privateCall instanceof TLRPC.TL_phoneCallDiscarded) { if (BuildVars.LOGS_ENABLED) { FileLog.w("Call " + privateCall.id + " was discarded before the service started, stopping"); } stopSelf(); return; } if (Build.VERSION.SDK_INT >= 19 && XiaomiUtilities.isMIUI() && !XiaomiUtilities.isCustomPermissionGranted(XiaomiUtilities.OP_SHOW_WHEN_LOCKED)) { if (((KeyguardManager) getSystemService(KEYGUARD_SERVICE)).inKeyguardRestrictedInputMode()) { if (BuildVars.LOGS_ENABLED) { FileLog.e("MIUI: no permission to show when locked but the screen is locked. ¯\\_(ツ)_/¯"); } stopSelf(); return; } } TLRPC.TL_phone_receivedCall req = new TLRPC.TL_phone_receivedCall(); req.peer = new TLRPC.TL_inputPhoneCall(); req.peer.id = privateCall.id; req.peer.access_hash = privateCall.access_hash; ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { if (sharedInstance == null) { return; } if (BuildVars.LOGS_ENABLED) { FileLog.w("receivedCall response = " + response); } if (error != null) { if (BuildVars.LOGS_ENABLED) { FileLog.e("error on receivedCall: " + error); } stopSelf(); } else { if (USE_CONNECTION_SERVICE) { ContactsController.getInstance(currentAccount).createOrUpdateConnectionServiceContact(user.id, user.first_name, user.last_name); TelecomManager tm = (TelecomManager) getSystemService(TELECOM_SERVICE); Bundle extras = new Bundle(); extras.putInt("call_type", 1); tm.addNewIncomingCall(addAccountToTelecomManager(), extras); } if (startRinging) { startRinging(); } } }), ConnectionsManager.RequestFlagFailOnServerErrors); } private boolean isRinging() { return currentState == STATE_WAITING_INCOMING; } public boolean isJoined() { return currentState != STATE_WAIT_INIT && currentState != STATE_CREATING; } public void requestVideoCall(boolean screencast) { if (tgVoip[CAPTURE_DEVICE_CAMERA] == null) { return; } if (!screencast && captureDevice[CAPTURE_DEVICE_CAMERA] != 0) { tgVoip[CAPTURE_DEVICE_CAMERA].setupOutgoingVideoCreated(captureDevice[CAPTURE_DEVICE_CAMERA]); destroyCaptureDevice[CAPTURE_DEVICE_CAMERA] = false; } else { tgVoip[CAPTURE_DEVICE_CAMERA].setupOutgoingVideo(localSink[CAPTURE_DEVICE_CAMERA], screencast ? 2 : (isFrontFaceCamera ? 1 : 0)); } isPrivateScreencast = screencast; } public void switchCamera() { if (tgVoip[CAPTURE_DEVICE_CAMERA] == null || !tgVoip[CAPTURE_DEVICE_CAMERA].hasVideoCapturer() || switchingCamera) { if (captureDevice[CAPTURE_DEVICE_CAMERA] != 0 && !switchingCamera) { NativeInstance.switchCameraCapturer(captureDevice[CAPTURE_DEVICE_CAMERA], !isFrontFaceCamera); } return; } switchingCamera = true; tgVoip[CAPTURE_DEVICE_CAMERA].switchCamera(!isFrontFaceCamera); } public void createCaptureDevice(boolean screencast) { int index = screencast ? CAPTURE_DEVICE_SCREEN : CAPTURE_DEVICE_CAMERA; int deviceType; if (screencast) { deviceType = 2; } else { deviceType = isFrontFaceCamera ? 1 : 0; } if (groupCall == null) { if (!isPrivateScreencast && screencast) { setVideoState(false, Instance.VIDEO_STATE_INACTIVE); } isPrivateScreencast = screencast; if (tgVoip[CAPTURE_DEVICE_CAMERA] != null) { tgVoip[CAPTURE_DEVICE_CAMERA].clearVideoCapturer(); } } if (index == CAPTURE_DEVICE_SCREEN) { if (groupCall != null) { if (captureDevice[index] != 0) { return; } captureDevice[index] = NativeInstance.createVideoCapturer(localSink[index], deviceType); createGroupInstance(CAPTURE_DEVICE_SCREEN, false); setVideoState(true, Instance.VIDEO_STATE_ACTIVE); AccountInstance.getInstance(currentAccount).getNotificationCenter().postNotificationName(NotificationCenter.groupCallScreencastStateChanged); } else { requestVideoCall(true); setVideoState(true, Instance.VIDEO_STATE_ACTIVE); if (VoIPFragment.getInstance() != null) { VoIPFragment.getInstance().onScreenCastStart(); } } } else { if (captureDevice[index] != 0 || tgVoip[index] == null) { if (tgVoip[index] != null && captureDevice[index] != 0) { tgVoip[index].activateVideoCapturer(captureDevice[index]); } if (captureDevice[index] != 0) { return; } } captureDevice[index] = NativeInstance.createVideoCapturer(localSink[index], deviceType); } } public void setupCaptureDevice(boolean screencast, boolean micEnabled) { if (!screencast) { int index = screencast ? CAPTURE_DEVICE_SCREEN : CAPTURE_DEVICE_CAMERA; if (captureDevice[index] == 0 || tgVoip[index] == null) { return; } tgVoip[index].setupOutgoingVideoCreated(captureDevice[index]); destroyCaptureDevice[index] = false; videoState[index] = Instance.VIDEO_STATE_ACTIVE; } if (micMute == micEnabled) { setMicMute(!micEnabled, false, false); micSwitching = true; } if (groupCall != null) { editCallMember(UserConfig.getInstance(currentAccount).getCurrentUser(), !micEnabled, videoState[CAPTURE_DEVICE_CAMERA] != Instance.VIDEO_STATE_ACTIVE, null, null, () -> micSwitching = false); } } public void clearCamera() { if (tgVoip[CAPTURE_DEVICE_CAMERA] != null) { tgVoip[CAPTURE_DEVICE_CAMERA].clearVideoCapturer(); } } public void setVideoState(boolean screencast, int state) { int index = screencast ? CAPTURE_DEVICE_SCREEN : CAPTURE_DEVICE_CAMERA; int trueIndex = groupCall != null ? index : CAPTURE_DEVICE_CAMERA; if (tgVoip[trueIndex] == null) { if (captureDevice[index] != 0) { videoState[trueIndex] = state; NativeInstance.setVideoStateCapturer(captureDevice[index], videoState[trueIndex]); } else if (state == Instance.VIDEO_STATE_ACTIVE && currentState != STATE_BUSY && currentState != STATE_ENDED) { captureDevice[index] = NativeInstance.createVideoCapturer(localSink[trueIndex], isFrontFaceCamera ? 1 : 0); videoState[trueIndex] = Instance.VIDEO_STATE_ACTIVE; } return; } videoState[trueIndex] = state; tgVoip[trueIndex].setVideoState(videoState[trueIndex]); if (captureDevice[index] != 0) { NativeInstance.setVideoStateCapturer(captureDevice[index], videoState[trueIndex]); } if (!screencast) { if (groupCall != null) { editCallMember(UserConfig.getInstance(currentAccount).getCurrentUser(), null, videoState[CAPTURE_DEVICE_CAMERA] != Instance.VIDEO_STATE_ACTIVE, null, null, null); } checkIsNear(); } } public void stopScreenCapture() { if (groupCall == null || videoState[CAPTURE_DEVICE_SCREEN] != Instance.VIDEO_STATE_ACTIVE) { return; } TLRPC.TL_phone_leaveGroupCallPresentation req = new TLRPC.TL_phone_leaveGroupCallPresentation(); req.call = groupCall.getInputGroupCall(); ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> { if (response != null) { TLRPC.Updates updates = (TLRPC.Updates) response; MessagesController.getInstance(currentAccount).processUpdates(updates, false); } }); NativeInstance instance = tgVoip[CAPTURE_DEVICE_SCREEN]; if (instance != null) { Utilities.globalQueue.postRunnable(instance::stopGroup); } mySource[CAPTURE_DEVICE_SCREEN] = 0; tgVoip[CAPTURE_DEVICE_SCREEN] = null; destroyCaptureDevice[CAPTURE_DEVICE_SCREEN] = true; captureDevice[CAPTURE_DEVICE_SCREEN] = 0; videoState[CAPTURE_DEVICE_SCREEN] = Instance.VIDEO_STATE_INACTIVE; AccountInstance.getInstance(currentAccount).getNotificationCenter().postNotificationName(NotificationCenter.groupCallScreencastStateChanged); } public int getVideoState(boolean screencast) { return videoState[screencast ? CAPTURE_DEVICE_SCREEN : CAPTURE_DEVICE_CAMERA]; } public void setSinks(VideoSink local, VideoSink remote) { setSinks(local, false, remote); } public void setSinks(VideoSink local, boolean screencast, VideoSink remote) { ProxyVideoSink localSink = this.localSink[screencast ? CAPTURE_DEVICE_SCREEN : CAPTURE_DEVICE_CAMERA]; ProxyVideoSink remoteSink = this.remoteSink[screencast ? CAPTURE_DEVICE_SCREEN : CAPTURE_DEVICE_CAMERA]; if (localSink != null) { localSink.setTarget(local); } if (remoteSink != null) { remoteSink.setTarget(remote); } } public void setLocalSink(VideoSink local, boolean screencast) { if (screencast) { //localSink[CAPTURE_DEVICE_SCREEN].setTarget(local); } else { localSink[CAPTURE_DEVICE_CAMERA].setTarget(local); } } public void setRemoteSink(VideoSink remote, boolean screencast) { remoteSink[screencast ? CAPTURE_DEVICE_SCREEN : CAPTURE_DEVICE_CAMERA].setTarget(remote); } public ProxyVideoSink addRemoteSink(TLRPC.TL_groupCallParticipant participant, boolean screencast, VideoSink remote, VideoSink background) { if (tgVoip[CAPTURE_DEVICE_CAMERA] == null) { return null; } String endpointId = screencast ? participant.presentationEndpoint : participant.videoEndpoint; if (endpointId == null) { return null; } ProxyVideoSink sink = remoteSinks.get(endpointId); if (sink != null && sink.target == remote) { return sink; } if (sink == null) { sink = proxyVideoSinkLruCache.remove(endpointId); } if (sink == null) { sink = new ProxyVideoSink(); } if (remote != null) { sink.setTarget(remote); } if (background != null) { sink.setBackground(background); } remoteSinks.put(endpointId, sink); sink.nativeInstance = tgVoip[CAPTURE_DEVICE_CAMERA].addIncomingVideoOutput(QUALITY_MEDIUM, endpointId, createSsrcGroups(screencast ? participant.presentation : participant.video), sink); return sink; } private NativeInstance.SsrcGroup[] createSsrcGroups(TLRPC.TL_groupCallParticipantVideo video) { if (video.source_groups.isEmpty()) { return null; } NativeInstance.SsrcGroup[] result = new NativeInstance.SsrcGroup[video.source_groups.size()]; for (int a = 0; a < result.length; a++) { result[a] = new NativeInstance.SsrcGroup(); TLRPC.TL_groupCallParticipantVideoSourceGroup group = video.source_groups.get(a); result[a].semantics = group.semantics; result[a].ssrcs = new int[group.sources.size()]; for (int b = 0; b < result[a].ssrcs.length; b++) { result[a].ssrcs[b] = group.sources.get(b); } } return result; } public void requestFullScreen(TLRPC.TL_groupCallParticipant participant, boolean full, boolean screencast) { String endpointId = screencast ? participant.presentationEndpoint : participant.videoEndpoint; if (endpointId == null) { return; } if (full) { tgVoip[CAPTURE_DEVICE_CAMERA].setVideoEndpointQuality(endpointId, QUALITY_FULL); } else { tgVoip[CAPTURE_DEVICE_CAMERA].setVideoEndpointQuality(endpointId, QUALITY_MEDIUM); } } public void removeRemoteSink(TLRPC.TL_groupCallParticipant participant, boolean presentation) { if (presentation) { ProxyVideoSink sink = remoteSinks.remove(participant.presentationEndpoint); if (sink != null) { tgVoip[CAPTURE_DEVICE_CAMERA].removeIncomingVideoOutput(sink.nativeInstance); } } else { ProxyVideoSink sink = remoteSinks.remove(participant.videoEndpoint); if (sink != null) { tgVoip[CAPTURE_DEVICE_CAMERA].removeIncomingVideoOutput(sink.nativeInstance); } } } public boolean isFullscreen(TLRPC.TL_groupCallParticipant participant, boolean screencast) { return currentBackgroundSink[screencast ? CAPTURE_DEVICE_SCREEN : CAPTURE_DEVICE_CAMERA] != null && TextUtils.equals(currentBackgroundEndpointId[screencast ? CAPTURE_DEVICE_SCREEN : CAPTURE_DEVICE_CAMERA], screencast ? participant.presentationEndpoint : participant.videoEndpoint); } public void setBackgroundSinks(VideoSink local, VideoSink remote) { localSink[CAPTURE_DEVICE_CAMERA].setBackground(local); remoteSink[CAPTURE_DEVICE_CAMERA].setBackground(remote); } public void swapSinks() { localSink[CAPTURE_DEVICE_CAMERA].swap(); remoteSink[CAPTURE_DEVICE_CAMERA].swap(); } public boolean isHangingUp() { return currentState == STATE_HANGING_UP; } public void onSignalingData(TLRPC.TL_updatePhoneCallSignalingData data) { if (user == null || tgVoip[CAPTURE_DEVICE_CAMERA] == null || tgVoip[CAPTURE_DEVICE_CAMERA].isGroup() || getCallID() != data.phone_call_id) { return; } tgVoip[CAPTURE_DEVICE_CAMERA].onSignalingDataReceive(data.data); } public long getSelfId() { if (groupCallPeer == null) { return UserConfig.getInstance(currentAccount).clientUserId; } if (groupCallPeer instanceof TLRPC.TL_inputPeerUser) { return groupCallPeer.user_id; } else if (groupCallPeer instanceof TLRPC.TL_inputPeerChannel) { return -groupCallPeer.channel_id; } else { return -groupCallPeer.chat_id; } } public void onGroupCallParticipantsUpdate(TLRPC.TL_updateGroupCallParticipants update) { if (chat == null || groupCall == null || groupCall.call.id != update.call.id) { return; } long selfId = getSelfId(); for (int a = 0, N = update.participants.size(); a < N; a++) { TLRPC.TL_groupCallParticipant participant = update.participants.get(a); if (participant.left) { if (participant.source != 0) { if (participant.source == mySource[CAPTURE_DEVICE_CAMERA]) { int selfCount = 0; for (int b = 0; b < N; b++) { TLRPC.TL_groupCallParticipant p = update.participants.get(b); if (p.self || p.source == mySource[CAPTURE_DEVICE_CAMERA]) { selfCount++; } } if (selfCount > 1) { hangUp(2); return; } } } } else if (MessageObject.getPeerId(participant.peer) == selfId) { if (participant.source != mySource[CAPTURE_DEVICE_CAMERA] && mySource[CAPTURE_DEVICE_CAMERA] != 0 && participant.source != 0) { if (BuildVars.LOGS_ENABLED) { FileLog.d("source mismatch my = " + mySource[CAPTURE_DEVICE_CAMERA] + " psrc = " + participant.source); } hangUp(2); return; } else if (ChatObject.isChannel(chat) && currentGroupModeStreaming && participant.can_self_unmute) { switchingStream = true; createGroupInstance(CAPTURE_DEVICE_CAMERA, false); } if (participant.muted) { setMicMute(true, false, false); } } } } public void onGroupCallUpdated(TLRPC.GroupCall call) { if (chat == null) { return; } if (groupCall == null || groupCall.call.id != call.id) { return; } if (groupCall.call instanceof TLRPC.TL_groupCallDiscarded) { hangUp(2); return; } boolean newModeStreaming = false; if (myParams != null) { try { JSONObject object = new JSONObject(myParams.data); newModeStreaming = object.optBoolean("stream"); } catch (Exception e) { FileLog.e(e); } } if ((currentState == STATE_WAIT_INIT || newModeStreaming != currentGroupModeStreaming) && myParams != null) { if (playedConnectedSound && newModeStreaming != currentGroupModeStreaming) { switchingStream = true; } currentGroupModeStreaming = newModeStreaming; try { if (newModeStreaming) { tgVoip[CAPTURE_DEVICE_CAMERA].prepareForStream(groupCall.call != null && groupCall.call.rtmp_stream); } else { tgVoip[CAPTURE_DEVICE_CAMERA].setJoinResponsePayload(myParams.data); } dispatchStateChanged(STATE_WAIT_INIT_ACK); } catch (Exception e) { FileLog.e(e); } } } public void onCallUpdated(TLRPC.PhoneCall phoneCall) { if (user == null) { return; } if (privateCall == null) { pendingUpdates.add(phoneCall); return; } if (phoneCall == null) { return; } if (phoneCall.id != privateCall.id) { if (BuildVars.LOGS_ENABLED) { FileLog.w("onCallUpdated called with wrong call id (got " + phoneCall.id + ", expected " + this.privateCall.id + ")"); } return; } if (phoneCall.access_hash == 0) { phoneCall.access_hash = this.privateCall.access_hash; } if (BuildVars.LOGS_ENABLED) { FileLog.d("Call updated: " + phoneCall); } privateCall = phoneCall; if (phoneCall instanceof TLRPC.TL_phoneCallDiscarded) { needSendDebugLog = phoneCall.need_debug; needRateCall = phoneCall.need_rating; if (BuildVars.LOGS_ENABLED) { FileLog.d("call discarded, stopping service"); } if (phoneCall.reason instanceof TLRPC.TL_phoneCallDiscardReasonBusy) { dispatchStateChanged(STATE_BUSY); playingSound = true; Utilities.globalQueue.postRunnable(() -> soundPool.play(spBusyId, 1, 1, 0, -1, 1)); AndroidUtilities.runOnUIThread(afterSoundRunnable, 1500); endConnectionServiceCall(1500); stopSelf(); } else { callEnded(); } } else if (phoneCall instanceof TLRPC.TL_phoneCall && authKey == null) { if (phoneCall.g_a_or_b == null) { if (BuildVars.LOGS_ENABLED) { FileLog.w("stopping VoIP service, Ga == null"); } callFailed(); return; } if (!Arrays.equals(g_a_hash, Utilities.computeSHA256(phoneCall.g_a_or_b, 0, phoneCall.g_a_or_b.length))) { if (BuildVars.LOGS_ENABLED) { FileLog.w("stopping VoIP service, Ga hash doesn't match"); } callFailed(); return; } g_a = phoneCall.g_a_or_b; BigInteger g_a = new BigInteger(1, phoneCall.g_a_or_b); BigInteger p = new BigInteger(1, MessagesStorage.getInstance(currentAccount).getSecretPBytes()); if (!Utilities.isGoodGaAndGb(g_a, p)) { if (BuildVars.LOGS_ENABLED) { FileLog.w("stopping VoIP service, bad Ga and Gb (accepting)"); } callFailed(); return; } g_a = g_a.modPow(new BigInteger(1, a_or_b), p); byte[] authKey = g_a.toByteArray(); if (authKey.length > 256) { byte[] correctedAuth = new byte[256]; System.arraycopy(authKey, authKey.length - 256, correctedAuth, 0, 256); authKey = correctedAuth; } else if (authKey.length < 256) { byte[] correctedAuth = new byte[256]; System.arraycopy(authKey, 0, correctedAuth, 256 - authKey.length, authKey.length); for (int a = 0; a < 256 - authKey.length; a++) { correctedAuth[a] = 0; } authKey = correctedAuth; } byte[] authKeyHash = Utilities.computeSHA1(authKey); byte[] authKeyId = new byte[8]; System.arraycopy(authKeyHash, authKeyHash.length - 8, authKeyId, 0, 8); VoIPService.this.authKey = authKey; keyFingerprint = Utilities.bytesToLong(authKeyId); if (keyFingerprint != phoneCall.key_fingerprint) { if (BuildVars.LOGS_ENABLED) { FileLog.w("key fingerprints don't match"); } callFailed(); return; } initiateActualEncryptedCall(); } else if (phoneCall instanceof TLRPC.TL_phoneCallAccepted && authKey == null) { processAcceptedCall(); } else { if (currentState == STATE_WAITING && phoneCall.receive_date != 0) { dispatchStateChanged(STATE_RINGING); if (BuildVars.LOGS_ENABLED) { FileLog.d("!!!!!! CALL RECEIVED"); } if (connectingSoundRunnable != null) { AndroidUtilities.cancelRunOnUIThread(connectingSoundRunnable); connectingSoundRunnable = null; } Utilities.globalQueue.postRunnable(() -> { if (spPlayId != 0) { soundPool.stop(spPlayId); } spPlayId = soundPool.play(spRingbackID, 1, 1, 0, -1, 1); }); if (timeoutRunnable != null) { AndroidUtilities.cancelRunOnUIThread(timeoutRunnable); timeoutRunnable = null; } timeoutRunnable = () -> { timeoutRunnable = null; declineIncomingCall(DISCARD_REASON_MISSED, null); }; AndroidUtilities.runOnUIThread(timeoutRunnable, MessagesController.getInstance(currentAccount).callRingTimeout); } } } private void startRatingActivity() { try { PendingIntent.getActivity(VoIPService.this, 0, new Intent(VoIPService.this, VoIPFeedbackActivity.class) .putExtra("call_id", privateCall.id) .putExtra("call_access_hash", privateCall.access_hash) .putExtra("call_video", privateCall.video) .putExtra("account", currentAccount) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_MUTABLE).send(); } catch (Exception x) { if (BuildVars.LOGS_ENABLED) { FileLog.e("Error starting incall activity", x); } } } public byte[] getEncryptionKey() { return authKey; } private void processAcceptedCall() { dispatchStateChanged(STATE_EXCHANGING_KEYS); BigInteger p = new BigInteger(1, MessagesStorage.getInstance(currentAccount).getSecretPBytes()); BigInteger i_authKey = new BigInteger(1, privateCall.g_b); if (!Utilities.isGoodGaAndGb(i_authKey, p)) { if (BuildVars.LOGS_ENABLED) { FileLog.w("stopping VoIP service, bad Ga and Gb"); } callFailed(); return; } i_authKey = i_authKey.modPow(new BigInteger(1, a_or_b), p); byte[] authKey = i_authKey.toByteArray(); if (authKey.length > 256) { byte[] correctedAuth = new byte[256]; System.arraycopy(authKey, authKey.length - 256, correctedAuth, 0, 256); authKey = correctedAuth; } else if (authKey.length < 256) { byte[] correctedAuth = new byte[256]; System.arraycopy(authKey, 0, correctedAuth, 256 - authKey.length, authKey.length); for (int a = 0; a < 256 - authKey.length; a++) { correctedAuth[a] = 0; } authKey = correctedAuth; } byte[] authKeyHash = Utilities.computeSHA1(authKey); byte[] authKeyId = new byte[8]; System.arraycopy(authKeyHash, authKeyHash.length - 8, authKeyId, 0, 8); long fingerprint = Utilities.bytesToLong(authKeyId); this.authKey = authKey; keyFingerprint = fingerprint; TLRPC.TL_phone_confirmCall req = new TLRPC.TL_phone_confirmCall(); req.g_a = g_a; req.key_fingerprint = fingerprint; req.peer = new TLRPC.TL_inputPhoneCall(); req.peer.id = privateCall.id; req.peer.access_hash = privateCall.access_hash; req.protocol = new TLRPC.TL_phoneCallProtocol(); req.protocol.max_layer = Instance.getConnectionMaxLayer(); req.protocol.min_layer = CALL_MIN_LAYER; req.protocol.udp_p2p = req.protocol.udp_reflector = true; req.protocol.library_versions.addAll(Instance.AVAILABLE_VERSIONS); ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { if (error != null) { callFailed(); } else { privateCall = ((TLRPC.TL_phone_phoneCall) response).phone_call; initiateActualEncryptedCall(); } })); } private int convertDataSavingMode(int mode) { if (mode != Instance.DATA_SAVING_ROAMING) { return mode; } return ApplicationLoader.isRoaming() ? Instance.DATA_SAVING_MOBILE : Instance.DATA_SAVING_NEVER; } public void migrateToChat(TLRPC.Chat newChat) { chat = newChat; } public void setGroupCallPeer(TLRPC.InputPeer peer) { if (groupCall == null) { return; } groupCallPeer = peer; groupCall.setSelfPeer(groupCallPeer); TLRPC.ChatFull chatFull = MessagesController.getInstance(currentAccount).getChatFull(groupCall.chatId); if (chatFull != null) { chatFull.groupcall_default_join_as = groupCall.selfPeer; if (chatFull.groupcall_default_join_as != null) { if (chatFull instanceof TLRPC.TL_chatFull) { chatFull.flags |= 32768; } else { chatFull.flags |= 67108864; } } else { if (chatFull instanceof TLRPC.TL_chatFull) { chatFull.flags &=~ 32768; } else { chatFull.flags &=~ 67108864; } } } createGroupInstance(CAPTURE_DEVICE_CAMERA, true); if (videoState[CAPTURE_DEVICE_SCREEN] == Instance.VIDEO_STATE_ACTIVE) { createGroupInstance(CAPTURE_DEVICE_SCREEN, true); } } private void startGroupCall(int ssrc, String json, boolean create) { if (sharedInstance != this) { return; } if (createGroupCall) { groupCall = new ChatObject.Call(); groupCall.call = new TLRPC.TL_groupCall(); groupCall.call.participants_count = 0; groupCall.call.version = 1; groupCall.call.can_start_video = true; groupCall.call.can_change_join_muted = true; groupCall.chatId = chat.id; groupCall.currentAccount = AccountInstance.getInstance(currentAccount); groupCall.setSelfPeer(groupCallPeer); groupCall.createNoVideoParticipant(); dispatchStateChanged(STATE_CREATING); TLRPC.TL_phone_createGroupCall req = new TLRPC.TL_phone_createGroupCall(); req.peer = MessagesController.getInputPeer(chat); req.random_id = Utilities.random.nextInt(); if (scheduleDate != 0) { req.schedule_date = scheduleDate; req.flags |= 2; } ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> { if (response != null) { TLRPC.Updates updates = (TLRPC.Updates) response; for (int a = 0; a < updates.updates.size(); a++) { TLRPC.Update update = updates.updates.get(a); if (update instanceof TLRPC.TL_updateGroupCall) { TLRPC.TL_updateGroupCall updateGroupCall = (TLRPC.TL_updateGroupCall) update; AndroidUtilities.runOnUIThread(() -> { if (sharedInstance == null) { return; } groupCall.call.access_hash = updateGroupCall.call.access_hash; groupCall.call.id = updateGroupCall.call.id; MessagesController.getInstance(currentAccount).putGroupCall(groupCall.chatId, groupCall); startGroupCall(0, null, false); }); break; } } MessagesController.getInstance(currentAccount).processUpdates(updates, false); } else { AndroidUtilities.runOnUIThread(() -> { NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.needShowAlert, 6, error.text); hangUp(0); }); } }, ConnectionsManager.RequestFlagFailOnServerErrors); createGroupCall = false; return; } if (json == null) { if (groupCall == null) { groupCall = MessagesController.getInstance(currentAccount).getGroupCall(chat.id, false); if (groupCall != null) { groupCall.setSelfPeer(groupCallPeer); } } configureDeviceForCall(); showNotification(); AndroidUtilities.runOnUIThread(() -> NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.didStartedCall)); createGroupInstance(CAPTURE_DEVICE_CAMERA, false); } else { if (getSharedInstance() == null || groupCall == null) { return; } dispatchStateChanged(STATE_WAIT_INIT); if (BuildVars.LOGS_ENABLED) { FileLog.d("initital source = " + ssrc); } TLRPC.TL_phone_joinGroupCall req = new TLRPC.TL_phone_joinGroupCall(); req.muted = true; req.video_stopped = videoState[CAPTURE_DEVICE_CAMERA] != Instance.VIDEO_STATE_ACTIVE; req.call = groupCall.getInputGroupCall(); req.params = new TLRPC.TL_dataJSON(); req.params.data = json; if (!TextUtils.isEmpty(joinHash)) { req.invite_hash = joinHash; req.flags |= 2; } if (groupCallPeer != null) { req.join_as = groupCallPeer; } else { req.join_as = new TLRPC.TL_inputPeerUser(); req.join_as.user_id = AccountInstance.getInstance(currentAccount).getUserConfig().getClientUserId(); } ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> { if (response != null) { AndroidUtilities.runOnUIThread(() -> mySource[CAPTURE_DEVICE_CAMERA] = ssrc); TLRPC.Updates updates = (TLRPC.Updates) response; long selfId = getSelfId(); for (int a = 0, N = updates.updates.size(); a < N; a++) { TLRPC.Update update = updates.updates.get(a); if (update instanceof TLRPC.TL_updateGroupCallParticipants) { TLRPC.TL_updateGroupCallParticipants updateGroupCallParticipants = (TLRPC.TL_updateGroupCallParticipants) update; for (int b = 0, N2 = updateGroupCallParticipants.participants.size(); b < N2; b++) { TLRPC.TL_groupCallParticipant participant = updateGroupCallParticipants.participants.get(b); if (MessageObject.getPeerId(participant.peer) == selfId) { AndroidUtilities.runOnUIThread(() -> mySource[CAPTURE_DEVICE_CAMERA] = participant.source); if (BuildVars.LOGS_ENABLED) { FileLog.d("join source = " + participant.source); } break; } } } else if (update instanceof TLRPC.TL_updateGroupCallConnection) { TLRPC.TL_updateGroupCallConnection updateGroupCallConnection = (TLRPC.TL_updateGroupCallConnection) update; if (!updateGroupCallConnection.presentation) { myParams = updateGroupCallConnection.params; } } } MessagesController.getInstance(currentAccount).processUpdates(updates, false); AndroidUtilities.runOnUIThread(() -> groupCall.loadMembers(create)); startGroupCheckShortpoll(); } else { AndroidUtilities.runOnUIThread(() -> { if ("JOIN_AS_PEER_INVALID".equals(error.text)) { TLRPC.ChatFull chatFull = MessagesController.getInstance(currentAccount).getChatFull(chat.id); if (chatFull != null) { if (chatFull instanceof TLRPC.TL_chatFull) { chatFull.flags &=~ 32768; } else { chatFull.flags &=~ 67108864; } chatFull.groupcall_default_join_as = null; JoinCallAlert.resetCache(); } hangUp(2); } else if ("GROUPCALL_SSRC_DUPLICATE_MUCH".equals(error.text)) { createGroupInstance(CAPTURE_DEVICE_CAMERA, false); } else { if ("GROUPCALL_INVALID".equals(error.text)) { MessagesController.getInstance(currentAccount).loadFullChat(chat.id, 0, true); } NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.needShowAlert, 6, error.text); hangUp(0); } }); } }); } } private void startScreenCapture(int ssrc, String json) { if (getSharedInstance() == null || groupCall == null) { return; } mySource[CAPTURE_DEVICE_SCREEN] = 0; TLRPC.TL_phone_joinGroupCallPresentation req = new TLRPC.TL_phone_joinGroupCallPresentation(); req.call = groupCall.getInputGroupCall(); req.params = new TLRPC.TL_dataJSON(); req.params.data = json; ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> { if (response != null) { AndroidUtilities.runOnUIThread(() -> mySource[CAPTURE_DEVICE_SCREEN] = ssrc); TLRPC.Updates updates = (TLRPC.Updates) response; AndroidUtilities.runOnUIThread(() -> { if (tgVoip[CAPTURE_DEVICE_SCREEN] != null) { long selfId = getSelfId(); for (int a = 0, N = updates.updates.size(); a < N; a++) { TLRPC.Update update = updates.updates.get(a); if (update instanceof TLRPC.TL_updateGroupCallConnection) { TLRPC.TL_updateGroupCallConnection updateGroupCallConnection = (TLRPC.TL_updateGroupCallConnection) update; if (updateGroupCallConnection.presentation) { tgVoip[CAPTURE_DEVICE_SCREEN].setJoinResponsePayload(updateGroupCallConnection.params.data); } } else if (update instanceof TLRPC.TL_updateGroupCallParticipants) { TLRPC.TL_updateGroupCallParticipants updateGroupCallParticipants = (TLRPC.TL_updateGroupCallParticipants) update; for (int b = 0, N2 = updateGroupCallParticipants.participants.size(); b < N2; b++) { TLRPC.TL_groupCallParticipant participant = updateGroupCallParticipants.participants.get(b); if (MessageObject.getPeerId(participant.peer) == selfId) { if (participant.presentation != null) { if ((participant.presentation.flags & 2) != 0) { mySource[CAPTURE_DEVICE_SCREEN] = participant.presentation.audio_source; } else { for (int c = 0, N3 = participant.presentation.source_groups.size(); c < N3; c++) { TLRPC.TL_groupCallParticipantVideoSourceGroup sourceGroup = participant.presentation.source_groups.get(c); if (sourceGroup.sources.size() > 0) { mySource[CAPTURE_DEVICE_SCREEN] = sourceGroup.sources.get(0); } } } } break; } } } } } }); MessagesController.getInstance(currentAccount).processUpdates(updates, false); startGroupCheckShortpoll(); } else { AndroidUtilities.runOnUIThread(() -> { if ("GROUPCALL_VIDEO_TOO_MUCH".equals(error.text)) { groupCall.reloadGroupCall(); } else if ("JOIN_AS_PEER_INVALID".equals(error.text)) { TLRPC.ChatFull chatFull = MessagesController.getInstance(currentAccount).getChatFull(chat.id); if (chatFull != null) { if (chatFull instanceof TLRPC.TL_chatFull) { chatFull.flags &=~ 32768; } else { chatFull.flags &=~ 67108864; } chatFull.groupcall_default_join_as = null; JoinCallAlert.resetCache(); } hangUp(2); } else if ("GROUPCALL_SSRC_DUPLICATE_MUCH".equals(error.text)) { createGroupInstance(CAPTURE_DEVICE_SCREEN, false); } else { if ("GROUPCALL_INVALID".equals(error.text)) { MessagesController.getInstance(currentAccount).loadFullChat(chat.id, 0, true); } } }); } }); } private Runnable shortPollRunnable; private int checkRequestId; private void startGroupCheckShortpoll() { if (shortPollRunnable != null || sharedInstance == null || groupCall == null || (mySource[CAPTURE_DEVICE_CAMERA] == 0 && mySource[CAPTURE_DEVICE_SCREEN] == 0 && !(groupCall.call != null && groupCall.call.rtmp_stream))) { return; } AndroidUtilities.runOnUIThread(shortPollRunnable = () -> { if (shortPollRunnable == null || sharedInstance == null || groupCall == null || (mySource[CAPTURE_DEVICE_CAMERA] == 0 && mySource[CAPTURE_DEVICE_SCREEN] == 0 && !(groupCall.call != null && groupCall.call.rtmp_stream))) { return; } TLRPC.TL_phone_checkGroupCall req = new TLRPC.TL_phone_checkGroupCall(); req.call = groupCall.getInputGroupCall(); for (int a = 0; a < mySource.length; a++) { if (mySource[a] != 0) { req.sources.add(mySource[a]); } } checkRequestId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { if (shortPollRunnable == null || sharedInstance == null || groupCall == null) { return; } shortPollRunnable = null; checkRequestId = 0; boolean recreateCamera = false; boolean recreateScreenCapture = false; if (response instanceof TLRPC.Vector) { TLRPC.Vector vector = (TLRPC.Vector) response; if (mySource[CAPTURE_DEVICE_CAMERA] != 0 && req.sources.contains(mySource[CAPTURE_DEVICE_CAMERA])) { if (!vector.objects.contains(mySource[CAPTURE_DEVICE_CAMERA])) { recreateCamera = true; } } if (mySource[CAPTURE_DEVICE_SCREEN] != 0 && req.sources.contains(mySource[CAPTURE_DEVICE_SCREEN])) { if (!vector.objects.contains(mySource[CAPTURE_DEVICE_SCREEN])) { recreateScreenCapture = true; } } } else if (error != null && error.code == 400) { recreateCamera = true; if (mySource[CAPTURE_DEVICE_SCREEN] != 0 && req.sources.contains(mySource[CAPTURE_DEVICE_SCREEN])) { recreateScreenCapture = true; } } if (recreateCamera) { createGroupInstance(CAPTURE_DEVICE_CAMERA, false); } if (recreateScreenCapture) { createGroupInstance(CAPTURE_DEVICE_SCREEN, false); } if (mySource[CAPTURE_DEVICE_SCREEN] != 0 || mySource[CAPTURE_DEVICE_CAMERA] != 0 || (groupCall.call != null && groupCall.call.rtmp_stream)) { startGroupCheckShortpoll(); } })); }, 4000); } private void cancelGroupCheckShortPoll() { if (mySource[CAPTURE_DEVICE_SCREEN] != 0 || mySource[CAPTURE_DEVICE_CAMERA] != 0) { return; } if (checkRequestId != 0) { ConnectionsManager.getInstance(currentAccount).cancelRequest(checkRequestId, false); checkRequestId = 0; } if (shortPollRunnable != null) { AndroidUtilities.cancelRunOnUIThread(shortPollRunnable); shortPollRunnable = null; } } private static class RequestedParticipant { public int audioSsrc; public TLRPC.TL_groupCallParticipant participant; public RequestedParticipant(TLRPC.TL_groupCallParticipant p, int ssrc) { participant = p; audioSsrc = ssrc; } } private void broadcastUnknownParticipants(long taskPtr, int[] unknown) { if (groupCall == null || tgVoip[CAPTURE_DEVICE_CAMERA] == null) { return; } long selfId = getSelfId(); ArrayList<RequestedParticipant> participants = null; for (int a = 0, N = unknown.length; a < N; a++) { TLRPC.TL_groupCallParticipant p = groupCall.participantsBySources.get(unknown[a]); if (p == null) { p = groupCall.participantsByVideoSources.get(unknown[a]); if (p == null) { p = groupCall.participantsByPresentationSources.get(unknown[a]); } } if (p == null || MessageObject.getPeerId(p.peer) == selfId || p.source == 0) { continue; } if (participants == null) { participants = new ArrayList<>(); } participants.add(new RequestedParticipant(p, unknown[a])); } if (participants != null) { int[] ssrcs = new int[participants.size()]; for (int a = 0, N = participants.size(); a < N; a++) { RequestedParticipant p = participants.get(a); ssrcs[a] = p.audioSsrc; } tgVoip[CAPTURE_DEVICE_CAMERA].onMediaDescriptionAvailable(taskPtr, ssrcs); for (int a = 0, N = participants.size(); a < N; a++) { RequestedParticipant p = participants.get(a); if (p.participant.muted_by_you) { tgVoip[CAPTURE_DEVICE_CAMERA].setVolume(p.audioSsrc, 0); } else { tgVoip[CAPTURE_DEVICE_CAMERA].setVolume(p.audioSsrc, ChatObject.getParticipantVolume(p.participant) / 10000.0); } } } } private void createGroupInstance(int type, boolean switchAccount) { if (switchAccount) { mySource[type] = 0; if (type == CAPTURE_DEVICE_CAMERA) { switchingAccount = switchAccount; } } cancelGroupCheckShortPoll(); if (type == CAPTURE_DEVICE_CAMERA) { wasConnected = false; } else if (!wasConnected) { reconnectScreenCapture = true; return; } boolean created = false; if (tgVoip[type] == null) { created = true; final String logFilePath = BuildVars.DEBUG_VERSION ? VoIPHelper.getLogFilePath("voip_" + type + "_" + groupCall.call.id) : VoIPHelper.getLogFilePath(groupCall.call.id, false); tgVoip[type] = NativeInstance.makeGroup(logFilePath, captureDevice[type], type == CAPTURE_DEVICE_SCREEN, type == CAPTURE_DEVICE_CAMERA && SharedConfig.noiseSupression, (ssrc, json) -> { if (type == CAPTURE_DEVICE_CAMERA) { startGroupCall(ssrc, json, true); } else { startScreenCapture(ssrc, json); } }, (uids, levels, voice) -> { if (sharedInstance == null || groupCall == null || type != CAPTURE_DEVICE_CAMERA) { return; } groupCall.processVoiceLevelsUpdate(uids, levels, voice); float maxAmplitude = 0; boolean hasOther = false; for (int a = 0; a < uids.length; a++) { if (uids[a] == 0) { if (lastTypingTimeSend < SystemClock.uptimeMillis() - 5000 && levels[a] > 0.1f && voice[a]) { lastTypingTimeSend = SystemClock.uptimeMillis(); TLRPC.TL_messages_setTyping req = new TLRPC.TL_messages_setTyping(); req.action = new TLRPC.TL_speakingInGroupCallAction(); req.peer = MessagesController.getInputPeer(chat); ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> { }); } NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.webRtcMicAmplitudeEvent, levels[a]); continue; } hasOther = true; maxAmplitude = Math.max(maxAmplitude, levels[a]); } if (hasOther) { NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.webRtcSpeakerAmplitudeEvent, maxAmplitude); if (audioLevelsCallback != null) { audioLevelsCallback.run(uids, levels, voice); } } }, (taskPtr, unknown) -> { if (sharedInstance == null || groupCall == null || type != CAPTURE_DEVICE_CAMERA) { return; } groupCall.processUnknownVideoParticipants(unknown, (ssrcs) -> { if (sharedInstance == null || groupCall == null) { return; } broadcastUnknownParticipants(taskPtr, unknown); }); }, (timestamp, duration, videoChannel, quality) -> { if (type != CAPTURE_DEVICE_CAMERA) { return; } TLRPC.TL_upload_getFile req = new TLRPC.TL_upload_getFile(); req.limit = 128 * 1024; TLRPC.TL_inputGroupCallStream inputGroupCallStream = new TLRPC.TL_inputGroupCallStream(); inputGroupCallStream.call = groupCall.getInputGroupCall(); inputGroupCallStream.time_ms = timestamp; if (duration == 500) { inputGroupCallStream.scale = 1; } if (videoChannel != 0) { inputGroupCallStream.flags |= 1; inputGroupCallStream.video_channel = videoChannel; inputGroupCallStream.video_quality = quality; } req.location = inputGroupCallStream; String key = videoChannel == 0 ? ("" + timestamp) : (videoChannel + "_" + timestamp + "_" + quality); int reqId = AccountInstance.getInstance(currentAccount).getConnectionsManager().sendRequest(req, (response, error, responseTime) -> { AndroidUtilities.runOnUIThread(() -> currentStreamRequestTimestamp.remove(key)); if (tgVoip[type] == null) { return; } if (response != null) { TLRPC.TL_upload_file res = (TLRPC.TL_upload_file) response; tgVoip[type].onStreamPartAvailable(timestamp, res.bytes.buffer, res.bytes.limit(), responseTime, videoChannel, quality); } else { if ("GROUPCALL_JOIN_MISSING".equals(error.text)) { AndroidUtilities.runOnUIThread(() -> createGroupInstance(type, false)); } else { int status; if ("TIME_TOO_BIG".equals(error.text) || error.text.startsWith("FLOOD_WAIT")) { status = 0; } else { status = -1; } tgVoip[type].onStreamPartAvailable(timestamp, null, status, responseTime, videoChannel, quality); } } }, ConnectionsManager.RequestFlagFailOnServerErrors, ConnectionsManager.ConnectionTypeDownload, groupCall.call.stream_dc_id); AndroidUtilities.runOnUIThread(() -> currentStreamRequestTimestamp.put(key, reqId)); }, (timestamp, duration, videoChannel, quality) -> { if (type != CAPTURE_DEVICE_CAMERA) { return; } AndroidUtilities.runOnUIThread(() -> { String key = videoChannel == 0 ? ("" + timestamp) : (videoChannel + "_" + timestamp + "_" + quality); Integer reqId = currentStreamRequestTimestamp.get(key); if (reqId != null) { AccountInstance.getInstance(currentAccount).getConnectionsManager().cancelRequest(reqId, true); currentStreamRequestTimestamp.remove(key); } }); }, taskPtr -> { if (groupCall != null && groupCall.call != null && groupCall.call.rtmp_stream) { TLRPC.TL_phone_getGroupCallStreamChannels req = new TLRPC.TL_phone_getGroupCallStreamChannels(); req.call = groupCall.getInputGroupCall(); if (groupCall == null || groupCall.call == null || tgVoip[type] == null) { if (tgVoip[type] != null) { tgVoip[type].onRequestTimeComplete(taskPtr, 0); } return; } ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error, responseTime) -> { long currentTime = 0; if (error == null) { TLRPC.TL_phone_groupCallStreamChannels res = (TLRPC.TL_phone_groupCallStreamChannels) response; if (!res.channels.isEmpty()) { currentTime = res.channels.get(0).last_timestamp_ms; } if (!groupCall.loadedRtmpStreamParticipant) { groupCall.createRtmpStreamParticipant(res.channels); groupCall.loadedRtmpStreamParticipant = true; } } if (tgVoip[type] != null) { tgVoip[type].onRequestTimeComplete(taskPtr, currentTime); } }, ConnectionsManager.RequestFlagFailOnServerErrors, ConnectionsManager.ConnectionTypeDownload, groupCall.call.stream_dc_id); } else { if (tgVoip[type] != null) { tgVoip[type].onRequestTimeComplete(taskPtr, ConnectionsManager.getInstance(currentAccount).getCurrentTimeMillis()); } } }); tgVoip[type].setOnStateUpdatedListener((state, inTransition) -> updateConnectionState(type, state, inTransition)); } tgVoip[type].resetGroupInstance(!created, false); if (captureDevice[type] != 0) { destroyCaptureDevice[type] = false; } if (type == CAPTURE_DEVICE_CAMERA) { dispatchStateChanged(STATE_WAIT_INIT); } } private void updateConnectionState(int type, int state, boolean inTransition) { if (type != CAPTURE_DEVICE_CAMERA) { return; } dispatchStateChanged(state == 1 || switchingStream ? STATE_ESTABLISHED : STATE_RECONNECTING); if (switchingStream && (state == 0 || state == 1 && inTransition)) { AndroidUtilities.runOnUIThread(switchingStreamTimeoutRunnable = () -> { if (switchingStreamTimeoutRunnable == null) { return; } switchingStream = false; updateConnectionState(type, 0, true); switchingStreamTimeoutRunnable = null; }, 3000); } if (state == 0) { startGroupCheckShortpoll(); if (playedConnectedSound && spPlayId == 0 && !switchingStream && !switchingAccount) { Utilities.globalQueue.postRunnable(() -> { if (spPlayId != 0) { soundPool.stop(spPlayId); } spPlayId = soundPool.play(spVoiceChatConnecting, 1.0f, 1.0f, 0, -1, 1); }); } } else { cancelGroupCheckShortPoll(); if (!inTransition) { switchingStream = false; switchingAccount = false; } if (switchingStreamTimeoutRunnable != null) { AndroidUtilities.cancelRunOnUIThread(switchingStreamTimeoutRunnable); switchingStreamTimeoutRunnable = null; } if (playedConnectedSound) { Utilities.globalQueue.postRunnable(() -> { if (spPlayId != 0) { soundPool.stop(spPlayId); spPlayId = 0; } }); if (connectingSoundRunnable != null) { AndroidUtilities.cancelRunOnUIThread(connectingSoundRunnable); connectingSoundRunnable = null; } } else { playConnectedSound(); } if (!wasConnected) { wasConnected = true; if (reconnectScreenCapture) { createGroupInstance(CAPTURE_DEVICE_SCREEN, false); reconnectScreenCapture = false; } NativeInstance instance = tgVoip[CAPTURE_DEVICE_CAMERA]; if (instance != null) { if (!micMute) { instance.setMuteMicrophone(false); } } setParticipantsVolume(); } } } public void setParticipantsVolume() { NativeInstance instance = tgVoip[CAPTURE_DEVICE_CAMERA]; if (instance != null) { for (int a = 0, N = groupCall.participants.size(); a < N; a++) { TLRPC.TL_groupCallParticipant participant = groupCall.participants.valueAt(a); if (participant.self || participant.source == 0 || !participant.can_self_unmute && participant.muted) { continue; } if (participant.muted_by_you) { setParticipantVolume(participant, 0); } else { setParticipantVolume(participant, ChatObject.getParticipantVolume(participant)); } } } } public void setParticipantVolume(TLRPC.TL_groupCallParticipant participant, int volume) { tgVoip[CAPTURE_DEVICE_CAMERA].setVolume(participant.source, volume / 10000.0); if (participant.presentation != null && participant.presentation.audio_source != 0) { tgVoip[CAPTURE_DEVICE_CAMERA].setVolume(participant.presentation.audio_source, volume / 10000.0); } } public boolean isSwitchingStream() { return switchingStream; } private void initiateActualEncryptedCall() { if (timeoutRunnable != null) { AndroidUtilities.cancelRunOnUIThread(timeoutRunnable); timeoutRunnable = null; } try { if (BuildVars.LOGS_ENABLED) { FileLog.d("InitCall: keyID=" + keyFingerprint); } SharedPreferences nprefs = MessagesController.getNotificationsSettings(currentAccount); Set<String> set = nprefs.getStringSet("calls_access_hashes", null); HashSet<String> hashes; if (set != null) { hashes = new HashSet<>(set); } else { hashes = new HashSet<>(); } hashes.add(privateCall.id + " " + privateCall.access_hash + " " + System.currentTimeMillis()); while (hashes.size() > 20) { String oldest = null; long oldestTime = Long.MAX_VALUE; Iterator<String> itr = hashes.iterator(); while (itr.hasNext()) { String item = itr.next(); String[] s = item.split(" "); if (s.length < 2) { itr.remove(); } else { try { long t = Long.parseLong(s[2]); if (t < oldestTime) { oldestTime = t; oldest = item; } } catch (Exception x) { itr.remove(); } } } if (oldest != null) { hashes.remove(oldest); } } nprefs.edit().putStringSet("calls_access_hashes", hashes).commit(); boolean sysAecAvailable = false, sysNsAvailable = false; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { try { sysAecAvailable = AcousticEchoCanceler.isAvailable(); } catch (Exception ignored) { } try { sysNsAvailable = NoiseSuppressor.isAvailable(); } catch (Exception ignored) { } } final SharedPreferences preferences = MessagesController.getGlobalMainSettings(); // config final MessagesController messagesController = MessagesController.getInstance(currentAccount); final double initializationTimeout = messagesController.callConnectTimeout / 1000.0; final double receiveTimeout = messagesController.callPacketTimeout / 1000.0; final int voipDataSaving = convertDataSavingMode(preferences.getInt("VoipDataSaving", VoIPHelper.getDataSavingDefault())); final Instance.ServerConfig serverConfig = Instance.getGlobalServerConfig(); final boolean enableAec = !(sysAecAvailable && serverConfig.useSystemAec); final boolean enableNs = !(sysNsAvailable && serverConfig.useSystemNs); final String logFilePath = BuildVars.DEBUG_VERSION ? VoIPHelper.getLogFilePath("voip" + privateCall.id) : VoIPHelper.getLogFilePath(privateCall.id, false); final String statsLogFilePath = VoIPHelper.getLogFilePath(privateCall.id, true); final Instance.Config config = new Instance.Config(initializationTimeout, receiveTimeout, voipDataSaving, privateCall.p2p_allowed, enableAec, enableNs, true, false, serverConfig.enableStunMarking, logFilePath, statsLogFilePath, privateCall.protocol.max_layer); // persistent state final String persistentStateFilePath = new File(ApplicationLoader.applicationContext.getCacheDir(), "voip_persistent_state.json").getAbsolutePath(); // endpoints final boolean forceTcp = preferences.getBoolean("dbg_force_tcp_in_calls", false); final int endpointType = forceTcp ? Instance.ENDPOINT_TYPE_TCP_RELAY : Instance.ENDPOINT_TYPE_UDP_RELAY; final Instance.Endpoint[] endpoints = new Instance.Endpoint[privateCall.connections.size()]; ArrayList<Long> reflectorIds = new ArrayList<>(); for (int i = 0; i < endpoints.length; i++) { final TLRPC.PhoneConnection connection = privateCall.connections.get(i); endpoints[i] = new Instance.Endpoint(connection instanceof TLRPC.TL_phoneConnectionWebrtc, connection.id, connection.ip, connection.ipv6, connection.port, endpointType, connection.peer_tag, connection.turn, connection.stun, connection.username, connection.password, connection.tcp); if (connection instanceof TLRPC.TL_phoneConnection) { reflectorIds.add(((TLRPC.TL_phoneConnection) connection).id); } } if (!reflectorIds.isEmpty()) { Collections.sort(reflectorIds); HashMap<Long, Integer> reflectorIdMapping = new HashMap<>(); for (int i = 0; i < reflectorIds.size(); i++) { reflectorIdMapping.put(reflectorIds.get(i), i + 1); } for (int i = 0; i < endpoints.length; i++) { endpoints[i].reflectorId = reflectorIdMapping.getOrDefault(endpoints[i].id, 0); } } if (forceTcp) { AndroidUtilities.runOnUIThread(() -> Toast.makeText(VoIPService.this, "This call uses TCP which will degrade its quality.", Toast.LENGTH_SHORT).show()); } // proxy Instance.Proxy proxy = null; if (preferences.getBoolean("proxy_enabled", false) && preferences.getBoolean("proxy_enabled_calls", false)) { final String server = preferences.getString("proxy_ip", null); final String secret = preferences.getString("proxy_secret", null); if (!TextUtils.isEmpty(server) && TextUtils.isEmpty(secret)) { proxy = new Instance.Proxy(server, preferences.getInt("proxy_port", 0), preferences.getString("proxy_user", null), preferences.getString("proxy_pass", null)); } } // encryption key final Instance.EncryptionKey encryptionKey = new Instance.EncryptionKey(authKey, isOutgoing); boolean newAvailable = "2.7.7".compareTo(privateCall.protocol.library_versions.get(0)) <= 0; if (captureDevice[CAPTURE_DEVICE_CAMERA] != 0 && !newAvailable) { NativeInstance.destroyVideoCapturer(captureDevice[CAPTURE_DEVICE_CAMERA]); captureDevice[CAPTURE_DEVICE_CAMERA] = 0; videoState[CAPTURE_DEVICE_CAMERA] = Instance.VIDEO_STATE_INACTIVE; } if (!isOutgoing) { if (videoCall && (Build.VERSION.SDK_INT < 23 || checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)) { captureDevice[CAPTURE_DEVICE_CAMERA] = NativeInstance.createVideoCapturer(localSink[CAPTURE_DEVICE_CAMERA], isFrontFaceCamera ? 1 : 0); videoState[CAPTURE_DEVICE_CAMERA] = Instance.VIDEO_STATE_ACTIVE; } else { videoState[CAPTURE_DEVICE_CAMERA] = Instance.VIDEO_STATE_INACTIVE; } } // init tgVoip[CAPTURE_DEVICE_CAMERA] = Instance.makeInstance(privateCall.protocol.library_versions.get(0), config, persistentStateFilePath, endpoints, proxy, getNetworkType(), encryptionKey, remoteSink[CAPTURE_DEVICE_CAMERA], captureDevice[CAPTURE_DEVICE_CAMERA], (uids, levels, voice) -> { if (sharedInstance == null || privateCall == null) { return; } NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.webRtcMicAmplitudeEvent, levels[0]); NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.webRtcSpeakerAmplitudeEvent, levels[1]); }); tgVoip[CAPTURE_DEVICE_CAMERA].setOnStateUpdatedListener(this::onConnectionStateChanged); tgVoip[CAPTURE_DEVICE_CAMERA].setOnSignalBarsUpdatedListener(this::onSignalBarCountChanged); tgVoip[CAPTURE_DEVICE_CAMERA].setOnSignalDataListener(this::onSignalingData); tgVoip[CAPTURE_DEVICE_CAMERA].setOnRemoteMediaStateUpdatedListener((audioState, videoState) -> AndroidUtilities.runOnUIThread(() -> { remoteAudioState = audioState; remoteVideoState = videoState; checkIsNear(); for (int a = 0; a < stateListeners.size(); a++) { StateListener l = stateListeners.get(a); l.onMediaStateUpdated(audioState, videoState); } })); tgVoip[CAPTURE_DEVICE_CAMERA].setMuteMicrophone(micMute); if (newAvailable != isVideoAvailable) { isVideoAvailable = newAvailable; for (int a = 0; a < stateListeners.size(); a++) { StateListener l = stateListeners.get(a); l.onVideoAvailableChange(isVideoAvailable); } } destroyCaptureDevice[CAPTURE_DEVICE_CAMERA] = false; AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { if (tgVoip[CAPTURE_DEVICE_CAMERA] != null) { updateTrafficStats(tgVoip[CAPTURE_DEVICE_CAMERA], null); AndroidUtilities.runOnUIThread(this, 5000); } } }, 5000); } catch (Exception x) { if (BuildVars.LOGS_ENABLED) { FileLog.e("error starting call", x); } callFailed(); } } public void playConnectedSound() { Utilities.globalQueue.postRunnable(() -> soundPool.play(spVoiceChatStartId, 1.0f, 1.0f, 0, 0, 1)); playedConnectedSound = true; } private void startConnectingSound() { Utilities.globalQueue.postRunnable(() -> { if (spPlayId != 0) { soundPool.stop(spPlayId); } spPlayId = soundPool.play(spConnectingId, 1, 1, 0, -1, 1); if (spPlayId == 0) { AndroidUtilities.runOnUIThread(connectingSoundRunnable = new Runnable() { @Override public void run() { if (sharedInstance == null) { return; } Utilities.globalQueue.postRunnable(() -> { if (spPlayId == 0) { spPlayId = soundPool.play(spConnectingId, 1, 1, 0, -1, 1); } if (spPlayId == 0) { AndroidUtilities.runOnUIThread(this, 100); } else { connectingSoundRunnable = null; } }); } }, 100); } }); } public void onSignalingData(byte[] data) { if (privateCall == null) { return; } TLRPC.TL_phone_sendSignalingData req = new TLRPC.TL_phone_sendSignalingData(); req.peer = new TLRPC.TL_inputPhoneCall(); req.peer.access_hash = privateCall.access_hash; req.peer.id = privateCall.id; req.data = data; ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> { }); } public boolean isVideoAvailable() { return isVideoAvailable; } void onMediaButtonEvent(KeyEvent ev) { if (ev == null) { return; } if (ev.getKeyCode() == KeyEvent.KEYCODE_HEADSETHOOK || ev.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PAUSE || ev.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) { if (ev.getAction() == KeyEvent.ACTION_UP) { if (currentState == STATE_WAITING_INCOMING) { acceptIncomingCall(); } else { setMicMute(!isMicMute(), false, true); } } } } public byte[] getGA() { return g_a; } public void forceRating() { forceRating = true; } private String[] getEmoji() { ByteArrayOutputStream os = new ByteArrayOutputStream(); try { os.write(authKey); os.write(g_a); } catch (IOException ignore) { } return EncryptionKeyEmojifier.emojifyForCall(Utilities.computeSHA256(os.toByteArray(), 0, os.size())); } public boolean hasEarpiece() { if (USE_CONNECTION_SERVICE) { if (systemCallConnection != null && systemCallConnection.getCallAudioState() != null) { int routeMask = systemCallConnection.getCallAudioState().getSupportedRouteMask(); return (routeMask & (CallAudioState.ROUTE_EARPIECE | CallAudioState.ROUTE_WIRED_HEADSET)) != 0; } } if (((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getPhoneType() != TelephonyManager.PHONE_TYPE_NONE) { return true; } if (mHasEarpiece != null) { return mHasEarpiece; } // not calculated yet, do it now try { AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); Method method = AudioManager.class.getMethod("getDevicesForStream", Integer.TYPE); Field field = AudioManager.class.getField("DEVICE_OUT_EARPIECE"); int earpieceFlag = field.getInt(null); int bitmaskResult = (int) method.invoke(am, AudioManager.STREAM_VOICE_CALL); // check if masked by the earpiece flag if ((bitmaskResult & earpieceFlag) == earpieceFlag) { mHasEarpiece = Boolean.TRUE; } else { mHasEarpiece = Boolean.FALSE; } } catch (Throwable error) { if (BuildVars.LOGS_ENABLED) { FileLog.e("Error while checking earpiece! ", error); } mHasEarpiece = Boolean.TRUE; } return mHasEarpiece; } private int getStatsNetworkType() { int netType = StatsController.TYPE_WIFI; if (lastNetInfo != null) { if (lastNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) { netType = lastNetInfo.isRoaming() ? StatsController.TYPE_ROAMING : StatsController.TYPE_MOBILE; } } return netType; } protected void setSwitchingCamera(boolean switching, boolean isFrontFace) { switchingCamera = switching; if (!switching) { isFrontFaceCamera = isFrontFace; for (int a = 0; a < stateListeners.size(); a++) { StateListener l = stateListeners.get(a); l.onCameraSwitch(isFrontFaceCamera); } } } protected void onCameraFirstFrameAvailable() { for (int a = 0; a < stateListeners.size(); a++) { StateListener l = stateListeners.get(a); l.onCameraFirstFrameAvailable(); } } public void registerStateListener(StateListener l) { if (stateListeners.contains(l)) { return; } stateListeners.add(l); if (currentState != 0) { l.onStateChanged(currentState); } if (signalBarCount != 0) { l.onSignalBarsCountChanged(signalBarCount); } } public void unregisterStateListener(StateListener l) { stateListeners.remove(l); } public void editCallMember(TLObject object, Boolean mute, Boolean muteVideo, Integer volume, Boolean raiseHand, Runnable onComplete) { if (object == null || groupCall == null) { return; } TLRPC.TL_phone_editGroupCallParticipant req = new TLRPC.TL_phone_editGroupCallParticipant(); req.call = groupCall.getInputGroupCall(); if (object instanceof TLRPC.User) { TLRPC.User user = (TLRPC.User) object; if (UserObject.isUserSelf(user) && groupCallPeer != null) { req.participant = groupCallPeer; } else { req.participant = MessagesController.getInputPeer(user); if (BuildVars.LOGS_ENABLED) { FileLog.d("edit group call part id = " + req.participant.user_id + " access_hash = " + req.participant.user_id); } } } else if (object instanceof TLRPC.Chat) { TLRPC.Chat chat = (TLRPC.Chat) object; req.participant = MessagesController.getInputPeer(chat); if (BuildVars.LOGS_ENABLED) { FileLog.d("edit group call part id = " + (req.participant.chat_id != 0 ? req.participant.chat_id : req.participant.channel_id) + " access_hash = " + req.participant.access_hash); } } if (mute != null) { req.muted = mute; req.flags |= 1; } if (volume != null) { req.volume = volume; req.flags |= 2; } if (raiseHand != null) { req.raise_hand = raiseHand; req.flags |= 4; } if (muteVideo != null) { req.video_stopped = muteVideo; req.flags |= 8; } if (BuildVars.LOGS_ENABLED) { FileLog.d("edit group call flags = " + req.flags); } int account = currentAccount; AccountInstance.getInstance(account).getConnectionsManager().sendRequest(req, (response, error) -> { if (response != null) { AccountInstance.getInstance(account).getMessagesController().processUpdates((TLRPC.Updates) response, false); } else if (error != null) { if ("GROUPCALL_VIDEO_TOO_MUCH".equals(error.text)) { groupCall.reloadGroupCall(); } } if (onComplete != null) { AndroidUtilities.runOnUIThread(onComplete); } }); } public boolean isMicMute() { return micMute; } public void toggleSpeakerphoneOrShowRouteSheet(Context context, boolean fromOverlayWindow) { if (isBluetoothHeadsetConnected() && hasEarpiece()) { BottomSheet.Builder builder = new BottomSheet.Builder(context) .setTitle(LocaleController.getString("VoipOutputDevices", R.string.VoipOutputDevices), true) .setItems(new CharSequence[]{ LocaleController.getString("VoipAudioRoutingSpeaker", R.string.VoipAudioRoutingSpeaker), isHeadsetPlugged ? LocaleController.getString("VoipAudioRoutingHeadset", R.string.VoipAudioRoutingHeadset) : LocaleController.getString("VoipAudioRoutingEarpiece", R.string.VoipAudioRoutingEarpiece), currentBluetoothDeviceName != null ? currentBluetoothDeviceName : LocaleController.getString("VoipAudioRoutingBluetooth", R.string.VoipAudioRoutingBluetooth)}, new int[]{R.drawable.calls_menu_speaker, isHeadsetPlugged ? R.drawable.calls_menu_headset : R.drawable.calls_menu_phone, R.drawable.calls_menu_bluetooth}, (dialog, which) -> { if (getSharedInstance() == null) { return; } setAudioOutput(which); }); BottomSheet bottomSheet = builder.create(); if (fromOverlayWindow) { if (Build.VERSION.SDK_INT >= 26) { bottomSheet.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY); } else { bottomSheet.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); } } builder.show(); return; } if (USE_CONNECTION_SERVICE && systemCallConnection != null && systemCallConnection.getCallAudioState() != null) { if (hasEarpiece()) { systemCallConnection.setAudioRoute(systemCallConnection.getCallAudioState().getRoute() == CallAudioState.ROUTE_SPEAKER ? CallAudioState.ROUTE_WIRED_OR_EARPIECE : CallAudioState.ROUTE_SPEAKER); } else { systemCallConnection.setAudioRoute(systemCallConnection.getCallAudioState().getRoute() == CallAudioState.ROUTE_BLUETOOTH ? CallAudioState.ROUTE_WIRED_OR_EARPIECE : CallAudioState.ROUTE_BLUETOOTH); } } else if (audioConfigured && !USE_CONNECTION_SERVICE) { AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); if (hasEarpiece()) { am.setSpeakerphoneOn(!am.isSpeakerphoneOn()); } else { am.setBluetoothScoOn(!am.isBluetoothScoOn()); } updateOutputGainControlState(); } else { speakerphoneStateToSet = !speakerphoneStateToSet; } for (StateListener l : stateListeners) { l.onAudioSettingsChanged(); } } public void setAudioOutput(int which) { if (BuildVars.LOGS_ENABLED) { FileLog.d("setAudioOutput " + which); } AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); if (USE_CONNECTION_SERVICE && systemCallConnection != null) { switch (which) { case 2: systemCallConnection.setAudioRoute(CallAudioState.ROUTE_BLUETOOTH); break; case 1: systemCallConnection.setAudioRoute(CallAudioState.ROUTE_WIRED_OR_EARPIECE); break; case 0: systemCallConnection.setAudioRoute(CallAudioState.ROUTE_SPEAKER); break; } } else if (audioConfigured && !USE_CONNECTION_SERVICE) { switch (which) { case 2: if (!bluetoothScoActive) { needSwitchToBluetoothAfterScoActivates = true; try { am.startBluetoothSco(); } catch (Throwable e) { FileLog.e(e); } } else { am.setBluetoothScoOn(true); am.setSpeakerphoneOn(false); } audioRouteToSet = AUDIO_ROUTE_BLUETOOTH; break; case 1: needSwitchToBluetoothAfterScoActivates = false; if (bluetoothScoActive || bluetoothScoConnecting) { am.stopBluetoothSco(); bluetoothScoActive = false; bluetoothScoConnecting = false; } am.setSpeakerphoneOn(false); am.setBluetoothScoOn(false); audioRouteToSet = AUDIO_ROUTE_EARPIECE; break; case 0: needSwitchToBluetoothAfterScoActivates = false; if (bluetoothScoActive || bluetoothScoConnecting) { am.stopBluetoothSco(); bluetoothScoActive = false; bluetoothScoConnecting = false; } am.setBluetoothScoOn(false); am.setSpeakerphoneOn(true); audioRouteToSet = AUDIO_ROUTE_SPEAKER; break; } updateOutputGainControlState(); } else { switch (which) { case 2: audioRouteToSet = AUDIO_ROUTE_BLUETOOTH; speakerphoneStateToSet = false; break; case 1: audioRouteToSet = AUDIO_ROUTE_EARPIECE; speakerphoneStateToSet = false; break; case 0: audioRouteToSet = AUDIO_ROUTE_SPEAKER; speakerphoneStateToSet = true; break; } } for (StateListener l : stateListeners) { l.onAudioSettingsChanged(); } } public boolean isSpeakerphoneOn() { if (USE_CONNECTION_SERVICE && systemCallConnection != null && systemCallConnection.getCallAudioState() != null) { int route = systemCallConnection.getCallAudioState().getRoute(); return hasEarpiece() ? route == CallAudioState.ROUTE_SPEAKER : route == CallAudioState.ROUTE_BLUETOOTH; } else if (audioConfigured && !USE_CONNECTION_SERVICE) { AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); return hasEarpiece() ? am.isSpeakerphoneOn() : am.isBluetoothScoOn(); } return speakerphoneStateToSet; } public int getCurrentAudioRoute() { if (USE_CONNECTION_SERVICE) { if (systemCallConnection != null && systemCallConnection.getCallAudioState() != null) { switch (systemCallConnection.getCallAudioState().getRoute()) { case CallAudioState.ROUTE_BLUETOOTH: return AUDIO_ROUTE_BLUETOOTH; case CallAudioState.ROUTE_EARPIECE: case CallAudioState.ROUTE_WIRED_HEADSET: return AUDIO_ROUTE_EARPIECE; case CallAudioState.ROUTE_SPEAKER: return AUDIO_ROUTE_SPEAKER; } } return audioRouteToSet; } if (audioConfigured) { AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); if (am.isBluetoothScoOn()) { return AUDIO_ROUTE_BLUETOOTH; } else if (am.isSpeakerphoneOn()) { return AUDIO_ROUTE_SPEAKER; } else { return AUDIO_ROUTE_EARPIECE; } } return audioRouteToSet; } public String getDebugString() { return tgVoip[CAPTURE_DEVICE_CAMERA] != null ? tgVoip[CAPTURE_DEVICE_CAMERA].getDebugInfo() : ""; } public long getCallDuration() { if (callStartTime == 0) { return 0; } return SystemClock.elapsedRealtime() - callStartTime; } public void stopRinging() { if (ringtonePlayer != null) { ringtonePlayer.stop(); ringtonePlayer.release(); ringtonePlayer = null; } if (vibrator != null) { vibrator.cancel(); vibrator = null; } } private void showNotification(String name, Bitmap photo) { Intent intent = new Intent(this, LaunchActivity.class).setAction(groupCall != null ? "voip_chat" : "voip"); if (groupCall != null) { intent.putExtra("currentAccount", currentAccount); } Notification.Builder builder = new Notification.Builder(this) .setContentText(name) .setContentIntent(PendingIntent.getActivity(this, 50, intent, PendingIntent.FLAG_MUTABLE)); if (groupCall != null) { builder.setContentTitle(ChatObject.isChannelOrGiga(chat) ? LocaleController.getString("VoipLiveStream", R.string.VoipLiveStream) : LocaleController.getString("VoipVoiceChat", R.string.VoipVoiceChat)); builder.setSmallIcon(isMicMute() ? R.drawable.voicechat_muted : R.drawable.voicechat_active); } else { builder.setContentTitle(LocaleController.getString("VoipOutgoingCall", R.string.VoipOutgoingCall)); builder.setSmallIcon(R.drawable.notification); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { Intent endIntent = new Intent(this, VoIPActionsReceiver.class); endIntent.setAction(getPackageName() + ".END_CALL"); if (groupCall != null) { builder.addAction(R.drawable.ic_call_end_white_24dp, ChatObject.isChannelOrGiga(chat) ? LocaleController.getString("VoipChannelLeaveAlertTitle", R.string.VoipChannelLeaveAlertTitle) : LocaleController.getString("VoipGroupLeaveAlertTitle", R.string.VoipGroupLeaveAlertTitle), PendingIntent.getBroadcast(this, 0, endIntent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT)); } else { builder.addAction(R.drawable.ic_call_end_white_24dp, LocaleController.getString("VoipEndCall", R.string.VoipEndCall), PendingIntent.getBroadcast(this, 0, endIntent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT)); } builder.setPriority(Notification.PRIORITY_MAX); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { builder.setShowWhen(false); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { builder.setColor(0xff282e31); builder.setColorized(true); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { builder.setColor(0xff2ca5e0); } if (Build.VERSION.SDK_INT >= 26) { NotificationsController.checkOtherNotificationsChannel(); builder.setChannelId(NotificationsController.OTHER_NOTIFICATIONS_CHANNEL); } if (photo != null) { builder.setLargeIcon(photo); } try { startForeground(ID_ONGOING_CALL_NOTIFICATION, builder.getNotification()); } catch (Exception e) { if (photo != null && e instanceof IllegalArgumentException) { showNotification(name, null); } } } private void startRingtoneAndVibration(long chatID) { SharedPreferences prefs = MessagesController.getNotificationsSettings(currentAccount); AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); boolean needRing = am.getRingerMode() != AudioManager.RINGER_MODE_SILENT; if (needRing) { ringtonePlayer = new MediaPlayer(); ringtonePlayer.setOnPreparedListener(mediaPlayer -> { try { ringtonePlayer.start(); } catch (Throwable e) { FileLog.e(e); } }); ringtonePlayer.setLooping(true); if (isHeadsetPlugged) { ringtonePlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL); } else { ringtonePlayer.setAudioStreamType(AudioManager.STREAM_RING); if (!USE_CONNECTION_SERVICE) { am.requestAudioFocus(this, AudioManager.STREAM_RING, AudioManager.AUDIOFOCUS_GAIN); } } try { String notificationUri; if (prefs.getBoolean("custom_" + chatID, false)) { notificationUri = prefs.getString("ringtone_path_" + chatID, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE).toString()); } else { notificationUri = prefs.getString("CallsRingtonePath", RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE).toString()); } ringtonePlayer.setDataSource(this, Uri.parse(notificationUri)); ringtonePlayer.prepareAsync(); } catch (Exception e) { FileLog.e(e); if (ringtonePlayer != null) { ringtonePlayer.release(); ringtonePlayer = null; } } int vibrate; if (prefs.getBoolean("custom_" + chatID, false)) { vibrate = prefs.getInt("calls_vibrate_" + chatID, 0); } else { vibrate = prefs.getInt("vibrate_calls", 0); } if ((vibrate != 2 && vibrate != 4 && (am.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE || am.getRingerMode() == AudioManager.RINGER_MODE_NORMAL)) || (vibrate == 4 && am.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE)) { vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); long duration = 700; if (vibrate == 1) { duration /= 2; } else if (vibrate == 3) { duration *= 2; } vibrator.vibrate(new long[]{0, duration, 500}, 0); } } } @Override public void onDestroy() { if (BuildVars.LOGS_ENABLED) { FileLog.d("=============== VoIPService STOPPING ==============="); } stopForeground(true); stopRinging(); if (currentAccount >= 0) { if (ApplicationLoader.mainInterfacePaused || !ApplicationLoader.isScreenOn) { MessagesController.getInstance(currentAccount).ignoreSetOnline = false; } NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.appDidLogout); } SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE); Sensor proximity = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY); if (proximity != null) { sm.unregisterListener(this); } if (proximityWakelock != null && proximityWakelock.isHeld()) { proximityWakelock.release(); } if (updateNotificationRunnable != null) { Utilities.globalQueue.cancelRunnable(updateNotificationRunnable); updateNotificationRunnable = null; } if (switchingStreamTimeoutRunnable != null) { AndroidUtilities.cancelRunOnUIThread(switchingStreamTimeoutRunnable); switchingStreamTimeoutRunnable = null; } unregisterReceiver(receiver); if (timeoutRunnable != null) { AndroidUtilities.cancelRunOnUIThread(timeoutRunnable); timeoutRunnable = null; } super.onDestroy(); sharedInstance = null; Arrays.fill(mySource, 0); cancelGroupCheckShortPoll(); AndroidUtilities.runOnUIThread(() -> NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.didEndCall)); if (tgVoip[CAPTURE_DEVICE_CAMERA] != null) { StatsController.getInstance(currentAccount).incrementTotalCallsTime(getStatsNetworkType(), (int) (getCallDuration() / 1000) % 5); onTgVoipPreStop(); if (tgVoip[CAPTURE_DEVICE_CAMERA].isGroup()) { NativeInstance instance = tgVoip[CAPTURE_DEVICE_CAMERA]; Utilities.globalQueue.postRunnable(instance::stopGroup); for (HashMap.Entry<String, Integer> entry : currentStreamRequestTimestamp.entrySet()) { AccountInstance.getInstance(currentAccount).getConnectionsManager().cancelRequest(entry.getValue(), true); } currentStreamRequestTimestamp.clear(); } else { Instance.FinalState state = tgVoip[CAPTURE_DEVICE_CAMERA].stop(); updateTrafficStats(tgVoip[CAPTURE_DEVICE_CAMERA], state.trafficStats); onTgVoipStop(state); } prevTrafficStats = null; callStartTime = 0; tgVoip[CAPTURE_DEVICE_CAMERA] = null; Instance.destroyInstance(); } if (tgVoip[CAPTURE_DEVICE_SCREEN] != null) { NativeInstance instance = tgVoip[CAPTURE_DEVICE_SCREEN]; Utilities.globalQueue.postRunnable(instance::stopGroup); tgVoip[CAPTURE_DEVICE_SCREEN] = null; } for (int a = 0; a < captureDevice.length; a++) { if (captureDevice[a] != 0) { if (destroyCaptureDevice[a]) { NativeInstance.destroyVideoCapturer(captureDevice[a]); } captureDevice[a] = 0; } } cpuWakelock.release(); if (!playingSound) { AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); if (!USE_CONNECTION_SERVICE) { if (isBtHeadsetConnected || bluetoothScoActive || bluetoothScoConnecting) { am.stopBluetoothSco(); am.setBluetoothScoOn(false); am.setSpeakerphoneOn(false); bluetoothScoActive = false; bluetoothScoConnecting = false; } if (onDestroyRunnable == null) { Utilities.globalQueue.postRunnable(setModeRunnable = () -> { synchronized (sync) { if (setModeRunnable == null) { return; } setModeRunnable = null; } try { am.setMode(AudioManager.MODE_NORMAL); } catch (SecurityException x) { if (BuildVars.LOGS_ENABLED) { FileLog.e("Error setting audio more to normal", x); } } }); } am.abandonAudioFocus(this); } try { am.unregisterMediaButtonEventReceiver(new ComponentName(this, VoIPMediaButtonReceiver.class)); } catch (Exception e) { FileLog.e(e); } if (audioDeviceCallback != null) { am.unregisterAudioDeviceCallback(audioDeviceCallback); } if (hasAudioFocus) { am.abandonAudioFocus(this); } Utilities.globalQueue.postRunnable(() -> soundPool.release()); } if (USE_CONNECTION_SERVICE) { if (!didDeleteConnectionServiceContact) { ContactsController.getInstance(currentAccount).deleteConnectionServiceContact(); } if (systemCallConnection != null && !playingSound) { systemCallConnection.destroy(); } } VoIPHelper.lastCallTime = SystemClock.elapsedRealtime(); setSinks(null, null); if (onDestroyRunnable != null) { onDestroyRunnable.run(); } if (currentAccount >= 0) { ConnectionsManager.getInstance(currentAccount).setAppPaused(true, false); if (ChatObject.isChannel(chat)) { MessagesController.getInstance(currentAccount).startShortPoll(chat, classGuid, true); } } } public long getCallID() { return privateCall != null ? privateCall.id : 0; } public void hangUp() { hangUp(0, null); } public void hangUp(int discard) { hangUp(discard, null); } public void hangUp(Runnable onDone) { hangUp(0, onDone); } public void acceptIncomingCall() { MessagesController.getInstance(currentAccount).ignoreSetOnline = false; stopRinging(); showNotification(); configureDeviceForCall(); startConnectingSound(); dispatchStateChanged(STATE_EXCHANGING_KEYS); AndroidUtilities.runOnUIThread(() -> NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.didStartedCall)); final MessagesStorage messagesStorage = MessagesStorage.getInstance(currentAccount); TLRPC.TL_messages_getDhConfig req = new TLRPC.TL_messages_getDhConfig(); req.random_length = 256; req.version = messagesStorage.getLastSecretVersion(); ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> { if (error == null) { TLRPC.messages_DhConfig res = (TLRPC.messages_DhConfig) response; if (response instanceof TLRPC.TL_messages_dhConfig) { if (!Utilities.isGoodPrime(res.p, res.g)) { if (BuildVars.LOGS_ENABLED) { FileLog.e("stopping VoIP service, bad prime"); } callFailed(); return; } messagesStorage.setSecretPBytes(res.p); messagesStorage.setSecretG(res.g); messagesStorage.setLastSecretVersion(res.version); MessagesStorage.getInstance(currentAccount).saveSecretParams(messagesStorage.getLastSecretVersion(), messagesStorage.getSecretG(), messagesStorage.getSecretPBytes()); } byte[] salt = new byte[256]; for (int a = 0; a < 256; a++) { salt[a] = (byte) ((byte) (Utilities.random.nextDouble() * 256) ^ res.random[a]); } if (privateCall == null) { if (BuildVars.LOGS_ENABLED) { FileLog.e("call is null"); } callFailed(); return; } a_or_b = salt; BigInteger g_b = BigInteger.valueOf(messagesStorage.getSecretG()); BigInteger p = new BigInteger(1, messagesStorage.getSecretPBytes()); g_b = g_b.modPow(new BigInteger(1, salt), p); g_a_hash = privateCall.g_a_hash; byte[] g_b_bytes = g_b.toByteArray(); if (g_b_bytes.length > 256) { byte[] correctedAuth = new byte[256]; System.arraycopy(g_b_bytes, 1, correctedAuth, 0, 256); g_b_bytes = correctedAuth; } TLRPC.TL_phone_acceptCall req1 = new TLRPC.TL_phone_acceptCall(); req1.g_b = g_b_bytes; req1.peer = new TLRPC.TL_inputPhoneCall(); req1.peer.id = privateCall.id; req1.peer.access_hash = privateCall.access_hash; req1.protocol = new TLRPC.TL_phoneCallProtocol(); req1.protocol.udp_p2p = req1.protocol.udp_reflector = true; req1.protocol.min_layer = CALL_MIN_LAYER; req1.protocol.max_layer = Instance.getConnectionMaxLayer(); req1.protocol.library_versions.addAll(Instance.AVAILABLE_VERSIONS); ConnectionsManager.getInstance(currentAccount).sendRequest(req1, (response1, error1) -> AndroidUtilities.runOnUIThread(() -> { if (error1 == null) { if (BuildVars.LOGS_ENABLED) { FileLog.w("accept call ok! " + response1); } privateCall = ((TLRPC.TL_phone_phoneCall) response1).phone_call; if (privateCall instanceof TLRPC.TL_phoneCallDiscarded) { onCallUpdated(privateCall); } } else { if (BuildVars.LOGS_ENABLED) { FileLog.e("Error on phone.acceptCall: " + error1); } callFailed(); } }), ConnectionsManager.RequestFlagFailOnServerErrors); } else { callFailed(); } }); } public void declineIncomingCall(int reason, final Runnable onDone) { stopRinging(); callDiscardReason = reason; if (currentState == STATE_REQUESTING) { if (delayedStartOutgoingCall != null) { AndroidUtilities.cancelRunOnUIThread(delayedStartOutgoingCall); callEnded(); } else { dispatchStateChanged(STATE_HANGING_UP); endCallAfterRequest = true; AndroidUtilities.runOnUIThread(() -> { if (currentState == STATE_HANGING_UP) { callEnded(); } }, 5000); } return; } if (currentState == STATE_HANGING_UP || currentState == STATE_ENDED) { return; } dispatchStateChanged(STATE_HANGING_UP); if (privateCall == null) { onDestroyRunnable = onDone; callEnded(); if (callReqId != 0) { ConnectionsManager.getInstance(currentAccount).cancelRequest(callReqId, false); callReqId = 0; } return; } TLRPC.TL_phone_discardCall req = new TLRPC.TL_phone_discardCall(); req.peer = new TLRPC.TL_inputPhoneCall(); req.peer.access_hash = privateCall.access_hash; req.peer.id = privateCall.id; req.duration = (int) (getCallDuration() / 1000); req.connection_id = tgVoip[CAPTURE_DEVICE_CAMERA] != null ? tgVoip[CAPTURE_DEVICE_CAMERA].getPreferredRelayId() : 0; switch (reason) { case DISCARD_REASON_DISCONNECT: req.reason = new TLRPC.TL_phoneCallDiscardReasonDisconnect(); break; case DISCARD_REASON_MISSED: req.reason = new TLRPC.TL_phoneCallDiscardReasonMissed(); break; case DISCARD_REASON_LINE_BUSY: req.reason = new TLRPC.TL_phoneCallDiscardReasonBusy(); break; case DISCARD_REASON_HANGUP: default: req.reason = new TLRPC.TL_phoneCallDiscardReasonHangup(); break; } ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> { if (error != null) { if (BuildVars.LOGS_ENABLED) { FileLog.e("error on phone.discardCall: " + error); } } else { if (response instanceof TLRPC.TL_updates) { TLRPC.TL_updates updates = (TLRPC.TL_updates) response; MessagesController.getInstance(currentAccount).processUpdates(updates, false); } if (BuildVars.LOGS_ENABLED) { FileLog.d("phone.discardCall " + response); } } }, ConnectionsManager.RequestFlagFailOnServerErrors); onDestroyRunnable = onDone; callEnded(); } public void declineIncomingCall() { declineIncomingCall(DISCARD_REASON_HANGUP, null); } private Class<? extends Activity> getUIActivityClass() { return LaunchActivity.class; } @TargetApi(Build.VERSION_CODES.O) public CallConnection getConnectionAndStartCall() { if (systemCallConnection == null) { if (BuildVars.LOGS_ENABLED) { FileLog.d("creating call connection"); } systemCallConnection = new CallConnection(); systemCallConnection.setInitializing(); if (isOutgoing) { delayedStartOutgoingCall = () -> { delayedStartOutgoingCall = null; startOutgoingCall(); }; AndroidUtilities.runOnUIThread(delayedStartOutgoingCall, 2000); } systemCallConnection.setAddress(Uri.fromParts("tel", "+99084" + user.id, null), TelecomManager.PRESENTATION_ALLOWED); systemCallConnection.setCallerDisplayName(ContactsController.formatName(user.first_name, user.last_name), TelecomManager.PRESENTATION_ALLOWED); } return systemCallConnection; } private void startRinging() { if (currentState == STATE_WAITING_INCOMING) { return; } if (USE_CONNECTION_SERVICE && systemCallConnection != null) { systemCallConnection.setRinging(); } if (BuildVars.LOGS_ENABLED) { FileLog.d("starting ringing for call " + privateCall.id); } dispatchStateChanged(STATE_WAITING_INCOMING); if (!notificationsDisabled && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { showIncomingNotification(ContactsController.formatName(user.first_name, user.last_name), null, user, privateCall.video, 0); if (BuildVars.LOGS_ENABLED) { FileLog.d("Showing incoming call notification"); } } else { startRingtoneAndVibration(user.id); if (BuildVars.LOGS_ENABLED) { FileLog.d("Starting incall activity for incoming call"); } try { PendingIntent.getActivity(VoIPService.this, 12345, new Intent(VoIPService.this, LaunchActivity.class).setAction("voip"), PendingIntent.FLAG_MUTABLE).send(); } catch (Exception x) { if (BuildVars.LOGS_ENABLED) { FileLog.e("Error starting incall activity", x); } } } } public void startRingtoneAndVibration() { if (!startedRinging) { startRingtoneAndVibration(user.id); startedRinging = true; } } private void updateServerConfig() { final SharedPreferences preferences = MessagesController.getMainSettings(currentAccount); Instance.setGlobalServerConfig(preferences.getString("voip_server_config", "{}")); ConnectionsManager.getInstance(currentAccount).sendRequest(new TLRPC.TL_phone_getCallConfig(), (response, error) -> { if (error == null) { String data = ((TLRPC.TL_dataJSON) response).data; Instance.setGlobalServerConfig(data); preferences.edit().putString("voip_server_config", data).commit(); } }); } private void showNotification() { if (user != null) { showNotification(ContactsController.formatName(user.first_name, user.last_name), getRoundAvatarBitmap(user)); } else { showNotification(chat.title, getRoundAvatarBitmap(chat)); } } private void onTgVoipPreStop() { /*if(BuildConfig.DEBUG){ String debugLog=controller.getDebugLog(); TLRPC.TL_phone_saveCallDebug req=new TLRPC.TL_phone_saveCallDebug(); req.debug=new TLRPC.TL_dataJSON(); req.debug.data=debugLog; req.peer=new TLRPC.TL_inputPhoneCall(); req.peer.access_hash=call.access_hash; req.peer.id=call.id; ConnectionsManager.getInstance(currentAccount).sendRequest(req, new RequestDelegate(){ @Override public void run(TLObject response, TLRPC.TL_error error){ if (BuildVars.LOGS_ENABLED) { FileLog.d("Sent debug logs, response=" + response); } } }); }*/ } public static String convertStreamToString(InputStream is) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } reader.close(); return sb.toString(); } public static String getStringFromFile(String filePath) throws Exception { File fl = new File(filePath); FileInputStream fin = new FileInputStream(fl); String ret = convertStreamToString(fin); fin.close(); return ret; } private void onTgVoipStop(Instance.FinalState finalState) { if (user == null) { return; } if (TextUtils.isEmpty(finalState.debugLog)) { try { finalState.debugLog = getStringFromFile(VoIPHelper.getLogFilePath(privateCall.id, true)); } catch (Exception e) { e.printStackTrace(); } } if (needRateCall || forceRating || finalState.isRatingSuggested) { startRatingActivity(); needRateCall = false; } if (needSendDebugLog && finalState.debugLog != null) { TLRPC.TL_phone_saveCallDebug req = new TLRPC.TL_phone_saveCallDebug(); req.debug = new TLRPC.TL_dataJSON(); req.debug.data = finalState.debugLog; req.peer = new TLRPC.TL_inputPhoneCall(); req.peer.access_hash = privateCall.access_hash; req.peer.id = privateCall.id; ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> { if (BuildVars.LOGS_ENABLED) { FileLog.d("Sent debug logs, response = " + response); } }); needSendDebugLog = false; } } private void initializeAccountRelatedThings() { updateServerConfig(); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.appDidLogout); ConnectionsManager.getInstance(currentAccount).setAppPaused(false, false); } @SuppressLint("InvalidWakeLockTag") @Override public void onCreate() { super.onCreate(); if (BuildVars.LOGS_ENABLED) { FileLog.d("=============== VoIPService STARTING ==============="); } try { AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER) != null) { int outFramesPerBuffer = Integer.parseInt(am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER)); Instance.setBufferSize(outFramesPerBuffer); } else { Instance.setBufferSize(AudioTrack.getMinBufferSize(48000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT) / 2); } cpuWakelock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "telegram-voip"); cpuWakelock.acquire(); btAdapter = am.isBluetoothScoAvailableOffCall() ? BluetoothAdapter.getDefaultAdapter() : null; IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); if (!USE_CONNECTION_SERVICE) { filter.addAction(ACTION_HEADSET_PLUG); if (btAdapter != null) { filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED); filter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED); } filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); } registerReceiver(receiver, filter); fetchBluetoothDeviceName(); if (audioDeviceCallback == null) { try { audioDeviceCallback = new AudioDeviceCallback() { @Override public void onAudioDevicesAdded(AudioDeviceInfo[] addedDevices) { checkUpdateBluetoothHeadset(); } @Override public void onAudioDevicesRemoved(AudioDeviceInfo[] removedDevices) { checkUpdateBluetoothHeadset(); } }; } catch (Throwable e) { //java.lang.NoClassDefFoundError on some devices FileLog.e(e); audioDeviceCallback = null; } } if (audioDeviceCallback != null) { am.registerAudioDeviceCallback(audioDeviceCallback, new Handler(Looper.getMainLooper())); } am.registerMediaButtonEventReceiver(new ComponentName(this, VoIPMediaButtonReceiver.class)); checkUpdateBluetoothHeadset(); } catch (Exception x) { if (BuildVars.LOGS_ENABLED) { FileLog.e("error initializing voip controller", x); } callFailed(); } if (callIShouldHavePutIntoIntent != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationsController.checkOtherNotificationsChannel(); Notification.Builder bldr = new Notification.Builder(this, NotificationsController.OTHER_NOTIFICATIONS_CHANNEL) .setContentTitle(LocaleController.getString("VoipOutgoingCall", R.string.VoipOutgoingCall)) .setShowWhen(false); if (groupCall != null) { bldr.setSmallIcon(isMicMute() ? R.drawable.voicechat_muted : R.drawable.voicechat_active); } else { bldr.setSmallIcon(R.drawable.notification); } startForeground(ID_ONGOING_CALL_NOTIFICATION, bldr.build()); } } private void checkUpdateBluetoothHeadset() { if (!USE_CONNECTION_SERVICE && btAdapter != null && btAdapter.isEnabled()) { try { MediaRouter mr = (MediaRouter) getSystemService(Context.MEDIA_ROUTER_SERVICE); if (Build.VERSION.SDK_INT < 24) { int headsetState = btAdapter.getProfileConnectionState(BluetoothProfile.HEADSET); updateBluetoothHeadsetState(headsetState == BluetoothProfile.STATE_CONNECTED); for (StateListener l : stateListeners) { l.onAudioSettingsChanged(); } } else { MediaRouter.RouteInfo ri = mr.getSelectedRoute(MediaRouter.ROUTE_TYPE_LIVE_AUDIO); if (ri.getDeviceType() == MediaRouter.RouteInfo.DEVICE_TYPE_BLUETOOTH) { int headsetState = btAdapter.getProfileConnectionState(BluetoothProfile.HEADSET); updateBluetoothHeadsetState(headsetState == BluetoothProfile.STATE_CONNECTED); for (StateListener l : stateListeners) { l.onAudioSettingsChanged(); } } else { updateBluetoothHeadsetState(false); } } } catch (Throwable e) { FileLog.e(e); } } } private void loadResources() { if (Build.VERSION.SDK_INT >= 21) { WebRtcAudioTrack.setAudioTrackUsageAttribute(AudioAttributes.USAGE_VOICE_COMMUNICATION); } Utilities.globalQueue.postRunnable(() -> { soundPool = new SoundPool(1, AudioManager.STREAM_VOICE_CALL, 0); spConnectingId = soundPool.load(this, R.raw.voip_connecting, 1); spRingbackID = soundPool.load(this, R.raw.voip_ringback, 1); spFailedID = soundPool.load(this, R.raw.voip_failed, 1); spEndId = soundPool.load(this, R.raw.voip_end, 1); spBusyId = soundPool.load(this, R.raw.voip_busy, 1); spVoiceChatEndId = soundPool.load(this, R.raw.voicechat_leave, 1); spVoiceChatStartId = soundPool.load(this, R.raw.voicechat_join, 1); spVoiceChatConnecting = soundPool.load(this, R.raw.voicechat_connecting, 1); spAllowTalkId = soundPool.load(this, R.raw.voip_onallowtalk, 1); spStartRecordId = soundPool.load(this, R.raw.voip_recordstart, 1); }); } private void dispatchStateChanged(int state) { if (BuildVars.LOGS_ENABLED) { FileLog.d("== Call " + getCallID() + " state changed to " + state + " =="); } currentState = state; if (USE_CONNECTION_SERVICE && state == STATE_ESTABLISHED /*&& !wasEstablished*/ && systemCallConnection != null) { systemCallConnection.setActive(); } for (int a = 0; a < stateListeners.size(); a++) { StateListener l = stateListeners.get(a); l.onStateChanged(state); } } private void updateTrafficStats(NativeInstance instance, Instance.TrafficStats trafficStats) { if (trafficStats == null) { trafficStats = instance.getTrafficStats(); } final long wifiSentDiff = trafficStats.bytesSentWifi - (prevTrafficStats != null ? prevTrafficStats.bytesSentWifi : 0); final long wifiRecvdDiff = trafficStats.bytesReceivedWifi - (prevTrafficStats != null ? prevTrafficStats.bytesReceivedWifi : 0); final long mobileSentDiff = trafficStats.bytesSentMobile - (prevTrafficStats != null ? prevTrafficStats.bytesSentMobile : 0); final long mobileRecvdDiff = trafficStats.bytesReceivedMobile - (prevTrafficStats != null ? prevTrafficStats.bytesReceivedMobile : 0); prevTrafficStats = trafficStats; if (wifiSentDiff > 0) { StatsController.getInstance(currentAccount).incrementSentBytesCount(StatsController.TYPE_WIFI, StatsController.TYPE_CALLS, wifiSentDiff); } if (wifiRecvdDiff > 0) { StatsController.getInstance(currentAccount).incrementReceivedBytesCount(StatsController.TYPE_WIFI, StatsController.TYPE_CALLS, wifiRecvdDiff); } if (mobileSentDiff > 0) { StatsController.getInstance(currentAccount).incrementSentBytesCount(lastNetInfo != null && lastNetInfo.isRoaming() ? StatsController.TYPE_ROAMING : StatsController.TYPE_MOBILE, StatsController.TYPE_CALLS, mobileSentDiff); } if (mobileRecvdDiff > 0) { StatsController.getInstance(currentAccount).incrementReceivedBytesCount(lastNetInfo != null && lastNetInfo.isRoaming() ? StatsController.TYPE_ROAMING : StatsController.TYPE_MOBILE, StatsController.TYPE_CALLS, mobileRecvdDiff); } } @SuppressLint("InvalidWakeLockTag") private void configureDeviceForCall() { if (BuildVars.LOGS_ENABLED) { FileLog.d("configureDeviceForCall, route to set = " + audioRouteToSet); } if (Build.VERSION.SDK_INT >= 21) { WebRtcAudioTrack.setAudioTrackUsageAttribute(hasRtmpStream() ? AudioAttributes.USAGE_MEDIA : AudioAttributes.USAGE_VOICE_COMMUNICATION); WebRtcAudioTrack.setAudioStreamType(hasRtmpStream() ? AudioManager.USE_DEFAULT_STREAM_TYPE : AudioManager.STREAM_VOICE_CALL); } needPlayEndSound = true; AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); if (!USE_CONNECTION_SERVICE) { Utilities.globalQueue.postRunnable(() -> { try { if (hasRtmpStream()) { am.setMode(AudioManager.MODE_NORMAL); am.setBluetoothScoOn(false); AndroidUtilities.runOnUIThread(() -> { if (!MediaController.getInstance().isMessagePaused()) { MediaController.getInstance().pauseMessage(MediaController.getInstance().getPlayingMessageObject()); } }); return; } am.setMode(AudioManager.MODE_IN_COMMUNICATION); } catch (Exception e) { FileLog.e(e); } AndroidUtilities.runOnUIThread(() -> { am.requestAudioFocus(VoIPService.this, AudioManager.STREAM_VOICE_CALL, AudioManager.AUDIOFOCUS_GAIN); if (isBluetoothHeadsetConnected() && hasEarpiece()) { switch (audioRouteToSet) { case AUDIO_ROUTE_BLUETOOTH: if (!bluetoothScoActive) { needSwitchToBluetoothAfterScoActivates = true; try { am.startBluetoothSco(); } catch (Throwable e) { FileLog.e(e); } } else { am.setBluetoothScoOn(true); am.setSpeakerphoneOn(false); } break; case AUDIO_ROUTE_EARPIECE: am.setBluetoothScoOn(false); am.setSpeakerphoneOn(false); break; case AUDIO_ROUTE_SPEAKER: am.setBluetoothScoOn(false); am.setSpeakerphoneOn(true); break; } } else if (isBluetoothHeadsetConnected()) { am.setBluetoothScoOn(speakerphoneStateToSet); } else { am.setSpeakerphoneOn(speakerphoneStateToSet); if (speakerphoneStateToSet) { audioRouteToSet = AUDIO_ROUTE_SPEAKER; } else { audioRouteToSet = AUDIO_ROUTE_EARPIECE; } } updateOutputGainControlState(); audioConfigured = true; }); }); } SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE); Sensor proximity = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY); try { if (proximity != null) { proximityWakelock = ((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(PROXIMITY_SCREEN_OFF_WAKE_LOCK, "telegram-voip-prx"); sm.registerListener(this, proximity, SensorManager.SENSOR_DELAY_NORMAL); } } catch (Exception x) { if (BuildVars.LOGS_ENABLED) { FileLog.e("Error initializing proximity sensor", x); } } } private void fetchBluetoothDeviceName() { if (fetchingBluetoothDeviceName) { return; } try { currentBluetoothDeviceName = null; fetchingBluetoothDeviceName = true; BluetoothAdapter.getDefaultAdapter().getProfileProxy(this, serviceListener, BluetoothProfile.HEADSET); } catch (Throwable e) { FileLog.e(e); } } @SuppressLint("NewApi") @Override public void onSensorChanged(SensorEvent event) { if (unmutedByHold || remoteVideoState == Instance.VIDEO_STATE_ACTIVE || videoState[CAPTURE_DEVICE_CAMERA] == Instance.VIDEO_STATE_ACTIVE) { return; } if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) { AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); if (audioRouteToSet != AUDIO_ROUTE_EARPIECE || isHeadsetPlugged || am.isSpeakerphoneOn() || (isBluetoothHeadsetConnected() && am.isBluetoothScoOn())) { return; } boolean newIsNear = event.values[0] < Math.min(event.sensor.getMaximumRange(), 3); checkIsNear(newIsNear); } } private void checkIsNear() { if (remoteVideoState == Instance.VIDEO_STATE_ACTIVE || videoState[CAPTURE_DEVICE_CAMERA] == Instance.VIDEO_STATE_ACTIVE) { checkIsNear(false); } } private void checkIsNear(boolean newIsNear) { if (newIsNear != isProximityNear) { if (BuildVars.LOGS_ENABLED) { FileLog.d("proximity " + newIsNear); } isProximityNear = newIsNear; try { if (isProximityNear) { proximityWakelock.acquire(); } else { proximityWakelock.release(1); // this is non-public API before L } } catch (Exception x) { FileLog.e(x); } } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } public boolean isBluetoothHeadsetConnected() { if (USE_CONNECTION_SERVICE && systemCallConnection != null && systemCallConnection.getCallAudioState() != null) { return (systemCallConnection.getCallAudioState().getSupportedRouteMask() & CallAudioState.ROUTE_BLUETOOTH) != 0; } return isBtHeadsetConnected; } public void onAudioFocusChange(int focusChange) { if (focusChange == AudioManager.AUDIOFOCUS_GAIN) { hasAudioFocus = true; } else { hasAudioFocus = false; } } private void updateBluetoothHeadsetState(boolean connected) { if (connected == isBtHeadsetConnected) { return; } if (BuildVars.LOGS_ENABLED) { FileLog.d("updateBluetoothHeadsetState: " + connected); } isBtHeadsetConnected = connected; final AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); if (connected && !isRinging() && currentState != 0) { if (bluetoothScoActive) { if (BuildVars.LOGS_ENABLED) { FileLog.d("SCO already active, setting audio routing"); } if (!hasRtmpStream()) { am.setSpeakerphoneOn(false); am.setBluetoothScoOn(true); } } else { if (BuildVars.LOGS_ENABLED) { FileLog.d("startBluetoothSco"); } if (!hasRtmpStream()) { needSwitchToBluetoothAfterScoActivates = true; AndroidUtilities.runOnUIThread(() -> { try { am.startBluetoothSco(); } catch (Throwable ignore) { } }, 500); } } } else { bluetoothScoActive = false; bluetoothScoConnecting = false; am.setBluetoothScoOn(false); } for (StateListener l : stateListeners) { l.onAudioSettingsChanged(); } } public String getLastError() { return lastError; } public int getCallState() { return currentState; } public TLRPC.InputPeer getGroupCallPeer() { return groupCallPeer; } private void updateNetworkType() { if (tgVoip[CAPTURE_DEVICE_CAMERA] != null) { if (tgVoip[CAPTURE_DEVICE_CAMERA].isGroup()) { } else { tgVoip[CAPTURE_DEVICE_CAMERA].setNetworkType(getNetworkType()); } } else { lastNetInfo = getActiveNetworkInfo(); } } private int getNetworkType() { final NetworkInfo info = lastNetInfo = getActiveNetworkInfo(); int type = Instance.NET_TYPE_UNKNOWN; if (info != null) { switch (info.getType()) { case ConnectivityManager.TYPE_MOBILE: switch (info.getSubtype()) { case TelephonyManager.NETWORK_TYPE_GPRS: type = Instance.NET_TYPE_GPRS; break; case TelephonyManager.NETWORK_TYPE_EDGE: case TelephonyManager.NETWORK_TYPE_1xRTT: type = Instance.NET_TYPE_EDGE; break; case TelephonyManager.NETWORK_TYPE_UMTS: case TelephonyManager.NETWORK_TYPE_EVDO_0: type = Instance.NET_TYPE_3G; break; case TelephonyManager.NETWORK_TYPE_HSDPA: case TelephonyManager.NETWORK_TYPE_HSPA: case TelephonyManager.NETWORK_TYPE_HSPAP: case TelephonyManager.NETWORK_TYPE_HSUPA: case TelephonyManager.NETWORK_TYPE_EVDO_A: case TelephonyManager.NETWORK_TYPE_EVDO_B: type = Instance.NET_TYPE_HSPA; break; case TelephonyManager.NETWORK_TYPE_LTE: type = Instance.NET_TYPE_LTE; break; default: type = Instance.NET_TYPE_OTHER_MOBILE; break; } break; case ConnectivityManager.TYPE_WIFI: type = Instance.NET_TYPE_WIFI; break; case ConnectivityManager.TYPE_ETHERNET: type = Instance.NET_TYPE_ETHERNET; break; } } return type; } private NetworkInfo getActiveNetworkInfo() { return ((ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); } private void callFailed() { callFailed(tgVoip[CAPTURE_DEVICE_CAMERA] != null ? tgVoip[CAPTURE_DEVICE_CAMERA].getLastError() : Instance.ERROR_UNKNOWN); } private Bitmap getRoundAvatarBitmap(TLObject userOrChat) { Bitmap bitmap = null; try { if (userOrChat instanceof TLRPC.User) { TLRPC.User user = (TLRPC.User) userOrChat; if (user.photo != null && user.photo.photo_small != null) { BitmapDrawable img = ImageLoader.getInstance().getImageFromMemory(user.photo.photo_small, null, "50_50"); if (img != null) { bitmap = img.getBitmap().copy(Bitmap.Config.ARGB_8888, true); } else { try { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inMutable = true; bitmap = BitmapFactory.decodeFile(FileLoader.getInstance(currentAccount).getPathToAttach(user.photo.photo_small, true).toString(), opts); } catch (Throwable e) { FileLog.e(e); } } } } else { TLRPC.Chat chat = (TLRPC.Chat) userOrChat; if (chat.photo != null && chat.photo.photo_small != null) { BitmapDrawable img = ImageLoader.getInstance().getImageFromMemory(chat.photo.photo_small, null, "50_50"); if (img != null) { bitmap = img.getBitmap().copy(Bitmap.Config.ARGB_8888, true); } else { try { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inMutable = true; bitmap = BitmapFactory.decodeFile(FileLoader.getInstance(currentAccount).getPathToAttach(chat.photo.photo_small, true).toString(), opts); } catch (Throwable e) { FileLog.e(e); } } } } } catch (Throwable e) { FileLog.e(e); } if (bitmap == null) { Theme.createDialogsResources(this); AvatarDrawable placeholder; if (userOrChat instanceof TLRPC.User) { placeholder = new AvatarDrawable((TLRPC.User) userOrChat); } else { placeholder = new AvatarDrawable((TLRPC.Chat) userOrChat); } bitmap = Bitmap.createBitmap(AndroidUtilities.dp(42), AndroidUtilities.dp(42), Bitmap.Config.ARGB_8888); placeholder.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); placeholder.draw(new Canvas(bitmap)); } Canvas canvas = new Canvas(bitmap); Path circlePath = new Path(); circlePath.addCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2, bitmap.getWidth() / 2, Path.Direction.CW); circlePath.toggleInverseFillType(); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); canvas.drawPath(circlePath, paint); return bitmap; } private void showIncomingNotification(String name, CharSequence subText, TLObject userOrChat, boolean video, int additionalMemberCount) { Intent intent = new Intent(this, LaunchActivity.class); intent.setAction("voip"); Notification.Builder builder = new Notification.Builder(this) .setContentTitle(video ? LocaleController.getString("VoipInVideoCallBranding", R.string.VoipInVideoCallBranding) : LocaleController.getString("VoipInCallBranding", R.string.VoipInCallBranding)) .setContentText(name) .setSmallIcon(R.drawable.notification) .setSubText(subText) .setContentIntent(PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_MUTABLE)); Uri soundProviderUri = Uri.parse("content://" + ApplicationLoader.getApplicationId() + ".call_sound_provider/start_ringing"); if (Build.VERSION.SDK_INT >= 26) { SharedPreferences nprefs = MessagesController.getGlobalNotificationsSettings(); int chanIndex = nprefs.getInt("calls_notification_channel", 0); NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); NotificationChannel oldChannel = nm.getNotificationChannel("incoming_calls2" + chanIndex); if (oldChannel != null) { nm.deleteNotificationChannel(oldChannel.getId()); } NotificationChannel existingChannel = nm.getNotificationChannel("incoming_calls3" + chanIndex); boolean needCreate = true; if (existingChannel != null) { if (existingChannel.getImportance() < NotificationManager.IMPORTANCE_HIGH || !soundProviderUri.equals(existingChannel.getSound()) || existingChannel.getVibrationPattern() != null || existingChannel.shouldVibrate()) { if (BuildVars.LOGS_ENABLED) { FileLog.d("User messed up the notification channel; deleting it and creating a proper one"); } nm.deleteNotificationChannel("incoming_calls3" + chanIndex); chanIndex++; nprefs.edit().putInt("calls_notification_channel", chanIndex).commit(); } else { needCreate = false; } } if (needCreate) { AudioAttributes attrs = new AudioAttributes.Builder() .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) .setLegacyStreamType(AudioManager.STREAM_RING) .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION) .build(); NotificationChannel chan = new NotificationChannel("incoming_calls3" + chanIndex, LocaleController.getString("IncomingCalls", R.string.IncomingCalls), NotificationManager.IMPORTANCE_HIGH); chan.setSound(soundProviderUri, attrs); chan.enableVibration(false); chan.enableLights(false); chan.setBypassDnd(true); try { nm.createNotificationChannel(chan); } catch (Exception e) { FileLog.e(e); this.stopSelf(); return; } } builder.setChannelId("incoming_calls3" + chanIndex); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { builder.setSound(soundProviderUri, AudioManager.STREAM_RING); } Intent endIntent = new Intent(this, VoIPActionsReceiver.class); endIntent.setAction(getPackageName() + ".DECLINE_CALL"); endIntent.putExtra("call_id", getCallID()); CharSequence endTitle = LocaleController.getString("VoipDeclineCall", R.string.VoipDeclineCall); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { endTitle = new SpannableString(endTitle); ((SpannableString) endTitle).setSpan(new ForegroundColorSpan(0xFFF44336), 0, endTitle.length(), 0); } PendingIntent endPendingIntent = PendingIntent.getBroadcast(this, 0, endIntent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_CANCEL_CURRENT); builder.addAction(R.drawable.ic_call_end_white_24dp, endTitle, endPendingIntent); Intent answerIntent = new Intent(this, VoIPActionsReceiver.class); answerIntent.setAction(getPackageName() + ".ANSWER_CALL"); answerIntent.putExtra("call_id", getCallID()); CharSequence answerTitle = LocaleController.getString("VoipAnswerCall", R.string.VoipAnswerCall); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { answerTitle = new SpannableString(answerTitle); ((SpannableString) answerTitle).setSpan(new ForegroundColorSpan(0xFF00AA00), 0, answerTitle.length(), 0); } PendingIntent answerPendingIntent = PendingIntent.getBroadcast(this, 0, answerIntent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_CANCEL_CURRENT); builder.addAction(R.drawable.ic_call, answerTitle, answerPendingIntent); builder.setPriority(Notification.PRIORITY_MAX); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { builder.setShowWhen(false); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { builder.setColor(0xff2ca5e0); builder.setVibrate(new long[0]); builder.setCategory(Notification.CATEGORY_CALL); builder.setFullScreenIntent(PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_MUTABLE), true); if (userOrChat instanceof TLRPC.User) { TLRPC.User user = (TLRPC.User) userOrChat; if (!TextUtils.isEmpty(user.phone)) { builder.addPerson("tel:" + user.phone); } } } Notification incomingNotification = builder.getNotification(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { RemoteViews customView = new RemoteViews(getPackageName(), LocaleController.isRTL ? R.layout.call_notification_rtl : R.layout.call_notification); customView.setTextViewText(R.id.name, name); boolean subtitleVisible = true; if (TextUtils.isEmpty(subText)) { customView.setViewVisibility(R.id.subtitle, View.GONE); if (UserConfig.getActivatedAccountsCount() > 1) { TLRPC.User self = UserConfig.getInstance(currentAccount).getCurrentUser(); customView.setTextViewText(R.id.title, video ? LocaleController.formatString("VoipInVideoCallBrandingWithName", R.string.VoipInVideoCallBrandingWithName, ContactsController.formatName(self.first_name, self.last_name)) : LocaleController.formatString("VoipInCallBrandingWithName", R.string.VoipInCallBrandingWithName, ContactsController.formatName(self.first_name, self.last_name))); } else { customView.setTextViewText(R.id.title, video ? LocaleController.getString("VoipInVideoCallBranding", R.string.VoipInVideoCallBranding) : LocaleController.getString("VoipInCallBranding", R.string.VoipInCallBranding)); } } else { if (UserConfig.getActivatedAccountsCount() > 1) { TLRPC.User self = UserConfig.getInstance(currentAccount).getCurrentUser(); customView.setTextViewText(R.id.subtitle, LocaleController.formatString("VoipAnsweringAsAccount", R.string.VoipAnsweringAsAccount, ContactsController.formatName(self.first_name, self.last_name))); } else { customView.setViewVisibility(R.id.subtitle, View.GONE); } customView.setTextViewText(R.id.title, subText); } Bitmap avatar = getRoundAvatarBitmap(userOrChat); customView.setTextViewText(R.id.answer_text, LocaleController.getString("VoipAnswerCall", R.string.VoipAnswerCall)); customView.setTextViewText(R.id.decline_text, LocaleController.getString("VoipDeclineCall", R.string.VoipDeclineCall)); customView.setImageViewBitmap(R.id.photo, avatar); customView.setOnClickPendingIntent(R.id.answer_btn, answerPendingIntent); customView.setOnClickPendingIntent(R.id.decline_btn, endPendingIntent); builder.setLargeIcon(avatar); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { builder.setColor(0xFF282e31); builder.setColorized(true); builder.setCustomBigContentView(customView); } else { incomingNotification.headsUpContentView = incomingNotification.bigContentView = customView; } } startForeground(ID_INCOMING_CALL_NOTIFICATION, incomingNotification); startRingtoneAndVibration(); } private void callFailed(String error) { if (privateCall != null) { if (BuildVars.LOGS_ENABLED) { FileLog.d("Discarding failed call"); } TLRPC.TL_phone_discardCall req = new TLRPC.TL_phone_discardCall(); req.peer = new TLRPC.TL_inputPhoneCall(); req.peer.access_hash = privateCall.access_hash; req.peer.id = privateCall.id; req.duration = (int) (getCallDuration() / 1000); req.connection_id = tgVoip[CAPTURE_DEVICE_CAMERA] != null ? tgVoip[CAPTURE_DEVICE_CAMERA].getPreferredRelayId() : 0; req.reason = new TLRPC.TL_phoneCallDiscardReasonDisconnect(); ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error1) -> { if (error1 != null) { if (BuildVars.LOGS_ENABLED) { FileLog.e("error on phone.discardCall: " + error1); } } else { if (BuildVars.LOGS_ENABLED) { FileLog.d("phone.discardCall " + response); } } }); } try { throw new Exception("Call " + getCallID() + " failed with error: " + error); } catch (Exception x) { FileLog.e(x); } lastError = error; AndroidUtilities.runOnUIThread(() -> dispatchStateChanged(STATE_FAILED)); if (TextUtils.equals(error, Instance.ERROR_LOCALIZED) && soundPool != null) { playingSound = true; Utilities.globalQueue.postRunnable(() -> soundPool.play(spFailedID, 1, 1, 0, 0, 1)); AndroidUtilities.runOnUIThread(afterSoundRunnable, 1000); } if (USE_CONNECTION_SERVICE && systemCallConnection != null) { systemCallConnection.setDisconnected(new DisconnectCause(DisconnectCause.ERROR)); systemCallConnection.destroy(); systemCallConnection = null; } stopSelf(); } void callFailedFromConnectionService() { if (isOutgoing) { callFailed(Instance.ERROR_CONNECTION_SERVICE); } else { hangUp(); } } @Override public void onConnectionStateChanged(int newState, boolean inTransition) { AndroidUtilities.runOnUIThread(() -> { if (newState == STATE_ESTABLISHED) { if (callStartTime == 0) { callStartTime = SystemClock.elapsedRealtime(); } //peerCapabilities = tgVoip.getPeerCapabilities(); } if (newState == STATE_FAILED) { callFailed(); return; } if (newState == STATE_ESTABLISHED) { if (connectingSoundRunnable != null) { AndroidUtilities.cancelRunOnUIThread(connectingSoundRunnable); connectingSoundRunnable = null; } Utilities.globalQueue.postRunnable(() -> { if (spPlayId != 0) { soundPool.stop(spPlayId); spPlayId = 0; } }); if (groupCall == null && !wasEstablished) { wasEstablished = true; if (!isProximityNear && !privateCall.video) { Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); if (vibrator.hasVibrator()) { vibrator.vibrate(100); } } AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { if (tgVoip[CAPTURE_DEVICE_CAMERA] != null) { StatsController.getInstance(currentAccount).incrementTotalCallsTime(getStatsNetworkType(), 5); AndroidUtilities.runOnUIThread(this, 5000); } } }, 5000); if (isOutgoing) { StatsController.getInstance(currentAccount).incrementSentItemsCount(getStatsNetworkType(), StatsController.TYPE_CALLS, 1); } else { StatsController.getInstance(currentAccount).incrementReceivedItemsCount(getStatsNetworkType(), StatsController.TYPE_CALLS, 1); } } } if (newState == STATE_RECONNECTING) { Utilities.globalQueue.postRunnable(() -> { if (spPlayId != 0) { soundPool.stop(spPlayId); } spPlayId = soundPool.play(groupCall != null ? spVoiceChatConnecting : spConnectingId, 1, 1, 0, -1, 1); }); } dispatchStateChanged(newState); }); } public void playStartRecordSound() { Utilities.globalQueue.postRunnable(() -> soundPool.play(spStartRecordId, 0.5f, 0.5f, 0, 0, 1)); } public void playAllowTalkSound() { Utilities.globalQueue.postRunnable(() -> soundPool.play(spAllowTalkId, 0.5f, 0.5f, 0, 0, 1)); } @Override public void onSignalBarCountChanged(int newCount) { AndroidUtilities.runOnUIThread(() -> { signalBarCount = newCount; for (int a = 0; a < stateListeners.size(); a++) { StateListener l = stateListeners.get(a); l.onSignalBarsCountChanged(newCount); } }); } public boolean isBluetoothOn() { final AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); return am.isBluetoothScoOn(); } public boolean isBluetoothWillOn() { return needSwitchToBluetoothAfterScoActivates; } public boolean isHeadsetPlugged() { return isHeadsetPlugged; } private void callEnded() { if (BuildVars.LOGS_ENABLED) { FileLog.d("Call " + getCallID() + " ended"); } if (groupCall != null && (!playedConnectedSound || onDestroyRunnable != null)) { needPlayEndSound = false; } AndroidUtilities.runOnUIThread(() -> dispatchStateChanged(STATE_ENDED)); int delay = 700; Utilities.globalQueue.postRunnable(() -> { if (spPlayId != 0) { soundPool.stop(spPlayId); spPlayId = 0; } }); if (connectingSoundRunnable != null) { AndroidUtilities.cancelRunOnUIThread(connectingSoundRunnable); connectingSoundRunnable = null; } if (needPlayEndSound) { playingSound = true; if (groupCall == null) { Utilities.globalQueue.postRunnable(() -> soundPool.play(spEndId, 1, 1, 0, 0, 1)); } else { Utilities.globalQueue.postRunnable(() -> soundPool.play(spVoiceChatEndId, 1.0f, 1.0f, 0, 0, 1), 100); delay = 500; } AndroidUtilities.runOnUIThread(afterSoundRunnable, delay); } if (timeoutRunnable != null) { AndroidUtilities.cancelRunOnUIThread(timeoutRunnable); timeoutRunnable = null; } endConnectionServiceCall(needPlayEndSound ? delay : 0); stopSelf(); } private void endConnectionServiceCall(long delay) { if (USE_CONNECTION_SERVICE) { Runnable r = () -> { if (systemCallConnection != null) { switch (callDiscardReason) { case DISCARD_REASON_HANGUP: systemCallConnection.setDisconnected(new DisconnectCause(isOutgoing ? DisconnectCause.LOCAL : DisconnectCause.REJECTED)); break; case DISCARD_REASON_DISCONNECT: systemCallConnection.setDisconnected(new DisconnectCause(DisconnectCause.ERROR)); break; case DISCARD_REASON_LINE_BUSY: systemCallConnection.setDisconnected(new DisconnectCause(DisconnectCause.BUSY)); break; case DISCARD_REASON_MISSED: systemCallConnection.setDisconnected(new DisconnectCause(isOutgoing ? DisconnectCause.CANCELED : DisconnectCause.MISSED)); break; default: systemCallConnection.setDisconnected(new DisconnectCause(DisconnectCause.REMOTE)); break; } systemCallConnection.destroy(); systemCallConnection = null; } }; if (delay > 0) { AndroidUtilities.runOnUIThread(r, delay); } else { r.run(); } } } public boolean isOutgoing() { return isOutgoing; } public void handleNotificationAction(Intent intent) { if ((getPackageName() + ".END_CALL").equals(intent.getAction())) { stopForeground(true); hangUp(); } else if ((getPackageName() + ".DECLINE_CALL").equals(intent.getAction())) { stopForeground(true); declineIncomingCall(DISCARD_REASON_LINE_BUSY, null); } else if ((getPackageName() + ".ANSWER_CALL").equals(intent.getAction())) { acceptIncomingCallFromNotification(); } } private void acceptIncomingCallFromNotification() { showNotification(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.R && (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED || privateCall.video && checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) { try { //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT); PendingIntent.getActivity(VoIPService.this, 0, new Intent(VoIPService.this, VoIPPermissionActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_ONE_SHOT).send(); } catch (Exception x) { if (BuildVars.LOGS_ENABLED) { FileLog.e("Error starting permission activity", x); } } return; } acceptIncomingCall(); try { PendingIntent.getActivity(VoIPService.this, 0, new Intent(VoIPService.this, getUIActivityClass()).setAction("voip"), PendingIntent.FLAG_MUTABLE).send(); } catch (Exception x) { if (BuildVars.LOGS_ENABLED) { FileLog.e("Error starting incall activity", x); } } } public void updateOutputGainControlState() { if (hasRtmpStream()) { return; } if (tgVoip[CAPTURE_DEVICE_CAMERA] != null) { if (!USE_CONNECTION_SERVICE) { final AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); tgVoip[CAPTURE_DEVICE_CAMERA].setAudioOutputGainControlEnabled(hasEarpiece() && !am.isSpeakerphoneOn() && !am.isBluetoothScoOn() && !isHeadsetPlugged); tgVoip[CAPTURE_DEVICE_CAMERA].setEchoCancellationStrength(isHeadsetPlugged || (hasEarpiece() && !am.isSpeakerphoneOn() && !am.isBluetoothScoOn() && !isHeadsetPlugged) ? 0 : 1); } else { final boolean isEarpiece = systemCallConnection.getCallAudioState().getRoute() == CallAudioState.ROUTE_EARPIECE; tgVoip[CAPTURE_DEVICE_CAMERA].setAudioOutputGainControlEnabled(isEarpiece); tgVoip[CAPTURE_DEVICE_CAMERA].setEchoCancellationStrength(isEarpiece ? 0 : 1); } } } public int getAccount() { return currentAccount; } @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.appDidLogout) { callEnded(); } } public static boolean isAnyKindOfCallActive() { if (VoIPService.getSharedInstance() != null) { return VoIPService.getSharedInstance().getCallState() != VoIPService.STATE_WAITING_INCOMING; } return false; } private boolean isFinished() { return currentState == STATE_ENDED || currentState == STATE_FAILED; } public int getRemoteAudioState() { return remoteAudioState; } public int getRemoteVideoState() { return remoteVideoState; } @TargetApi(Build.VERSION_CODES.O) private PhoneAccountHandle addAccountToTelecomManager() { TelecomManager tm = (TelecomManager) getSystemService(TELECOM_SERVICE); TLRPC.User self = UserConfig.getInstance(currentAccount).getCurrentUser(); PhoneAccountHandle handle = new PhoneAccountHandle(new ComponentName(this, TelegramConnectionService.class), "" + self.id); PhoneAccount account = new PhoneAccount.Builder(handle, ContactsController.formatName(self.first_name, self.last_name)) .setCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED) .setIcon(Icon.createWithResource(this, R.drawable.ic_launcher_dr)) .setHighlightColor(0xff2ca5e0) .addSupportedUriScheme("sip") .build(); tm.registerPhoneAccount(account); return handle; } private static boolean isDeviceCompatibleWithConnectionServiceAPI() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { return false; } // some non-Google devices don't implement the ConnectionService API correctly so, sadly, // we'll have to whitelist only a handful of known-compatible devices for now return false;/*"angler".equals(Build.PRODUCT) // Nexus 6P || "bullhead".equals(Build.PRODUCT) // Nexus 5X || "sailfish".equals(Build.PRODUCT) // Pixel || "marlin".equals(Build.PRODUCT) // Pixel XL || "walleye".equals(Build.PRODUCT) // Pixel 2 || "taimen".equals(Build.PRODUCT) // Pixel 2 XL || "blueline".equals(Build.PRODUCT) // Pixel 3 || "crosshatch".equals(Build.PRODUCT) // Pixel 3 XL || MessagesController.getGlobalMainSettings().getBoolean("dbg_force_connection_service", false);*/ } public interface StateListener { default void onStateChanged(int state) { } default void onSignalBarsCountChanged(int count) { } default void onAudioSettingsChanged() { } default void onMediaStateUpdated(int audioState, int videoState) { } default void onCameraSwitch(boolean isFrontFace) { } default void onCameraFirstFrameAvailable() { } default void onVideoAvailableChange(boolean isAvailable) { } default void onScreenOnChange(boolean screenOn) { } } public class CallConnection extends Connection { public CallConnection() { setConnectionProperties(PROPERTY_SELF_MANAGED); setAudioModeIsVoip(true); } @Override public void onCallAudioStateChanged(CallAudioState state) { if (BuildVars.LOGS_ENABLED) { FileLog.d("ConnectionService call audio state changed: " + state); } for (StateListener l : stateListeners) { l.onAudioSettingsChanged(); } } @Override public void onDisconnect() { if (BuildVars.LOGS_ENABLED) { FileLog.d("ConnectionService onDisconnect"); } setDisconnected(new DisconnectCause(DisconnectCause.LOCAL)); destroy(); systemCallConnection = null; hangUp(); } @Override public void onAnswer() { acceptIncomingCallFromNotification(); } @Override public void onReject() { needPlayEndSound = false; declineIncomingCall(DISCARD_REASON_HANGUP, null); } @Override public void onShowIncomingCallUi() { startRinging(); } @Override public void onStateChanged(int state) { super.onStateChanged(state); if (BuildVars.LOGS_ENABLED) { FileLog.d("ConnectionService onStateChanged " + stateToString(state)); } if (state == Connection.STATE_ACTIVE) { ContactsController.getInstance(currentAccount).deleteConnectionServiceContact(); didDeleteConnectionServiceContact = true; } } @Override public void onCallEvent(String event, Bundle extras) { super.onCallEvent(event, extras); if (BuildVars.LOGS_ENABLED) FileLog.d("ConnectionService onCallEvent " + event); } //undocumented API public void onSilence() { if (BuildVars.LOGS_ENABLED) { FileLog.d("onSlience"); } stopRinging(); } } public static class SharedUIParams { public boolean tapToVideoTooltipWasShowed; public boolean cameraAlertWasShowed; public boolean wasVideoCall; } }
flyun/chatAir
TMessagesProj/src/main/java/org/telegram/messenger/voip/VoIPService.java
41,707
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.ui.Components; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.drawable.Animatable; import android.graphics.drawable.BitmapDrawable; import android.os.Build; import android.view.View; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AnimatedFileDrawableStream; import org.telegram.messenger.DispatchQueue; import org.telegram.messenger.DispatchQueuePoolBackground; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.ImageLocation; import org.telegram.messenger.ImageReceiver; import org.telegram.messenger.utils.BitmapsCache; import org.telegram.tgnet.TLRPC; import java.io.File; import java.util.ArrayList; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class AnimatedFileDrawable extends BitmapDrawable implements Animatable, BitmapsCache.Cacheable { public boolean skipFrameUpdate; public long currentTime; private static native long createDecoder(String src, int[] params, int account, long streamFileSize, Object readCallback, boolean preview); private static native void destroyDecoder(long ptr); private static native void stopDecoder(long ptr); private static native int getVideoFrame(long ptr, Bitmap bitmap, int[] params, int stride, boolean preview, float startTimeSeconds, float endTimeSeconds); private static native void seekToMs(long ptr, long ms, boolean precise); private static native int getFrameAtTime(long ptr, long ms, Bitmap bitmap, int[] data, int stride); private static native void prepareToSeek(long ptr); private static native void getVideoInfo(int sdkVersion, String src, int[] params); public final static int PARAM_NUM_SUPPORTED_VIDEO_CODEC = 0; public final static int PARAM_NUM_WIDTH = 1; public final static int PARAM_NUM_HEIGHT = 2; public final static int PARAM_NUM_BITRATE = 3; public final static int PARAM_NUM_DURATION = 4; public final static int PARAM_NUM_AUDIO_FRAME_SIZE = 5; public final static int PARAM_NUM_VIDEO_FRAME_SIZE = 6; public final static int PARAM_NUM_FRAMERATE = 7; public final static int PARAM_NUM_ROTATION = 8; public final static int PARAM_NUM_SUPPORTED_AUDIO_CODEC = 9; public final static int PARAM_NUM_HAS_AUDIO = 10; public final static int PARAM_NUM_COUNT = 11; private long lastFrameTime; private int lastTimeStamp; private int invalidateAfter = 50; private final int[] metaData = new int[5]; private Runnable loadFrameTask; private Bitmap renderingBitmap; private int renderingBitmapTime; private Bitmap nextRenderingBitmap; private int nextRenderingBitmapTime; private Bitmap backgroundBitmap; private int backgroundBitmapTime; private boolean destroyWhenDone; private boolean decoderCreated; private boolean decodeSingleFrame; private boolean singleFrameDecoded; private boolean forceDecodeAfterNextFrame; private File path; private long streamFileSize; private int streamLoadingPriority; private int currentAccount; private boolean recycleWithSecond; private volatile long pendingSeekTo = -1; private volatile long pendingSeekToUI = -1; private boolean pendingRemoveLoading; private int pendingRemoveLoadingFramesReset; private boolean isRestarted; private final Object sync = new Object(); private boolean invalidateParentViewWithSecond; public boolean ignoreNoParent; private long lastFrameDecodeTime; private RectF actualDrawRect = new RectF(); private BitmapShader[] renderingShader = new BitmapShader[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT]; private BitmapShader[] nextRenderingShader = new BitmapShader[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT]; private BitmapShader[] backgroundShader = new BitmapShader[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT]; private BitmapShader renderingShaderBackgroundDraw; private int[] roundRadius = new int[4]; private int[] roundRadiusBackup; private Matrix[] shaderMatrix = new Matrix[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT]; private Path[] roundPath = new Path[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT]; private static float[] radii = new float[8]; private Matrix shaderMatrixBackgroundDraw; private float scaleX = 1.0f; private float scaleY = 1.0f; private boolean applyTransformation; private final RectF dstRect = new RectF(); private volatile boolean isRunning; private volatile boolean isRecycled; public volatile long nativePtr; private DispatchQueue decodeQueue; private float startTime; private float endTime; private int renderingHeight; private int renderingWidth; private boolean precache; private float scaleFactor = 1f; public boolean isWebmSticker; private final TLRPC.Document document; private RectF[] dstRectBackground = new RectF[DrawingInBackgroundThreadDrawable.THREAD_COUNT]; private Paint[] backgroundPaint = new Paint[DrawingInBackgroundThreadDrawable.THREAD_COUNT]; private Matrix[] shaderMatrixBackground = new Matrix[DrawingInBackgroundThreadDrawable.THREAD_COUNT]; private Path[] roundPathBackground = new Path[DrawingInBackgroundThreadDrawable.THREAD_COUNT]; private View parentView; private ArrayList<View> secondParentViews = new ArrayList<>(); private ArrayList<ImageReceiver> parents = new ArrayList<>(); private AnimatedFileDrawableStream stream; private boolean useSharedQueue; private boolean invalidatePath = true; private boolean invalidateTaskIsRunning; private boolean limitFps; public int repeatCount; BitmapsCache bitmapsCache; BitmapsCache.Metadata cacheMetadata; private static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(8, new ThreadPoolExecutor.DiscardPolicy()); private Runnable uiRunnableNoFrame = new Runnable() { @Override public void run() { chekDestroyDecoder(); loadFrameTask = null; scheduleNextGetFrame(); invalidateInternal(); } }; boolean generatingCache; Runnable cacheGenRunnable; private Runnable uiRunnableGenerateCache = new Runnable() { @Override public void run() { if (!isRecycled && !destroyWhenDone && !generatingCache && cacheGenRunnable == null) { startTime = System.currentTimeMillis(); if (RLottieDrawable.lottieCacheGenerateQueue == null) { RLottieDrawable.createCacheGenQueue(); } generatingCache = true; loadFrameTask = null; BitmapsCache.incrementTaskCounter(); RLottieDrawable.lottieCacheGenerateQueue.postRunnable(cacheGenRunnable = () -> { bitmapsCache.createCache(); AndroidUtilities.runOnUIThread(() -> { if (cacheGenRunnable != null) { BitmapsCache.decrementTaskCounter(); cacheGenRunnable = null; } generatingCache = false; scheduleNextGetFrame(); }); }); } } }; private void chekDestroyDecoder() { if (loadFrameRunnable == null && destroyWhenDone && nativePtr != 0 && !generatingCache) { destroyDecoder(nativePtr); nativePtr = 0; } if (!canLoadFrames()) { if (renderingBitmap != null) { renderingBitmap.recycle(); renderingBitmap = null; } if (backgroundBitmap != null) { backgroundBitmap.recycle(); backgroundBitmap = null; } if (decodeQueue != null) { decodeQueue.recycle(); decodeQueue = null; } invalidateInternal(); } } private void invalidateInternal() { for (int i = 0; i < parents.size(); i++) { parents.get(i).invalidate(); } } private Runnable uiRunnable = new Runnable() { @Override public void run() { chekDestroyDecoder(); if (stream != null && pendingRemoveLoading) { FileLoader.getInstance(currentAccount).removeLoadingVideo(stream.getDocument(), false, false); } if (pendingRemoveLoadingFramesReset <= 0) { pendingRemoveLoading = true; } else { pendingRemoveLoadingFramesReset--; } if (!forceDecodeAfterNextFrame) { singleFrameDecoded = true; } else { forceDecodeAfterNextFrame = false; } loadFrameTask = null; nextRenderingBitmap = backgroundBitmap; nextRenderingBitmapTime = backgroundBitmapTime; for (int i = 0; i < backgroundShader.length; i++) { nextRenderingShader[i] = backgroundShader[i]; } if (isRestarted) { isRestarted = false; repeatCount++; checkRepeat(); } if (metaData[3] < lastTimeStamp) { lastTimeStamp = startTime > 0 ? (int) (startTime * 1000) : 0; } if (metaData[3] - lastTimeStamp != 0) { invalidateAfter = metaData[3] - lastTimeStamp; if (limitFps && invalidateAfter < 32) { invalidateAfter = 32; } } if (pendingSeekToUI >= 0 && pendingSeekTo == -1) { pendingSeekToUI = -1; invalidateAfter = 0; } lastTimeStamp = metaData[3]; if (!secondParentViews.isEmpty()) { for (int a = 0, N = secondParentViews.size(); a < N; a++) { secondParentViews.get(a).invalidate(); } } invalidateInternal(); scheduleNextGetFrame(); } }; public void checkRepeat() { if (ignoreNoParent) { start(); return; } int count = 0; for (int j = 0; j < parents.size(); j++) { ImageReceiver parent = parents.get(j); if (!parent.isAttachedToWindow()) { parents.remove(j); j--; } if (parent.animatedFileDrawableRepeatMaxCount > 0 && repeatCount >= parent.animatedFileDrawableRepeatMaxCount) { count++; } } if (parents.size() == count) { stop(); } else { start(); } } private Runnable loadFrameRunnable = new Runnable() { @Override public void run() { if (!isRecycled) { if (!decoderCreated && nativePtr == 0) { nativePtr = createDecoder(path.getAbsolutePath(), metaData, currentAccount, streamFileSize, stream, false); if (nativePtr != 0 && (metaData[0] > 3840 || metaData[1] > 3840)) { destroyDecoder(nativePtr); nativePtr = 0; } updateScaleFactor(); decoderCreated = true; } try { if (bitmapsCache != null) { if (backgroundBitmap == null) { backgroundBitmap = Bitmap.createBitmap(renderingWidth, renderingHeight, Bitmap.Config.ARGB_8888); } if (cacheMetadata == null) { cacheMetadata = new BitmapsCache.Metadata(); } lastFrameDecodeTime = System.currentTimeMillis(); int lastFrame = cacheMetadata.frame; int result = bitmapsCache.getFrame(backgroundBitmap, cacheMetadata); if (result != -1 && cacheMetadata.frame < lastFrame) { isRestarted = true; } metaData[3] = backgroundBitmapTime = cacheMetadata.frame * Math.max(16, metaData[4] / Math.max(1, bitmapsCache.getFrameCount())); if (bitmapsCache.needGenCache()) { AndroidUtilities.runOnUIThread(uiRunnableGenerateCache); } if (result == -1) { AndroidUtilities.runOnUIThread(uiRunnableNoFrame); } else { AndroidUtilities.runOnUIThread(uiRunnable); } return; } if (nativePtr != 0 || metaData[0] == 0 || metaData[1] == 0) { if (backgroundBitmap == null && metaData[0] > 0 && metaData[1] > 0) { try { backgroundBitmap = Bitmap.createBitmap((int) (metaData[0] * scaleFactor), (int) (metaData[1] * scaleFactor), Bitmap.Config.ARGB_8888); } catch (Throwable e) { FileLog.e(e); } if (backgroundShader[0] == null && backgroundBitmap != null && hasRoundRadius()) { backgroundShader[0] = new BitmapShader(backgroundBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); } } boolean seekWas = false; if (pendingSeekTo >= 0) { metaData[3] = (int) pendingSeekTo; long seekTo = pendingSeekTo; synchronized (sync) { pendingSeekTo = -1; } seekWas = true; if (stream != null) { stream.reset(); } seekToMs(nativePtr, seekTo, true); } if (backgroundBitmap != null) { lastFrameDecodeTime = System.currentTimeMillis(); if (getVideoFrame(nativePtr, backgroundBitmap, metaData, backgroundBitmap.getRowBytes(), false, startTime, endTime) == 0) { AndroidUtilities.runOnUIThread(uiRunnableNoFrame); return; } if (metaData[3] < lastTimeStamp) { isRestarted = true; } if (seekWas) { lastTimeStamp = metaData[3]; } backgroundBitmapTime = metaData[3]; } } else { AndroidUtilities.runOnUIThread(uiRunnableNoFrame); return; } } catch (Throwable e) { FileLog.e(e); } } AndroidUtilities.runOnUIThread(uiRunnable); } }; private void updateScaleFactor() { if (!isWebmSticker && renderingHeight > 0 && renderingWidth > 0 && metaData[0] > 0 && metaData[1] > 0) { scaleFactor = Math.max(renderingWidth / (float) metaData[0], renderingHeight / (float) metaData[1]); if (scaleFactor <= 0 || scaleFactor > 0.7) { scaleFactor = 1; } } else { scaleFactor = 1f; } } private final Runnable mStartTask = () -> { if (!secondParentViews.isEmpty()) { for (int a = 0, N = secondParentViews.size(); a < N; a++) { secondParentViews.get(a).invalidate(); } } if ((secondParentViews.isEmpty() || invalidateParentViewWithSecond) && parentView != null) { parentView.invalidate(); } }; public AnimatedFileDrawable(File file, boolean createDecoder, long streamSize, int streamLoadingPriority, TLRPC.Document document, ImageLocation location, Object parentObject, long seekTo, int account, boolean preview, BitmapsCache.CacheOptions cacheOptions) { this(file, createDecoder, streamSize, streamLoadingPriority, document, location, parentObject, seekTo, account, preview, 0, 0, cacheOptions); } public AnimatedFileDrawable(File file, boolean createDecoder, long streamSize, int streamLoadingPriority, TLRPC.Document document, ImageLocation location, Object parentObject, long seekTo, int account, boolean preview, int w, int h, BitmapsCache.CacheOptions cacheOptions) { path = file; streamFileSize = streamSize; this.streamLoadingPriority = streamLoadingPriority; currentAccount = account; renderingHeight = h; renderingWidth = w; this.precache = cacheOptions != null && renderingWidth > 0 && renderingHeight > 0; this.document = document; getPaint().setFlags(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); if (streamSize != 0 && (document != null || location != null)) { stream = new AnimatedFileDrawableStream(document, location, parentObject, account, preview, streamLoadingPriority); } if (createDecoder && !this.precache) { nativePtr = createDecoder(file.getAbsolutePath(), metaData, currentAccount, streamFileSize, stream, preview); if (nativePtr != 0 && (metaData[0] > 3840 || metaData[1] > 3840)) { destroyDecoder(nativePtr); nativePtr = 0; } updateScaleFactor(); decoderCreated = true; } if (this.precache) { nativePtr = createDecoder(file.getAbsolutePath(), metaData, currentAccount, streamFileSize, stream, preview); if (nativePtr != 0 && (metaData[0] > 3840 || metaData[1] > 3840)) { destroyDecoder(nativePtr); nativePtr = 0; } else { bitmapsCache = new BitmapsCache(file, this, cacheOptions, renderingWidth, renderingHeight, !limitFps); } } if (seekTo != 0) { seekTo(seekTo, false); } } public void setIsWebmSticker(boolean b) { isWebmSticker = b; if (isWebmSticker) { useSharedQueue = true; } } public Bitmap getFrameAtTime(long ms) { return getFrameAtTime(ms, false); } public Bitmap getFrameAtTime(long ms, boolean precise) { if (!decoderCreated || nativePtr == 0) { return null; } if (stream != null) { stream.cancel(false); stream.reset(); } if (!precise) { seekToMs(nativePtr, ms, precise); } Bitmap backgroundBitmap = Bitmap.createBitmap(metaData[0], metaData[1], Bitmap.Config.ARGB_8888); int result; if (precise) { result = getFrameAtTime(nativePtr, ms, backgroundBitmap, metaData, backgroundBitmap.getRowBytes()); } else { result = getVideoFrame(nativePtr, backgroundBitmap, metaData, backgroundBitmap.getRowBytes(), true, 0, 0); } return result != 0 ? backgroundBitmap : null; } public void setParentView(View view) { if (parentView != null) { return; } parentView = view; } public void addParent(ImageReceiver imageReceiver) { if (imageReceiver != null && !parents.contains(imageReceiver)) { parents.add(imageReceiver); if (isRunning) { scheduleNextGetFrame(); } } checkCacheCancel(); } public void removeParent(ImageReceiver imageReceiver) { parents.remove(imageReceiver); if (parents.size() == 0) { repeatCount = 0; } checkCacheCancel(); } private Runnable cancelCache; public void checkCacheCancel() { if (bitmapsCache == null) { return; } boolean mustCancel = parents.isEmpty(); if (mustCancel && cancelCache == null) { AndroidUtilities.runOnUIThread(cancelCache = () -> { if (bitmapsCache != null) { bitmapsCache.cancelCreate(); } }, 600); } else if (!mustCancel && cancelCache != null) { AndroidUtilities.cancelRunOnUIThread(cancelCache); cancelCache = null; } } public void setInvalidateParentViewWithSecond(boolean value) { invalidateParentViewWithSecond = value; } public void addSecondParentView(View view) { if (view == null || secondParentViews.contains(view)) { return; } secondParentViews.add(view); } public void removeSecondParentView(View view) { secondParentViews.remove(view); if (secondParentViews.isEmpty()) { if (recycleWithSecond) { recycle(); } else { if (roundRadiusBackup != null) { setRoundRadius(roundRadiusBackup); } } } } public void setAllowDecodeSingleFrame(boolean value) { decodeSingleFrame = value; if (decodeSingleFrame) { scheduleNextGetFrame(); } } public void seekTo(long ms, boolean removeLoading) { seekTo(ms, removeLoading, false); } public void seekTo(long ms, boolean removeLoading, boolean force) { synchronized (sync) { pendingSeekTo = ms; pendingSeekToUI = ms; if (nativePtr != 0) { prepareToSeek(nativePtr); } if (decoderCreated && stream != null) { stream.cancel(removeLoading); pendingRemoveLoading = removeLoading; pendingRemoveLoadingFramesReset = pendingRemoveLoading ? 0 : 10; } if (force && decodeSingleFrame) { singleFrameDecoded = false; if (loadFrameTask == null) { scheduleNextGetFrame(); } else { forceDecodeAfterNextFrame = true; } } } } public void recycle() { if (!secondParentViews.isEmpty()) { recycleWithSecond = true; return; } isRunning = false; isRecycled = true; if (cacheGenRunnable != null) { BitmapsCache.decrementTaskCounter(); RLottieDrawable.lottieCacheGenerateQueue.cancelRunnable(cacheGenRunnable); cacheGenRunnable = null; } if (loadFrameTask == null) { if (nativePtr != 0) { destroyDecoder(nativePtr); nativePtr = 0; } ArrayList<Bitmap> bitmapToRecycle = new ArrayList<>(); bitmapToRecycle.add(renderingBitmap); bitmapToRecycle.add(nextRenderingBitmap); bitmapToRecycle.add(backgroundBitmap); renderingBitmap = null; nextRenderingBitmap = null; backgroundBitmap = null; if (decodeQueue != null) { decodeQueue.recycle(); decodeQueue = null; } getPaint().setShader(null); AndroidUtilities.recycleBitmaps(bitmapToRecycle); } else { destroyWhenDone = true; } if (stream != null) { stream.cancel(true); stream = null; } invalidateInternal(); } public void resetStream(boolean stop) { if (stream != null) { stream.cancel(true); } if (nativePtr != 0) { if (stop) { stopDecoder(nativePtr); } else { prepareToSeek(nativePtr); } } } public void setUseSharedQueue(boolean value) { if (isWebmSticker) { return; } useSharedQueue = value; } @Override protected void finalize() throws Throwable { try { recycle(); } finally { super.finalize(); } } @Override public int getOpacity() { return PixelFormat.TRANSPARENT; } @Override public void start() { if (isRunning || parents.size() == 0 && !ignoreNoParent) { return; } isRunning = true; scheduleNextGetFrame(); AndroidUtilities.runOnUIThread(mStartTask); } public float getCurrentProgress() { if (metaData[4] == 0) { return 0; } if (pendingSeekToUI >= 0) { return pendingSeekToUI / (float) metaData[4]; } return metaData[3] / (float) metaData[4]; } public int getCurrentProgressMs() { if (pendingSeekToUI >= 0) { return (int) pendingSeekToUI; } return nextRenderingBitmapTime != 0 ? nextRenderingBitmapTime : renderingBitmapTime; } public int getDurationMs() { return metaData[4]; } private void scheduleNextGetFrame() { if (loadFrameTask != null || nextRenderingBitmap != null || !canLoadFrames() || destroyWhenDone || !isRunning && (!decodeSingleFrame || decodeSingleFrame && singleFrameDecoded) || parents.size() == 0 && !ignoreNoParent || generatingCache) { return; } long ms = 0; if (lastFrameDecodeTime != 0) { ms = Math.min(invalidateAfter, Math.max(0, invalidateAfter - (System.currentTimeMillis() - lastFrameDecodeTime))); } if (useSharedQueue) { if (limitFps) { DispatchQueuePoolBackground.execute(loadFrameTask = loadFrameRunnable); } else { executor.schedule(loadFrameTask = loadFrameRunnable, ms, TimeUnit.MILLISECONDS); } } else { if (decodeQueue == null) { decodeQueue = new DispatchQueue("decodeQueue" + this); } decodeQueue.postRunnable(loadFrameTask = loadFrameRunnable, ms); } } public boolean isLoadingStream() { return stream != null && stream.isWaitingForLoad(); } @Override public void stop() { isRunning = false; } @Override public boolean isRunning() { return isRunning; } @Override public int getIntrinsicHeight() { int height = decoderCreated ? (metaData[2] == 90 || metaData[2] == 270 ? metaData[0] : metaData[1]) : 0; if (height == 0) { return AndroidUtilities.dp(100); } else { height *= scaleFactor; } return height; } @Override public int getIntrinsicWidth() { int width = decoderCreated ? (metaData[2] == 90 || metaData[2] == 270 ? metaData[1] : metaData[0]) : 0; if (width == 0) { return AndroidUtilities.dp(100); } else { width *= scaleFactor; } return width; } @Override protected void onBoundsChange(Rect bounds) { super.onBoundsChange(bounds); applyTransformation = true; } @Override public void draw(Canvas canvas) { drawInternal(canvas, false, System.currentTimeMillis(), 0); } public void drawInBackground(Canvas canvas, float x, float y, float w, float h, int alpha, ColorFilter colorFilter, int threadIndex) { if (dstRectBackground[threadIndex] == null) { dstRectBackground[threadIndex] = new RectF(); backgroundPaint[threadIndex] = new Paint(); backgroundPaint[threadIndex].setFilterBitmap(true); } backgroundPaint[threadIndex].setAlpha(alpha); backgroundPaint[threadIndex].setColorFilter(colorFilter); dstRectBackground[threadIndex].set(x, y, x + w, y + h); drawInternal(canvas, true, 0, threadIndex); } public void drawInternal(Canvas canvas, boolean drawInBackground, long currentTime, int threadIndex) { if (!canLoadFrames() || destroyWhenDone) { return; } if (currentTime == 0) { currentTime = System.currentTimeMillis(); } RectF rect = drawInBackground ? dstRectBackground[threadIndex] : dstRect; Paint paint = drawInBackground ? backgroundPaint[threadIndex] : getPaint(); if (!drawInBackground) { updateCurrentFrame(currentTime, false); } if (renderingBitmap != null) { float scaleX = this.scaleX; float scaleY = this.scaleY; if (drawInBackground) { int bitmapW = renderingBitmap.getWidth(); int bitmapH = renderingBitmap.getHeight(); if (metaData[2] == 90 || metaData[2] == 270) { int temp = bitmapW; bitmapW = bitmapH; bitmapH = temp; } scaleX = rect.width() / bitmapW; scaleY = rect.height() / bitmapH; } else if (applyTransformation) { int bitmapW = renderingBitmap.getWidth(); int bitmapH = renderingBitmap.getHeight(); if (metaData[2] == 90 || metaData[2] == 270) { int temp = bitmapW; bitmapW = bitmapH; bitmapH = temp; } rect.set(getBounds()); this.scaleX = scaleX = rect.width() / bitmapW; this.scaleY = scaleY = rect.height() / bitmapH; applyTransformation = false; } if (hasRoundRadius()) { int index = drawInBackground ? threadIndex + 1 : 0; if (renderingShader[index] == null) { renderingShader[index] = new BitmapShader(renderingBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); } paint.setShader(renderingShader[index]); Matrix matrix = shaderMatrix[index]; if (matrix == null) { matrix = shaderMatrix[index] = new Matrix(); } Path path = roundPath[index]; if (path == null) { path = roundPath[index] = new Path(); } matrix.reset(); matrix.setTranslate(rect.left, rect.top); if (metaData[2] == 90) { matrix.preRotate(90); matrix.preTranslate(0, -rect.width()); } else if (metaData[2] == 180) { matrix.preRotate(180); matrix.preTranslate(-rect.width(), -rect.height()); } else if (metaData[2] == 270) { matrix.preRotate(270); matrix.preTranslate(-rect.height(), 0); } matrix.preScale(scaleX, scaleY); renderingShader[index].setLocalMatrix(matrix); if (invalidatePath || drawInBackground) { if (!drawInBackground) { invalidatePath = false; } for (int a = 0; a < roundRadius.length; a++) { radii[a * 2] = roundRadius[a]; radii[a * 2 + 1] = roundRadius[a]; } path.reset(); path.addRoundRect(drawInBackground ? rect : actualDrawRect, radii, Path.Direction.CW); path.close(); } canvas.drawPath(path, paint); } else { canvas.translate(rect.left, rect.top); if (metaData[2] == 90) { canvas.rotate(90); canvas.translate(0, -rect.width()); } else if (metaData[2] == 180) { canvas.rotate(180); canvas.translate(-rect.width(), -rect.height()); } else if (metaData[2] == 270) { canvas.rotate(270); canvas.translate(-rect.height(), 0); } canvas.scale(scaleX, scaleY); canvas.drawBitmap(renderingBitmap, 0, 0, paint); } } } public long getLastFrameTimestamp() { return lastTimeStamp; } @Override public int getMinimumHeight() { int height = decoderCreated ? (metaData[2] == 90 || metaData[2] == 270 ? metaData[0] : metaData[1]) : 0; if (height == 0) { return AndroidUtilities.dp(100); } return height; } @Override public int getMinimumWidth() { int width = decoderCreated ? (metaData[2] == 90 || metaData[2] == 270 ? metaData[1] : metaData[0]) : 0; if (width == 0) { return AndroidUtilities.dp(100); } return width; } public Bitmap getRenderingBitmap() { return renderingBitmap; } public Bitmap getNextRenderingBitmap() { return nextRenderingBitmap; } public Bitmap getBackgroundBitmap() { return backgroundBitmap; } public Bitmap getAnimatedBitmap() { if (renderingBitmap != null) { return renderingBitmap; } else if (nextRenderingBitmap != null) { return nextRenderingBitmap; } return null; } public void setActualDrawRect(float x, float y, float width, float height) { float bottom = y + height; float right = x + width; if (actualDrawRect.left != x || actualDrawRect.top != y || actualDrawRect.right != right || actualDrawRect.bottom != bottom) { actualDrawRect.set(x, y, right, bottom); invalidatePath = true; } } public void setRoundRadius(int[] value) { if (!secondParentViews.isEmpty()) { if (roundRadiusBackup == null) { roundRadiusBackup = new int[4]; } System.arraycopy(roundRadius, 0, roundRadiusBackup, 0, roundRadiusBackup.length); } for (int i = 0; i < 4; i++) { if (!invalidatePath && value[i] != roundRadius[i]) { invalidatePath = true; } roundRadius[i] = value[i]; } } private boolean hasRoundRadius() { for (int a = 0; a < roundRadius.length; a++) { if (roundRadius[a] != 0) { return true; } } return false; } public boolean hasBitmap() { return canLoadFrames() && (renderingBitmap != null || nextRenderingBitmap != null); } public int getOrientation() { return metaData[2]; } public AnimatedFileDrawable makeCopy() { AnimatedFileDrawable drawable; if (stream != null) { drawable = new AnimatedFileDrawable(path, false, streamFileSize, streamLoadingPriority, stream.getDocument(), stream.getLocation(), stream.getParentObject(), pendingSeekToUI, currentAccount, stream != null && stream.isPreview(), null); } else { drawable = new AnimatedFileDrawable(path, false, streamFileSize, streamLoadingPriority, document, null, null, pendingSeekToUI, currentAccount, stream != null && stream.isPreview(), null); } drawable.metaData[0] = metaData[0]; drawable.metaData[1] = metaData[1]; return drawable; } public static void getVideoInfo(String src, int[] params) { getVideoInfo(Build.VERSION.SDK_INT, src, params); } public void setStartEndTime(long startTime, long endTime) { this.startTime = startTime / 1000f; this.endTime = endTime / 1000f; if (getCurrentProgressMs() < startTime) { seekTo(startTime, true); } } public long getStartTime() { return (long) (startTime * 1000); } public boolean isRecycled() { return isRecycled; } public Bitmap getNextFrame() { if (nativePtr == 0) { return backgroundBitmap; } if (backgroundBitmap == null) { backgroundBitmap = Bitmap.createBitmap((int) (metaData[0] * scaleFactor), (int) (metaData[1] * scaleFactor), Bitmap.Config.ARGB_8888); } getVideoFrame(nativePtr, backgroundBitmap, metaData, backgroundBitmap.getRowBytes(), false, startTime, endTime); return backgroundBitmap; } public void setLimitFps(boolean limitFps) { this.limitFps = limitFps; } public ArrayList<ImageReceiver> getParents() { return parents; } public File getFilePath() { return path; } long cacheGenerateTimestamp; Bitmap generatingCacheBitmap; long cacheGenerateNativePtr; int tryCount; int lastMetadata; @Override public void prepareForGenerateCache() { cacheGenerateNativePtr = createDecoder(path.getAbsolutePath(), metaData, currentAccount, streamFileSize, stream, false); } @Override public void releaseForGenerateCache() { if (cacheGenerateNativePtr != 0) { destroyDecoder(cacheGenerateNativePtr); } } @Override public int getNextFrame(Bitmap bitmap) { if (cacheGenerateNativePtr == 0) { return -1; } Canvas canvas = new Canvas(bitmap); if (generatingCacheBitmap == null) { generatingCacheBitmap = Bitmap.createBitmap(metaData[0], metaData[1], Bitmap.Config.ARGB_8888); } getVideoFrame(cacheGenerateNativePtr, generatingCacheBitmap, metaData, generatingCacheBitmap.getRowBytes(), false, startTime, endTime); if (cacheGenerateTimestamp != 0 && (metaData[3] == 0 || cacheGenerateTimestamp > metaData[3])) { return 0; } if (lastMetadata == metaData[3]) { tryCount++; if (tryCount > 5) { return 0; } } lastMetadata = metaData[3]; bitmap.eraseColor(Color.TRANSPARENT); canvas.save(); float s = (float) renderingWidth / generatingCacheBitmap.getWidth(); canvas.scale(s, s); canvas.drawBitmap(generatingCacheBitmap, 0, 0, null); canvas.restore(); cacheGenerateTimestamp = metaData[3]; return 1; } @Override public Bitmap getFirstFrame(Bitmap bitmap) { if (bitmap == null) { bitmap = Bitmap.createBitmap(renderingWidth, renderingHeight, Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(bitmap); if (generatingCacheBitmap == null) { generatingCacheBitmap = Bitmap.createBitmap(metaData[0], metaData[1], Bitmap.Config.ARGB_8888); } long nativePtr = createDecoder(path.getAbsolutePath(), metaData, currentAccount, streamFileSize, stream, false); if (nativePtr == 0) { return bitmap; } getVideoFrame(nativePtr, generatingCacheBitmap, metaData, generatingCacheBitmap.getRowBytes(), false, startTime, endTime); destroyDecoder(nativePtr); bitmap.eraseColor(Color.TRANSPARENT); canvas.save(); float s = (float) renderingWidth / generatingCacheBitmap.getWidth(); canvas.scale(s, s); canvas.drawBitmap(generatingCacheBitmap, 0, 0, null); canvas.restore(); return bitmap; } public void drawFrame(Canvas canvas, int incFrame) { if (nativePtr == 0) { return; } for (int i = 0; i < incFrame; ++i) { getNextFrame(); } Bitmap bitmap = getBackgroundBitmap(); if (bitmap == null) { bitmap = getNextFrame(); } AndroidUtilities.rectTmp2.set(0, 0, bitmap.getWidth(), bitmap.getHeight()); canvas.drawBitmap(getBackgroundBitmap(), AndroidUtilities.rectTmp2, getBounds(), getPaint()); } public boolean canLoadFrames() { if (precache) { return bitmapsCache != null; } else { return nativePtr != 0 || !decoderCreated; } } public void checkCacheExist() { if (precache && bitmapsCache != null) { bitmapsCache.cacheExist(); } } public void updateCurrentFrame(long now, boolean b) { if (isRunning) { if (renderingBitmap == null && nextRenderingBitmap == null) { scheduleNextGetFrame(); } else if (nextRenderingBitmap != null && (renderingBitmap == null || (Math.abs(now - lastFrameTime) >= invalidateAfter && !skipFrameUpdate))) { //if (precache) { backgroundBitmap = renderingBitmap; // } renderingBitmap = nextRenderingBitmap; renderingBitmapTime = nextRenderingBitmapTime; for (int i = 0; i < backgroundShader.length; i++) { // if (precache) { backgroundShader[i] = renderingShader[i]; // } renderingShader[i] = nextRenderingShader[i]; nextRenderingShader[i] = null; } nextRenderingBitmap = null; nextRenderingBitmapTime = 0; lastFrameTime = now; scheduleNextGetFrame(); } else { invalidateInternal(); } } else if (!isRunning && decodeSingleFrame && Math.abs(now - lastFrameTime) >= invalidateAfter && nextRenderingBitmap != null) { // if (precache) { backgroundBitmap = renderingBitmap; // } renderingBitmap = nextRenderingBitmap; renderingBitmapTime = nextRenderingBitmapTime; for (int i = 0; i < backgroundShader.length; i++) { // if (precache) { backgroundShader[i] = renderingShader[i]; // } renderingShader[i] = nextRenderingShader[i]; nextRenderingShader[i] = null; } nextRenderingBitmap = null; nextRenderingBitmapTime = 0; lastFrameTime = now; scheduleNextGetFrame(); } } }
dawitys/Telegram
TMessagesProj/src/main/java/org/telegram/ui/Components/AnimatedFileDrawable.java
41,708
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.messenger; import android.app.Activity; import android.app.ActivityManager; import android.app.Dialog; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.media.MediaCodecInfo; import android.media.MediaCodecList; import android.os.Build; import android.os.Environment; import android.os.SystemClock; import android.text.TextUtils; import android.util.Base64; import android.webkit.WebView; import androidx.annotation.IntDef; import androidx.annotation.RequiresApi; import androidx.core.content.pm.ShortcutManagerCompat; import org.json.JSONObject; import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.SerializedData; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.AlertDialog; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.Components.SwipeGestureSettingsView; import org.telegram.ui.LaunchActivity; import java.io.File; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; public class SharedConfig { /** * V2: Ping and check time serialized */ private final static int PROXY_SCHEMA_V2 = 2; private final static int PROXY_CURRENT_SCHEMA_VERSION = PROXY_SCHEMA_V2; public final static int PASSCODE_TYPE_PIN = 0, PASSCODE_TYPE_PASSWORD = 1; private static int legacyDevicePerformanceClass = -1; public static boolean loopStickers() { return LiteMode.isEnabled(LiteMode.FLAG_ANIMATED_STICKERS_CHAT); } public static boolean readOnlyStorageDirAlertShowed; public static void checkSdCard(File file) { if (file == null || SharedConfig.storageCacheDir == null || readOnlyStorageDirAlertShowed) { return; } if (file.getPath().startsWith(SharedConfig.storageCacheDir)) { AndroidUtilities.runOnUIThread(() -> { if (readOnlyStorageDirAlertShowed) { return; } BaseFragment fragment = LaunchActivity.getLastFragment(); if (fragment != null && fragment.getParentActivity() != null) { SharedConfig.storageCacheDir = null; SharedConfig.saveConfig(); ImageLoader.getInstance().checkMediaPaths(() -> { }); readOnlyStorageDirAlertShowed = true; AlertDialog.Builder dialog = new AlertDialog.Builder(fragment.getParentActivity()); dialog.setTitle(LocaleController.getString("SdCardError", R.string.SdCardError)); dialog.setSubtitle(LocaleController.getString("SdCardErrorDescription", R.string.SdCardErrorDescription)); dialog.setPositiveButton(LocaleController.getString("DoNotUseSDCard", R.string.DoNotUseSDCard), (dialog1, which) -> { }); Dialog dialogFinal = dialog.create(); dialogFinal.setCanceledOnTouchOutside(false); dialogFinal.show(); } }); } } static Boolean allowPreparingHevcPlayers; public static boolean allowPreparingHevcPlayers() { if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) { return false; } if (allowPreparingHevcPlayers == null) { int codecCount = MediaCodecList.getCodecCount(); int maxInstances = 0; int capabilities = 0; for (int i = 0; i < codecCount; i++) { MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i); if (codecInfo.isEncoder()) { continue; } boolean found = false; for (int k = 0; k < codecInfo.getSupportedTypes().length; k++) { if (codecInfo.getSupportedTypes()[k].contains("video/hevc")) { found = true; break; } } if (!found) { continue; } capabilities = codecInfo.getCapabilitiesForType("video/hevc").getMaxSupportedInstances(); if (capabilities > maxInstances) { maxInstances = capabilities; } } allowPreparingHevcPlayers = maxInstances >= 8; } return allowPreparingHevcPlayers; } public static void toggleSurfaceInStories() { useSurfaceInStories = !useSurfaceInStories; ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE) .edit() .putBoolean("useSurfaceInStories", useSurfaceInStories) .apply(); } public static void togglePhotoViewerBlur() { photoViewerBlur = !photoViewerBlur; ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE) .edit() .putBoolean("photoViewerBlur", photoViewerBlur) .apply(); } private static String goodHevcEncoder; private static HashSet<String> hevcEncoderWhitelist = new HashSet<>(); static { hevcEncoderWhitelist.add("c2.exynos.hevc.encoder"); hevcEncoderWhitelist.add("OMX.Exynos.HEVC.Encoder".toLowerCase()); } @RequiresApi(api = Build.VERSION_CODES.Q) public static String findGoodHevcEncoder() { if (goodHevcEncoder == null) { int codecCount = MediaCodecList.getCodecCount(); for (int i = 0; i < codecCount; i++) { MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i); if (!codecInfo.isEncoder()) { continue; } for (int k = 0; k < codecInfo.getSupportedTypes().length; k++) { if (codecInfo.getSupportedTypes()[k].contains("video/hevc") && codecInfo.isHardwareAccelerated() && isWhitelisted(codecInfo)) { return goodHevcEncoder = codecInfo.getName(); } } } goodHevcEncoder = ""; } return TextUtils.isEmpty(goodHevcEncoder) ? null : goodHevcEncoder; } private static boolean isWhitelisted(MediaCodecInfo codecInfo) { if (BuildVars.DEBUG_PRIVATE_VERSION) { return true; } return hevcEncoderWhitelist.contains(codecInfo.getName().toLowerCase()); } @Retention(RetentionPolicy.SOURCE) @IntDef({ PASSCODE_TYPE_PIN, PASSCODE_TYPE_PASSWORD }) public @interface PasscodeType {} public final static int SAVE_TO_GALLERY_FLAG_PEER = 1; public final static int SAVE_TO_GALLERY_FLAG_GROUP = 2; public final static int SAVE_TO_GALLERY_FLAG_CHANNELS = 4; @PushListenerController.PushType public static int pushType = PushListenerController.PUSH_TYPE_FIREBASE; public static String pushString = ""; public static String pushStringStatus = ""; public static long pushStringGetTimeStart; public static long pushStringGetTimeEnd; public static boolean pushStatSent; public static byte[] pushAuthKey; public static byte[] pushAuthKeyId; public static String directShareHash; @PasscodeType public static int passcodeType; public static String passcodeHash = ""; public static long passcodeRetryInMs; public static long lastUptimeMillis; public static int badPasscodeTries; public static byte[] passcodeSalt = new byte[0]; public static boolean appLocked; public static int autoLockIn = 60 * 60; public static boolean saveIncomingPhotos; public static boolean allowScreenCapture; public static int lastPauseTime; public static boolean isWaitingForPasscodeEnter; public static boolean useFingerprint = true; public static String lastUpdateVersion; public static int suggestStickers; public static boolean suggestAnimatedEmoji; public static int keepMedia = CacheByChatsController.KEEP_MEDIA_ONE_MONTH; //deprecated public static int lastKeepMediaCheckTime; public static int lastLogsCheckTime; public static int searchMessagesAsListHintShows; public static int textSelectionHintShows; public static int scheduledOrNoSoundHintShows; public static long scheduledOrNoSoundHintSeenAt; public static int scheduledHintShows; public static long scheduledHintSeenAt; public static int lockRecordAudioVideoHint; public static boolean forwardingOptionsHintShown; public static boolean searchMessagesAsListUsed; public static boolean stickersReorderingHintUsed; public static int dayNightWallpaperSwitchHint; public static boolean storyReactionsLongPressHint; public static boolean disableVoiceAudioEffects; public static boolean forceDisableTabletMode; public static boolean updateStickersOrderOnSend = true; public static boolean bigCameraForRound; public static boolean useSurfaceInStories; public static boolean photoViewerBlur = true; public static int stealthModeSendMessageConfirm = 2; private static int lastLocalId = -210000; public static String storageCacheDir; private static String passportConfigJson = ""; private static HashMap<String, String> passportConfigMap; public static int passportConfigHash; private static boolean configLoaded; private static final Object sync = new Object(); private static final Object localIdSync = new Object(); // public static int saveToGalleryFlags; public static int mapPreviewType = 2; public static boolean chatBubbles = Build.VERSION.SDK_INT >= 30; public static boolean raiseToSpeak = false; public static boolean raiseToListen = true; public static boolean nextMediaTap = true; public static boolean recordViaSco = false; public static boolean customTabs = true; public static boolean directShare = true; public static boolean inappCamera = true; public static boolean roundCamera16to9 = true; public static boolean noSoundHintShowed = false; public static boolean streamMedia = true; public static boolean streamAllVideo = false; public static boolean streamMkv = false; public static boolean saveStreamMedia = true; public static boolean pauseMusicOnRecord = false; public static boolean pauseMusicOnMedia = false; public static boolean noiseSupression; public static final boolean noStatusBar = true; public static boolean debugWebView; public static boolean sortContactsByName; public static boolean sortFilesByName; public static boolean shuffleMusic; public static boolean playOrderReversed; public static boolean hasCameraCache; public static boolean showNotificationsForAllAccounts = true; public static int repeatMode; public static boolean allowBigEmoji; public static boolean useSystemEmoji; public static int fontSize = 16; public static boolean fontSizeIsDefault; public static int bubbleRadius = 17; public static int ivFontSize = 16; public static boolean proxyRotationEnabled; public static int proxyRotationTimeout; public static int messageSeenHintCount; public static int emojiInteractionsHintCount; public static int dayNightThemeSwitchHintCount; public static TLRPC.TL_help_appUpdate pendingAppUpdate; public static int pendingAppUpdateBuildVersion; public static long lastUpdateCheckTime; public static boolean hasEmailLogin; @PerformanceClass private static int devicePerformanceClass; @PerformanceClass private static int overrideDevicePerformanceClass; public static boolean drawDialogIcons; public static boolean useThreeLinesLayout; public static boolean archiveHidden; private static int chatSwipeAction; public static int distanceSystemType; public static int mediaColumnsCount = 3; public static int storiesColumnsCount = 3; public static int fastScrollHintCount = 3; public static boolean dontAskManageStorage; public static boolean translateChats = true; public static boolean isFloatingDebugActive; public static LiteMode liteMode; private static final int[] LOW_SOC = { -1775228513, // EXYNOS 850 802464304, // EXYNOS 7872 802464333, // EXYNOS 7880 802464302, // EXYNOS 7870 2067362118, // MSM8953 2067362060, // MSM8937 2067362084, // MSM8940 2067362241, // MSM8992 2067362117, // MSM8952 2067361998, // MSM8917 -1853602818 // SDM439 }; static { loadConfig(); } public static class ProxyInfo { public String address; public int port; public String username; public String password; public String secret; public long proxyCheckPingId; public long ping; public boolean checking; public boolean available; public long availableCheckTime; public ProxyInfo(String address, int port, String username, String password, String secret) { this.address = address; this.port = port; this.username = username; this.password = password; this.secret = secret; if (this.address == null) { this.address = ""; } if (this.password == null) { this.password = ""; } if (this.username == null) { this.username = ""; } if (this.secret == null) { this.secret = ""; } } public String getLink() { StringBuilder url = new StringBuilder(!TextUtils.isEmpty(secret) ? "https://t.me/proxy?" : "https://t.me/socks?"); try { url.append("server=").append(URLEncoder.encode(address, "UTF-8")).append("&").append("port=").append(port); if (!TextUtils.isEmpty(username)) { url.append("&user=").append(URLEncoder.encode(username, "UTF-8")); } if (!TextUtils.isEmpty(password)) { url.append("&pass=").append(URLEncoder.encode(password, "UTF-8")); } if (!TextUtils.isEmpty(secret)) { url.append("&secret=").append(URLEncoder.encode(secret, "UTF-8")); } } catch (UnsupportedEncodingException ignored) {} return url.toString(); } } public static ArrayList<ProxyInfo> proxyList = new ArrayList<>(); private static boolean proxyListLoaded; public static ProxyInfo currentProxy; public static void saveConfig() { synchronized (sync) { try { SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("userconfing", Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("saveIncomingPhotos", saveIncomingPhotos); editor.putString("passcodeHash1", passcodeHash); editor.putString("passcodeSalt", passcodeSalt.length > 0 ? Base64.encodeToString(passcodeSalt, Base64.DEFAULT) : ""); editor.putBoolean("appLocked", appLocked); editor.putInt("passcodeType", passcodeType); editor.putLong("passcodeRetryInMs", passcodeRetryInMs); editor.putLong("lastUptimeMillis", lastUptimeMillis); editor.putInt("badPasscodeTries", badPasscodeTries); editor.putInt("autoLockIn", autoLockIn); editor.putInt("lastPauseTime", lastPauseTime); editor.putString("lastUpdateVersion2", lastUpdateVersion); editor.putBoolean("useFingerprint", useFingerprint); editor.putBoolean("allowScreenCapture", allowScreenCapture); editor.putString("pushString2", pushString); editor.putInt("pushType", pushType); editor.putBoolean("pushStatSent", pushStatSent); editor.putString("pushAuthKey", pushAuthKey != null ? Base64.encodeToString(pushAuthKey, Base64.DEFAULT) : ""); editor.putInt("lastLocalId", lastLocalId); editor.putString("passportConfigJson", passportConfigJson); editor.putInt("passportConfigHash", passportConfigHash); editor.putBoolean("sortContactsByName", sortContactsByName); editor.putBoolean("sortFilesByName", sortFilesByName); editor.putInt("textSelectionHintShows", textSelectionHintShows); editor.putInt("scheduledOrNoSoundHintShows", scheduledOrNoSoundHintShows); editor.putLong("scheduledOrNoSoundHintSeenAt", scheduledOrNoSoundHintSeenAt); editor.putInt("scheduledHintShows", scheduledHintShows); editor.putLong("scheduledHintSeenAt", scheduledHintSeenAt); editor.putBoolean("forwardingOptionsHintShown", forwardingOptionsHintShown); editor.putInt("lockRecordAudioVideoHint", lockRecordAudioVideoHint); editor.putString("storageCacheDir", !TextUtils.isEmpty(storageCacheDir) ? storageCacheDir : ""); editor.putBoolean("proxyRotationEnabled", proxyRotationEnabled); editor.putInt("proxyRotationTimeout", proxyRotationTimeout); if (pendingAppUpdate != null) { try { SerializedData data = new SerializedData(pendingAppUpdate.getObjectSize()); pendingAppUpdate.serializeToStream(data); String str = Base64.encodeToString(data.toByteArray(), Base64.DEFAULT); editor.putString("appUpdate", str); editor.putInt("appUpdateBuild", pendingAppUpdateBuildVersion); data.cleanup(); } catch (Exception ignore) { } } else { editor.remove("appUpdate"); } editor.putLong("appUpdateCheckTime", lastUpdateCheckTime); editor.apply(); editor = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Context.MODE_PRIVATE).edit(); editor.putBoolean("hasEmailLogin", hasEmailLogin); editor.putBoolean("floatingDebugActive", isFloatingDebugActive); editor.putBoolean("record_via_sco", recordViaSco); editor.apply(); } catch (Exception e) { FileLog.e(e); } } } public static int getLastLocalId() { int value; synchronized (localIdSync) { value = lastLocalId--; } return value; } public static void loadConfig() { synchronized (sync) { if (configLoaded || ApplicationLoader.applicationContext == null) { return; } BackgroundActivityPrefs.prefs = ApplicationLoader.applicationContext.getSharedPreferences("background_activity", Context.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("userconfing", Context.MODE_PRIVATE); saveIncomingPhotos = preferences.getBoolean("saveIncomingPhotos", false); passcodeHash = preferences.getString("passcodeHash1", ""); appLocked = preferences.getBoolean("appLocked", false); passcodeType = preferences.getInt("passcodeType", 0); passcodeRetryInMs = preferences.getLong("passcodeRetryInMs", 0); lastUptimeMillis = preferences.getLong("lastUptimeMillis", 0); badPasscodeTries = preferences.getInt("badPasscodeTries", 0); autoLockIn = preferences.getInt("autoLockIn", 60 * 60); lastPauseTime = preferences.getInt("lastPauseTime", 0); useFingerprint = preferences.getBoolean("useFingerprint", true); lastUpdateVersion = preferences.getString("lastUpdateVersion2", "3.5"); allowScreenCapture = preferences.getBoolean("allowScreenCapture", false); lastLocalId = preferences.getInt("lastLocalId", -210000); pushString = preferences.getString("pushString2", ""); pushType = preferences.getInt("pushType", PushListenerController.PUSH_TYPE_FIREBASE); pushStatSent = preferences.getBoolean("pushStatSent", false); passportConfigJson = preferences.getString("passportConfigJson", ""); passportConfigHash = preferences.getInt("passportConfigHash", 0); storageCacheDir = preferences.getString("storageCacheDir", null); proxyRotationEnabled = preferences.getBoolean("proxyRotationEnabled", false); proxyRotationTimeout = preferences.getInt("proxyRotationTimeout", ProxyRotationController.DEFAULT_TIMEOUT_INDEX); String authKeyString = preferences.getString("pushAuthKey", null); if (!TextUtils.isEmpty(authKeyString)) { pushAuthKey = Base64.decode(authKeyString, Base64.DEFAULT); } if (passcodeHash.length() > 0 && lastPauseTime == 0) { lastPauseTime = (int) (SystemClock.elapsedRealtime() / 1000 - 60 * 10); } String passcodeSaltString = preferences.getString("passcodeSalt", ""); if (passcodeSaltString.length() > 0) { passcodeSalt = Base64.decode(passcodeSaltString, Base64.DEFAULT); } else { passcodeSalt = new byte[0]; } lastUpdateCheckTime = preferences.getLong("appUpdateCheckTime", System.currentTimeMillis()); try { String update = preferences.getString("appUpdate", null); if (update != null) { pendingAppUpdateBuildVersion = preferences.getInt("appUpdateBuild", BuildVars.BUILD_VERSION); byte[] arr = Base64.decode(update, Base64.DEFAULT); if (arr != null) { SerializedData data = new SerializedData(arr); pendingAppUpdate = (TLRPC.TL_help_appUpdate) TLRPC.help_AppUpdate.TLdeserialize(data, data.readInt32(false), false); data.cleanup(); } } if (pendingAppUpdate != null) { long updateTime = 0; int updateVersion = 0; String updateVersionString = null; try { PackageInfo packageInfo = ApplicationLoader.applicationContext.getPackageManager().getPackageInfo(ApplicationLoader.applicationContext.getPackageName(), 0); updateVersion = packageInfo.versionCode; updateVersionString = packageInfo.versionName; } catch (Exception e) { FileLog.e(e); } if (updateVersion == 0) { updateVersion = BuildVars.BUILD_VERSION; } if (updateVersionString == null) { updateVersionString = BuildVars.BUILD_VERSION_STRING; } if (pendingAppUpdateBuildVersion != updateVersion || pendingAppUpdate.version == null || updateVersionString.compareTo(pendingAppUpdate.version) >= 0 || BuildVars.DEBUG_PRIVATE_VERSION) { pendingAppUpdate = null; AndroidUtilities.runOnUIThread(SharedConfig::saveConfig); } } } catch (Exception e) { FileLog.e(e); } preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); SaveToGallerySettingsHelper.load(preferences); mapPreviewType = preferences.getInt("mapPreviewType", 2); raiseToListen = preferences.getBoolean("raise_to_listen", true); raiseToSpeak = preferences.getBoolean("raise_to_speak", false); nextMediaTap = preferences.getBoolean("next_media_on_tap", true); recordViaSco = preferences.getBoolean("record_via_sco", false); customTabs = preferences.getBoolean("custom_tabs", true); directShare = preferences.getBoolean("direct_share", true); shuffleMusic = preferences.getBoolean("shuffleMusic", false); playOrderReversed = !shuffleMusic && preferences.getBoolean("playOrderReversed", false); inappCamera = preferences.getBoolean("inappCamera", true); hasCameraCache = preferences.contains("cameraCache"); roundCamera16to9 = true; repeatMode = preferences.getInt("repeatMode", 0); fontSize = preferences.getInt("fons_size", AndroidUtilities.isTablet() ? 18 : 16); fontSizeIsDefault = !preferences.contains("fons_size"); bubbleRadius = preferences.getInt("bubbleRadius", 17); ivFontSize = preferences.getInt("iv_font_size", fontSize); allowBigEmoji = preferences.getBoolean("allowBigEmoji", true); useSystemEmoji = preferences.getBoolean("useSystemEmoji", false); streamMedia = preferences.getBoolean("streamMedia", true); saveStreamMedia = preferences.getBoolean("saveStreamMedia", true); pauseMusicOnRecord = preferences.getBoolean("pauseMusicOnRecord", false); pauseMusicOnMedia = preferences.getBoolean("pauseMusicOnMedia", false); forceDisableTabletMode = preferences.getBoolean("forceDisableTabletMode", false); streamAllVideo = preferences.getBoolean("streamAllVideo", BuildVars.DEBUG_VERSION); streamMkv = preferences.getBoolean("streamMkv", false); suggestStickers = preferences.getInt("suggestStickers", 0); suggestAnimatedEmoji = preferences.getBoolean("suggestAnimatedEmoji", true); overrideDevicePerformanceClass = preferences.getInt("overrideDevicePerformanceClass", -1); devicePerformanceClass = preferences.getInt("devicePerformanceClass", -1); sortContactsByName = preferences.getBoolean("sortContactsByName", false); sortFilesByName = preferences.getBoolean("sortFilesByName", false); noSoundHintShowed = preferences.getBoolean("noSoundHintShowed", false); directShareHash = preferences.getString("directShareHash2", null); useThreeLinesLayout = preferences.getBoolean("useThreeLinesLayout", false); archiveHidden = preferences.getBoolean("archiveHidden", false); distanceSystemType = preferences.getInt("distanceSystemType", 0); keepMedia = preferences.getInt("keep_media", CacheByChatsController.KEEP_MEDIA_ONE_MONTH); debugWebView = preferences.getBoolean("debugWebView", false); lastKeepMediaCheckTime = preferences.getInt("lastKeepMediaCheckTime", 0); lastLogsCheckTime = preferences.getInt("lastLogsCheckTime", 0); searchMessagesAsListHintShows = preferences.getInt("searchMessagesAsListHintShows", 0); searchMessagesAsListUsed = preferences.getBoolean("searchMessagesAsListUsed", false); stickersReorderingHintUsed = preferences.getBoolean("stickersReorderingHintUsed", false); storyReactionsLongPressHint = preferences.getBoolean("storyReactionsLongPressHint", false); textSelectionHintShows = preferences.getInt("textSelectionHintShows", 0); scheduledOrNoSoundHintShows = preferences.getInt("scheduledOrNoSoundHintShows", 0); scheduledOrNoSoundHintSeenAt = preferences.getLong("scheduledOrNoSoundHintSeenAt", 0); scheduledHintShows = preferences.getInt("scheduledHintShows", 0); scheduledHintSeenAt = preferences.getLong("scheduledHintSeenAt", 0); forwardingOptionsHintShown = preferences.getBoolean("forwardingOptionsHintShown", false); lockRecordAudioVideoHint = preferences.getInt("lockRecordAudioVideoHint", 0); disableVoiceAudioEffects = preferences.getBoolean("disableVoiceAudioEffects", false); noiseSupression = preferences.getBoolean("noiseSupression", false); chatSwipeAction = preferences.getInt("ChatSwipeAction", -1); messageSeenHintCount = preferences.getInt("messageSeenCount", 3); emojiInteractionsHintCount = preferences.getInt("emojiInteractionsHintCount", 3); dayNightThemeSwitchHintCount = preferences.getInt("dayNightThemeSwitchHintCount", 3); stealthModeSendMessageConfirm = preferences.getInt("stealthModeSendMessageConfirm", 2); mediaColumnsCount = preferences.getInt("mediaColumnsCount", 3); storiesColumnsCount = preferences.getInt("storiesColumnsCount", 3); fastScrollHintCount = preferences.getInt("fastScrollHintCount", 3); dontAskManageStorage = preferences.getBoolean("dontAskManageStorage", false); hasEmailLogin = preferences.getBoolean("hasEmailLogin", false); isFloatingDebugActive = preferences.getBoolean("floatingDebugActive", false); updateStickersOrderOnSend = preferences.getBoolean("updateStickersOrderOnSend", true); dayNightWallpaperSwitchHint = preferences.getInt("dayNightWallpaperSwitchHint", 0); bigCameraForRound = preferences.getBoolean("bigCameraForRound", false); useSurfaceInStories = preferences.getBoolean("useSurfaceInStories", Build.VERSION.SDK_INT >= 30); photoViewerBlur = preferences.getBoolean("photoViewerBlur", true); loadDebugConfig(preferences); preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); showNotificationsForAllAccounts = preferences.getBoolean("AllAccounts", true); configLoaded = true; try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && debugWebView) { WebView.setWebContentsDebuggingEnabled(true); } } catch (Exception e) { FileLog.e(e); } } } public static void updateTabletConfig() { if (fontSizeIsDefault) { SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); fontSize = preferences.getInt("fons_size", AndroidUtilities.isTablet() ? 18 : 16); ivFontSize = preferences.getInt("iv_font_size", fontSize); } } public static void increaseBadPasscodeTries() { badPasscodeTries++; if (badPasscodeTries >= 3) { switch (badPasscodeTries) { case 3: passcodeRetryInMs = 5000; break; case 4: passcodeRetryInMs = 10000; break; case 5: passcodeRetryInMs = 15000; break; case 6: passcodeRetryInMs = 20000; break; case 7: passcodeRetryInMs = 25000; break; default: passcodeRetryInMs = 30000; break; } lastUptimeMillis = SystemClock.elapsedRealtime(); } saveConfig(); } public static boolean isAutoplayVideo() { return LiteMode.isEnabled(LiteMode.FLAG_AUTOPLAY_VIDEOS); } public static boolean isAutoplayGifs() { return LiteMode.isEnabled(LiteMode.FLAG_AUTOPLAY_GIFS); } public static boolean isPassportConfigLoaded() { return passportConfigMap != null; } public static void setPassportConfig(String json, int hash) { passportConfigMap = null; passportConfigJson = json; passportConfigHash = hash; saveConfig(); getCountryLangs(); } public static HashMap<String, String> getCountryLangs() { if (passportConfigMap == null) { passportConfigMap = new HashMap<>(); try { JSONObject object = new JSONObject(passportConfigJson); Iterator<String> iter = object.keys(); while (iter.hasNext()) { String key = iter.next(); passportConfigMap.put(key.toUpperCase(), object.getString(key).toUpperCase()); } } catch (Throwable e) { FileLog.e(e); } } return passportConfigMap; } public static boolean isAppUpdateAvailable() { if (pendingAppUpdate == null || pendingAppUpdate.document == null || !BuildVars.isStandaloneApp()) { return false; } int currentVersion; try { PackageInfo pInfo = ApplicationLoader.applicationContext.getPackageManager().getPackageInfo(ApplicationLoader.applicationContext.getPackageName(), 0); currentVersion = pInfo.versionCode; } catch (Exception e) { FileLog.e(e); currentVersion = BuildVars.BUILD_VERSION; } return pendingAppUpdateBuildVersion == currentVersion; } public static boolean setNewAppVersionAvailable(TLRPC.TL_help_appUpdate update) { String updateVersionString = null; int versionCode = 0; try { PackageInfo packageInfo = ApplicationLoader.applicationContext.getPackageManager().getPackageInfo(ApplicationLoader.applicationContext.getPackageName(), 0); versionCode = packageInfo.versionCode; updateVersionString = packageInfo.versionName; } catch (Exception e) { FileLog.e(e); } if (versionCode == 0) { versionCode = BuildVars.BUILD_VERSION; } if (updateVersionString == null) { updateVersionString = BuildVars.BUILD_VERSION_STRING; } if (update.version == null || versionBiggerOrEqual(updateVersionString, update.version)) { return false; } pendingAppUpdate = update; pendingAppUpdateBuildVersion = versionCode; saveConfig(); return true; } // returns a >= b private static boolean versionBiggerOrEqual(String a, String b) { String[] partsA = a.split("\\."); String[] partsB = b.split("\\."); for (int i = 0; i < Math.min(partsA.length, partsB.length); ++i) { int numA = Integer.parseInt(partsA[i]); int numB = Integer.parseInt(partsB[i]); if (numA < numB) { return false; } else if (numA > numB) { return true; } } return true; } public static boolean checkPasscode(String passcode) { if (passcodeSalt.length == 0) { boolean result = Utilities.MD5(passcode).equals(passcodeHash); if (result) { try { passcodeSalt = new byte[16]; Utilities.random.nextBytes(passcodeSalt); byte[] passcodeBytes = passcode.getBytes("UTF-8"); byte[] bytes = new byte[32 + passcodeBytes.length]; System.arraycopy(passcodeSalt, 0, bytes, 0, 16); System.arraycopy(passcodeBytes, 0, bytes, 16, passcodeBytes.length); System.arraycopy(passcodeSalt, 0, bytes, passcodeBytes.length + 16, 16); passcodeHash = Utilities.bytesToHex(Utilities.computeSHA256(bytes, 0, bytes.length)); saveConfig(); } catch (Exception e) { FileLog.e(e); } } return result; } else { try { byte[] passcodeBytes = passcode.getBytes("UTF-8"); byte[] bytes = new byte[32 + passcodeBytes.length]; System.arraycopy(passcodeSalt, 0, bytes, 0, 16); System.arraycopy(passcodeBytes, 0, bytes, 16, passcodeBytes.length); System.arraycopy(passcodeSalt, 0, bytes, passcodeBytes.length + 16, 16); String hash = Utilities.bytesToHex(Utilities.computeSHA256(bytes, 0, bytes.length)); return passcodeHash.equals(hash); } catch (Exception e) { FileLog.e(e); } } return false; } public static void clearConfig() { saveIncomingPhotos = false; appLocked = false; passcodeType = PASSCODE_TYPE_PIN; passcodeRetryInMs = 0; lastUptimeMillis = 0; badPasscodeTries = 0; passcodeHash = ""; passcodeSalt = new byte[0]; autoLockIn = 60 * 60; lastPauseTime = 0; useFingerprint = true; isWaitingForPasscodeEnter = false; allowScreenCapture = false; lastUpdateVersion = BuildVars.BUILD_VERSION_STRING; textSelectionHintShows = 0; scheduledOrNoSoundHintShows = 0; scheduledOrNoSoundHintSeenAt = 0; scheduledHintShows = 0; scheduledHintSeenAt = 0; lockRecordAudioVideoHint = 0; forwardingOptionsHintShown = false; messageSeenHintCount = 3; emojiInteractionsHintCount = 3; dayNightThemeSwitchHintCount = 3; stealthModeSendMessageConfirm = 2; dayNightWallpaperSwitchHint = 0; saveConfig(); } public static void setSuggestStickers(int type) { suggestStickers = type; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("suggestStickers", suggestStickers); editor.apply(); } public static void setSearchMessagesAsListUsed(boolean value) { searchMessagesAsListUsed = value; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("searchMessagesAsListUsed", searchMessagesAsListUsed); editor.apply(); } public static void setStickersReorderingHintUsed(boolean value) { stickersReorderingHintUsed = value; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("stickersReorderingHintUsed", stickersReorderingHintUsed); editor.apply(); } public static void setStoriesReactionsLongPressHintUsed(boolean value) { storyReactionsLongPressHint = value; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("storyReactionsLongPressHint", storyReactionsLongPressHint); editor.apply(); } public static void increaseTextSelectionHintShowed() { SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("textSelectionHintShows", ++textSelectionHintShows); editor.apply(); } public static void increaseDayNightWallpaperSiwtchHint() { SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("dayNightWallpaperSwitchHint", ++dayNightWallpaperSwitchHint); editor.apply(); } public static void removeTextSelectionHint() { SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("textSelectionHintShows", 3); editor.apply(); } public static void increaseScheduledOrNoSoundHintShowed() { SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); scheduledOrNoSoundHintSeenAt = System.currentTimeMillis(); editor.putInt("scheduledOrNoSoundHintShows", ++scheduledOrNoSoundHintShows); editor.putLong("scheduledOrNoSoundHintSeenAt", scheduledOrNoSoundHintSeenAt); editor.apply(); } public static void increaseScheduledHintShowed() { SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); scheduledHintSeenAt = System.currentTimeMillis(); editor.putInt("scheduledHintShows", ++scheduledHintShows); editor.putLong("scheduledHintSeenAt", scheduledHintSeenAt); editor.apply(); } public static void forwardingOptionsHintHintShowed() { SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); forwardingOptionsHintShown = true; editor.putBoolean("forwardingOptionsHintShown", forwardingOptionsHintShown); editor.apply(); } public static void removeScheduledOrNoSoundHint() { SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("scheduledOrNoSoundHintShows", 3); editor.apply(); } public static void removeScheduledHint() { SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("scheduledHintShows", 3); editor.apply(); } public static void increaseLockRecordAudioVideoHintShowed() { SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("lockRecordAudioVideoHint", ++lockRecordAudioVideoHint); editor.apply(); } public static void removeLockRecordAudioVideoHint() { SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("lockRecordAudioVideoHint", 3); editor.apply(); } public static void increaseSearchAsListHintShows() { SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("searchMessagesAsListHintShows", ++searchMessagesAsListHintShows); editor.apply(); } public static void setKeepMedia(int value) { keepMedia = value; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("keep_media", keepMedia); editor.apply(); } public static void toggleUpdateStickersOrderOnSend() { SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("updateStickersOrderOnSend", updateStickersOrderOnSend = !updateStickersOrderOnSend); editor.apply(); } public static void checkLogsToDelete() { if (!BuildVars.LOGS_ENABLED) { return; } int time = (int) (System.currentTimeMillis() / 1000); if (Math.abs(time - lastLogsCheckTime) < 60 * 60) { return; } lastLogsCheckTime = time; Utilities.cacheClearQueue.postRunnable(() -> { long currentTime = time - 60 * 60 * 24 * 10; try { File dir = AndroidUtilities.getLogsDir(); if (dir == null) { return; } Utilities.clearDir(dir.getAbsolutePath(), 0, currentTime, false); } catch (Throwable e) { FileLog.e(e); } SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("lastLogsCheckTime", lastLogsCheckTime); editor.apply(); }); } public static void toggleDisableVoiceAudioEffects() { disableVoiceAudioEffects = !disableVoiceAudioEffects; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("disableVoiceAudioEffects", disableVoiceAudioEffects); editor.apply(); } public static void toggleNoiseSupression() { noiseSupression = !noiseSupression; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("noiseSupression", noiseSupression); editor.apply(); } public static void toggleDebugWebView() { debugWebView = !debugWebView; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { WebView.setWebContentsDebuggingEnabled(debugWebView); } SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("debugWebView", debugWebView); editor.apply(); } public static void toggleLoopStickers() { LiteMode.toggleFlag(LiteMode.FLAG_ANIMATED_STICKERS_CHAT); } public static void toggleBigEmoji() { allowBigEmoji = !allowBigEmoji; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("allowBigEmoji", allowBigEmoji); editor.apply(); } public static void toggleSuggestAnimatedEmoji() { suggestAnimatedEmoji = !suggestAnimatedEmoji; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("suggestAnimatedEmoji", suggestAnimatedEmoji); editor.apply(); } public static void setPlaybackOrderType(int type) { if (type == 2) { shuffleMusic = true; playOrderReversed = false; } else if (type == 1) { playOrderReversed = true; shuffleMusic = false; } else { playOrderReversed = false; shuffleMusic = false; } MediaController.getInstance().checkIsNextMediaFileDownloaded(); SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("shuffleMusic", shuffleMusic); editor.putBoolean("playOrderReversed", playOrderReversed); editor.apply(); } public static void setRepeatMode(int mode) { repeatMode = mode; if (repeatMode < 0 || repeatMode > 2) { repeatMode = 0; } SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("repeatMode", repeatMode); editor.apply(); } public static void overrideDevicePerformanceClass(int performanceClass) { MessagesController.getGlobalMainSettings().edit().putInt("overrideDevicePerformanceClass", overrideDevicePerformanceClass = performanceClass).remove("lite_mode").apply(); if (liteMode != null) { liteMode.loadPreference(); } } public static void toggleAutoplayGifs() { LiteMode.toggleFlag(LiteMode.FLAG_AUTOPLAY_GIFS); } public static void setUseThreeLinesLayout(boolean value) { useThreeLinesLayout = value; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("useThreeLinesLayout", useThreeLinesLayout); editor.apply(); NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.dialogsNeedReload, true); } public static void toggleArchiveHidden() { archiveHidden = !archiveHidden; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("archiveHidden", archiveHidden); editor.apply(); } public static void toggleAutoplayVideo() { LiteMode.toggleFlag(LiteMode.FLAG_AUTOPLAY_VIDEOS); } public static boolean isSecretMapPreviewSet() { SharedPreferences preferences = MessagesController.getGlobalMainSettings(); return preferences.contains("mapPreviewType"); } public static void setSecretMapPreviewType(int value) { mapPreviewType = value; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("mapPreviewType", mapPreviewType); editor.apply(); } public static void setNoSoundHintShowed(boolean value) { if (noSoundHintShowed == value) { return; } noSoundHintShowed = value; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("noSoundHintShowed", noSoundHintShowed); editor.apply(); } public static void toggleRaiseToSpeak() { raiseToSpeak = !raiseToSpeak; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("raise_to_speak", raiseToSpeak); editor.apply(); } public static void toggleRaiseToListen() { raiseToListen = !raiseToListen; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("raise_to_listen", raiseToListen); editor.apply(); } public static void toggleNextMediaTap() { nextMediaTap = !nextMediaTap; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("next_media_on_tap", nextMediaTap); editor.apply(); } public static boolean enabledRaiseTo(boolean speak) { return raiseToListen && (!speak || raiseToSpeak); } public static void toggleCustomTabs() { customTabs = !customTabs; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("custom_tabs", customTabs); editor.apply(); } public static void toggleDirectShare() { directShare = !directShare; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("direct_share", directShare); editor.apply(); ShortcutManagerCompat.removeAllDynamicShortcuts(ApplicationLoader.applicationContext); MediaDataController.getInstance(UserConfig.selectedAccount).buildShortcuts(); } public static void toggleStreamMedia() { streamMedia = !streamMedia; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("streamMedia", streamMedia); editor.apply(); } public static void toggleSortContactsByName() { sortContactsByName = !sortContactsByName; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("sortContactsByName", sortContactsByName); editor.apply(); } public static void toggleSortFilesByName() { sortFilesByName = !sortFilesByName; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("sortFilesByName", sortFilesByName); editor.apply(); } public static void toggleStreamAllVideo() { streamAllVideo = !streamAllVideo; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("streamAllVideo", streamAllVideo); editor.apply(); } public static void toggleStreamMkv() { streamMkv = !streamMkv; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("streamMkv", streamMkv); editor.apply(); } public static void toggleSaveStreamMedia() { saveStreamMedia = !saveStreamMedia; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("saveStreamMedia", saveStreamMedia); editor.apply(); } public static void togglePauseMusicOnRecord() { pauseMusicOnRecord = !pauseMusicOnRecord; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("pauseMusicOnRecord", pauseMusicOnRecord); editor.apply(); } public static void togglePauseMusicOnMedia() { pauseMusicOnMedia = !pauseMusicOnMedia; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("pauseMusicOnMedia", pauseMusicOnMedia); editor.apply(); } public static void toggleChatBlur() { LiteMode.toggleFlag(LiteMode.FLAG_CHAT_BLUR); } public static void toggleForceDisableTabletMode() { forceDisableTabletMode = !forceDisableTabletMode; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("forceDisableTabletMode", forceDisableTabletMode); editor.apply(); } public static void toggleInappCamera() { inappCamera = !inappCamera; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("inappCamera", inappCamera); editor.apply(); } public static void toggleRoundCamera16to9() { roundCamera16to9 = !roundCamera16to9; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("roundCamera16to9", roundCamera16to9); editor.apply(); } public static void setDistanceSystemType(int type) { distanceSystemType = type; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("distanceSystemType", distanceSystemType); editor.apply(); LocaleController.resetImperialSystemType(); } public static void loadProxyList() { if (proxyListLoaded) { return; } SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); String proxyAddress = preferences.getString("proxy_ip", ""); String proxyUsername = preferences.getString("proxy_user", ""); String proxyPassword = preferences.getString("proxy_pass", ""); String proxySecret = preferences.getString("proxy_secret", ""); int proxyPort = preferences.getInt("proxy_port", 1080); proxyListLoaded = true; proxyList.clear(); currentProxy = null; String list = preferences.getString("proxy_list", null); if (!TextUtils.isEmpty(list)) { byte[] bytes = Base64.decode(list, Base64.DEFAULT); SerializedData data = new SerializedData(bytes); int count = data.readInt32(false); if (count == -1) { // V2 or newer int version = data.readByte(false); if (version == PROXY_SCHEMA_V2) { count = data.readInt32(false); for (int i = 0; i < count; i++) { ProxyInfo info = new ProxyInfo( data.readString(false), data.readInt32(false), data.readString(false), data.readString(false), data.readString(false)); info.ping = data.readInt64(false); info.availableCheckTime = data.readInt64(false); proxyList.add(0, info); if (currentProxy == null && !TextUtils.isEmpty(proxyAddress)) { if (proxyAddress.equals(info.address) && proxyPort == info.port && proxyUsername.equals(info.username) && proxyPassword.equals(info.password)) { currentProxy = info; } } } } else { FileLog.e("Unknown proxy schema version: " + version); } } else { for (int a = 0; a < count; a++) { ProxyInfo info = new ProxyInfo( data.readString(false), data.readInt32(false), data.readString(false), data.readString(false), data.readString(false)); proxyList.add(0, info); if (currentProxy == null && !TextUtils.isEmpty(proxyAddress)) { if (proxyAddress.equals(info.address) && proxyPort == info.port && proxyUsername.equals(info.username) && proxyPassword.equals(info.password)) { currentProxy = info; } } } } data.cleanup(); } if (currentProxy == null && !TextUtils.isEmpty(proxyAddress)) { ProxyInfo info = currentProxy = new ProxyInfo(proxyAddress, proxyPort, proxyUsername, proxyPassword, proxySecret); proxyList.add(0, info); } } public static void saveProxyList() { List<ProxyInfo> infoToSerialize = new ArrayList<>(proxyList); Collections.sort(infoToSerialize, (o1, o2) -> { long bias1 = SharedConfig.currentProxy == o1 ? -200000 : 0; if (!o1.available) { bias1 += 100000; } long bias2 = SharedConfig.currentProxy == o2 ? -200000 : 0; if (!o2.available) { bias2 += 100000; } return Long.compare(o1.ping + bias1, o2.ping + bias2); }); SerializedData serializedData = new SerializedData(); serializedData.writeInt32(-1); serializedData.writeByte(PROXY_CURRENT_SCHEMA_VERSION); int count = infoToSerialize.size(); serializedData.writeInt32(count); for (int a = count - 1; a >= 0; a--) { ProxyInfo info = infoToSerialize.get(a); serializedData.writeString(info.address != null ? info.address : ""); serializedData.writeInt32(info.port); serializedData.writeString(info.username != null ? info.username : ""); serializedData.writeString(info.password != null ? info.password : ""); serializedData.writeString(info.secret != null ? info.secret : ""); serializedData.writeInt64(info.ping); serializedData.writeInt64(info.availableCheckTime); } SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); preferences.edit().putString("proxy_list", Base64.encodeToString(serializedData.toByteArray(), Base64.NO_WRAP)).apply(); serializedData.cleanup(); } public static ProxyInfo addProxy(ProxyInfo proxyInfo) { loadProxyList(); int count = proxyList.size(); for (int a = 0; a < count; a++) { ProxyInfo info = proxyList.get(a); if (proxyInfo.address.equals(info.address) && proxyInfo.port == info.port && proxyInfo.username.equals(info.username) && proxyInfo.password.equals(info.password) && proxyInfo.secret.equals(info.secret)) { return info; } } proxyList.add(0, proxyInfo); saveProxyList(); return proxyInfo; } public static boolean isProxyEnabled() { return MessagesController.getGlobalMainSettings().getBoolean("proxy_enabled", false) && currentProxy != null; } public static void deleteProxy(ProxyInfo proxyInfo) { if (currentProxy == proxyInfo) { currentProxy = null; SharedPreferences preferences = MessagesController.getGlobalMainSettings(); boolean enabled = preferences.getBoolean("proxy_enabled", false); SharedPreferences.Editor editor = preferences.edit(); editor.putString("proxy_ip", ""); editor.putString("proxy_pass", ""); editor.putString("proxy_user", ""); editor.putString("proxy_secret", ""); editor.putInt("proxy_port", 1080); editor.putBoolean("proxy_enabled", false); editor.putBoolean("proxy_enabled_calls", false); editor.apply(); if (enabled) { ConnectionsManager.setProxySettings(false, "", 0, "", "", ""); } } proxyList.remove(proxyInfo); saveProxyList(); } public static void checkSaveToGalleryFiles() { Utilities.globalQueue.postRunnable(() -> { try { File telegramPath = new File(Environment.getExternalStorageDirectory(), "Telegram"); File imagePath = new File(telegramPath, "Telegram Images"); imagePath.mkdir(); File videoPath = new File(telegramPath, "Telegram Video"); videoPath.mkdir(); if (!BuildVars.NO_SCOPED_STORAGE) { if (imagePath.isDirectory()) { new File(imagePath, ".nomedia").delete(); } if (videoPath.isDirectory()) { new File(videoPath, ".nomedia").delete(); } } else { if (imagePath.isDirectory()) { AndroidUtilities.createEmptyFile(new File(imagePath, ".nomedia")); } if (videoPath.isDirectory()) { AndroidUtilities.createEmptyFile(new File(videoPath, ".nomedia")); } } } catch (Throwable e) { FileLog.e(e); } }); } public static int getChatSwipeAction(int currentAccount) { if (chatSwipeAction >= 0) { if (chatSwipeAction == SwipeGestureSettingsView.SWIPE_GESTURE_FOLDERS && MessagesController.getInstance(currentAccount).dialogFilters.isEmpty()) { return SwipeGestureSettingsView.SWIPE_GESTURE_ARCHIVE; } return chatSwipeAction; } else if (!MessagesController.getInstance(currentAccount).dialogFilters.isEmpty()) { return SwipeGestureSettingsView.SWIPE_GESTURE_FOLDERS; } return SwipeGestureSettingsView.SWIPE_GESTURE_ARCHIVE; } public static void updateChatListSwipeSetting(int newAction) { chatSwipeAction = newAction; SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); preferences.edit().putInt("ChatSwipeAction", chatSwipeAction).apply(); } public static void updateMessageSeenHintCount(int count) { messageSeenHintCount = count; SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); preferences.edit().putInt("messageSeenCount", messageSeenHintCount).apply(); } public static void updateEmojiInteractionsHintCount(int count) { emojiInteractionsHintCount = count; SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); preferences.edit().putInt("emojiInteractionsHintCount", emojiInteractionsHintCount).apply(); } public static void updateDayNightThemeSwitchHintCount(int count) { dayNightThemeSwitchHintCount = count; SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); preferences.edit().putInt("dayNightThemeSwitchHintCount", dayNightThemeSwitchHintCount).apply(); } public static void updateStealthModeSendMessageConfirm(int count) { stealthModeSendMessageConfirm = count; SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); preferences.edit().putInt("stealthModeSendMessageConfirm", stealthModeSendMessageConfirm).apply(); } public final static int PERFORMANCE_CLASS_LOW = 0; public final static int PERFORMANCE_CLASS_AVERAGE = 1; public final static int PERFORMANCE_CLASS_HIGH = 2; @Retention(RetentionPolicy.SOURCE) @IntDef({ PERFORMANCE_CLASS_LOW, PERFORMANCE_CLASS_AVERAGE, PERFORMANCE_CLASS_HIGH }) public @interface PerformanceClass {} @PerformanceClass public static int getDevicePerformanceClass() { if (overrideDevicePerformanceClass != -1) { return overrideDevicePerformanceClass; } if (devicePerformanceClass == -1) { devicePerformanceClass = measureDevicePerformanceClass(); } return devicePerformanceClass; } public static int measureDevicePerformanceClass() { int androidVersion = Build.VERSION.SDK_INT; int cpuCount = ConnectionsManager.CPU_COUNT; int memoryClass = ((ActivityManager) ApplicationLoader.applicationContext.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && Build.SOC_MODEL != null) { int hash = Build.SOC_MODEL.toUpperCase().hashCode(); for (int i = 0; i < LOW_SOC.length; ++i) { if (LOW_SOC[i] == hash) { return PERFORMANCE_CLASS_LOW; } } } int totalCpuFreq = 0; int freqResolved = 0; for (int i = 0; i < cpuCount; i++) { try { RandomAccessFile reader = new RandomAccessFile(String.format(Locale.ENGLISH, "/sys/devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq", i), "r"); String line = reader.readLine(); if (line != null) { totalCpuFreq += Utilities.parseInt(line) / 1000; freqResolved++; } reader.close(); } catch (Throwable ignore) {} } int maxCpuFreq = freqResolved == 0 ? -1 : (int) Math.ceil(totalCpuFreq / (float) freqResolved); long ram = -1; try { ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo(); ((ActivityManager) ApplicationLoader.applicationContext.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryInfo(memoryInfo); ram = memoryInfo.totalMem; } catch (Exception ignore) {} int performanceClass; if ( androidVersion < 21 || cpuCount <= 2 || memoryClass <= 100 || cpuCount <= 4 && maxCpuFreq != -1 && maxCpuFreq <= 1250 || cpuCount <= 4 && maxCpuFreq <= 1600 && memoryClass <= 128 && androidVersion <= 21 || cpuCount <= 4 && maxCpuFreq <= 1300 && memoryClass <= 128 && androidVersion <= 24 || ram != -1 && ram < 2L * 1024L * 1024L * 1024L ) { performanceClass = PERFORMANCE_CLASS_LOW; } else if ( cpuCount < 8 || memoryClass <= 160 || maxCpuFreq != -1 && maxCpuFreq <= 2055 || maxCpuFreq == -1 && cpuCount == 8 && androidVersion <= 23 ) { performanceClass = PERFORMANCE_CLASS_AVERAGE; } else { performanceClass = PERFORMANCE_CLASS_HIGH; } if (BuildVars.LOGS_ENABLED) { FileLog.d("device performance info selected_class = " + performanceClass + " (cpu_count = " + cpuCount + ", freq = " + maxCpuFreq + ", memoryClass = " + memoryClass + ", android version " + androidVersion + ", manufacture " + Build.MANUFACTURER + ", screenRefreshRate=" + AndroidUtilities.screenRefreshRate + ")"); } return performanceClass; } public static String performanceClassName(int perfClass) { switch (perfClass) { case PERFORMANCE_CLASS_HIGH: return "HIGH"; case PERFORMANCE_CLASS_AVERAGE: return "AVERAGE"; case PERFORMANCE_CLASS_LOW: return "LOW"; default: return "UNKNOWN"; } } public static void setMediaColumnsCount(int count) { if (mediaColumnsCount != count) { mediaColumnsCount = count; ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).edit().putInt("mediaColumnsCount", mediaColumnsCount).apply(); } } public static void setStoriesColumnsCount(int count) { if (storiesColumnsCount != count) { storiesColumnsCount = count; ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).edit().putInt("storiesColumnsCount", storiesColumnsCount).apply(); } } public static void setFastScrollHintCount(int count) { if (fastScrollHintCount != count) { fastScrollHintCount = count; ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).edit().putInt("fastScrollHintCount", fastScrollHintCount).apply(); } } public static void setDontAskManageStorage(boolean b) { dontAskManageStorage = b; ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).edit().putBoolean("dontAskManageStorage", dontAskManageStorage).apply(); } public static boolean canBlurChat() { return getDevicePerformanceClass() == PERFORMANCE_CLASS_HIGH; } public static boolean chatBlurEnabled() { return canBlurChat() && LiteMode.isEnabled(LiteMode.FLAG_CHAT_BLUR); } public static class BackgroundActivityPrefs { private static SharedPreferences prefs; public static long getLastCheckedBackgroundActivity() { return prefs.getLong("last_checked", 0); } public static void setLastCheckedBackgroundActivity(long l) { prefs.edit().putLong("last_checked", l).apply(); } public static int getDismissedCount() { return prefs.getInt("dismissed_count", 0); } public static void increaseDismissedCount() { prefs.edit().putInt("dismissed_count", getDismissedCount() + 1).apply(); } } private static Boolean animationsEnabled; public static void setAnimationsEnabled(boolean b) { animationsEnabled = b; } public static boolean animationsEnabled() { if (animationsEnabled == null) { animationsEnabled = MessagesController.getGlobalMainSettings().getBoolean("view_animations", true); } return animationsEnabled; } public static SharedPreferences getPreferences() { return ApplicationLoader.applicationContext.getSharedPreferences("userconfing", Context.MODE_PRIVATE); } public static boolean deviceIsLow() { return getDevicePerformanceClass() == PERFORMANCE_CLASS_LOW; } public static boolean deviceIsAboveAverage() { return getDevicePerformanceClass() >= PERFORMANCE_CLASS_AVERAGE; } public static boolean deviceIsHigh() { return getDevicePerformanceClass() >= PERFORMANCE_CLASS_HIGH; } public static boolean deviceIsAverage() { return getDevicePerformanceClass() <= PERFORMANCE_CLASS_AVERAGE; } public static void toggleRoundCamera() { bigCameraForRound = !bigCameraForRound; ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE) .edit() .putBoolean("bigCameraForRound", bigCameraForRound) .apply(); } @Deprecated public static int getLegacyDevicePerformanceClass() { if (legacyDevicePerformanceClass == -1) { int androidVersion = Build.VERSION.SDK_INT; int cpuCount = ConnectionsManager.CPU_COUNT; int memoryClass = ((ActivityManager) ApplicationLoader.applicationContext.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass(); int totalCpuFreq = 0; int freqResolved = 0; for (int i = 0; i < cpuCount; i++) { try { RandomAccessFile reader = new RandomAccessFile(String.format(Locale.ENGLISH, "/sys/devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq", i), "r"); String line = reader.readLine(); if (line != null) { totalCpuFreq += Utilities.parseInt(line) / 1000; freqResolved++; } reader.close(); } catch (Throwable ignore) {} } int maxCpuFreq = freqResolved == 0 ? -1 : (int) Math.ceil(totalCpuFreq / (float) freqResolved); if (androidVersion < 21 || cpuCount <= 2 || memoryClass <= 100 || cpuCount <= 4 && maxCpuFreq != -1 && maxCpuFreq <= 1250 || cpuCount <= 4 && maxCpuFreq <= 1600 && memoryClass <= 128 && androidVersion <= 21 || cpuCount <= 4 && maxCpuFreq <= 1300 && memoryClass <= 128 && androidVersion <= 24) { legacyDevicePerformanceClass = PERFORMANCE_CLASS_LOW; } else if (cpuCount < 8 || memoryClass <= 160 || maxCpuFreq != -1 && maxCpuFreq <= 2050 || maxCpuFreq == -1 && cpuCount == 8 && androidVersion <= 23) { legacyDevicePerformanceClass = PERFORMANCE_CLASS_AVERAGE; } else { legacyDevicePerformanceClass = PERFORMANCE_CLASS_HIGH; } } return legacyDevicePerformanceClass; } //DEBUG public static boolean drawActionBarShadow = true; private static void loadDebugConfig(SharedPreferences preferences) { drawActionBarShadow = preferences.getBoolean("drawActionBarShadow", true); } public static void saveDebugConfig() { SharedPreferences pref = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); pref.edit().putBoolean("drawActionBarShadow", drawActionBarShadow); } }
cloudveiltech/CloudVeilMessenger
TMessagesProj/src/main/java/org/telegram/messenger/SharedConfig.java
41,709
package org.telegram.ui.Components; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.RectF; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.SystemClock; import android.text.Layout; import android.text.Selection; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.StaticLayout; import android.text.TextPaint; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.text.style.CharacterStyle; import android.util.TypedValue; import android.view.Gravity; import android.view.HapticFeedbackConstants; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.DecelerateInterpolator; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.DrawableRes; import androidx.annotation.Keep; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ChatObject; import org.telegram.messenger.ContactsController; import org.telegram.messenger.DialogObject; import org.telegram.messenger.Emoji; import org.telegram.messenger.FileLog; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MediaController; import org.telegram.messenger.MessagesController; import org.telegram.messenger.R; import org.telegram.messenger.UserConfig; import org.telegram.messenger.UserObject; import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.Components.Premium.boosts.BoostRepository; import org.telegram.ui.PaymentFormActivity; import java.util.ArrayList; @SuppressWarnings("FieldCanBeLocal") @Deprecated // use Bulletin instead public class UndoView extends FrameLayout { private TextView infoTextView; private TextView subinfoTextView; private TextView undoTextView; private ImageView undoImageView; private RLottieImageView leftImageView; private BackupImageView avatarImageView; private LinearLayout undoButton; private int undoViewHeight; private BaseFragment parentFragment; private Object currentInfoObject; private Object currentInfoObject2; private int currentAccount = UserConfig.selectedAccount; private TextPaint textPaint; private Paint progressPaint; private RectF rect; private long timeLeft; private int prevSeconds; private String timeLeftString; private int textWidth; private int currentAction = -1; private ArrayList<Long> currentDialogIds; private Runnable currentActionRunnable; private Runnable currentCancelRunnable; private long lastUpdateTime; private float additionalTranslationY; private boolean isShown; private boolean fromTop; public final static int ACTION_CLEAR = 0; public final static int ACTION_DELETE = 1; public final static int ACTION_ARCHIVE = 2; public final static int ACTION_ARCHIVE_HINT = 3; public final static int ACTION_ARCHIVE_FEW = 4; public final static int ACTION_ARCHIVE_FEW_HINT = 5; public final static int ACTION_ARCHIVE_HIDDEN = 6; public final static int ACTION_ARCHIVE_PINNED = 7; public final static int ACTION_CONTACT_ADDED = 8; public final static int ACTION_OWNER_TRANSFERED_CHANNEL = 9; public final static int ACTION_OWNER_TRANSFERED_GROUP = 10; public final static int ACTION_QR_SESSION_ACCEPTED = 11; public final static int ACTION_THEME_CHANGED = 12; public final static int ACTION_QUIZ_CORRECT = 13; public final static int ACTION_QUIZ_INCORRECT = 14; public final static int ACTION_FILTERS_AVAILABLE = 15; public final static int ACTION_DICE_INFO = 16; public final static int ACTION_DICE_NO_SEND_INFO = 17; public final static int ACTION_TEXT_INFO = 18; public final static int ACTION_CACHE_WAS_CLEARED = 19; public final static int ACTION_ADDED_TO_FOLDER = 20; public final static int ACTION_REMOVED_FROM_FOLDER = 21; public final static int ACTION_PROFILE_PHOTO_CHANGED = 22; public final static int ACTION_CHAT_UNARCHIVED = 23; public final static int ACTION_PROXIMITY_SET = 24; public final static int ACTION_PROXIMITY_REMOVED = 25; public final static int ACTION_CLEAR_FEW = 26; public final static int ACTION_DELETE_FEW = 27; public final static int ACTION_VOIP_MUTED = 30; public final static int ACTION_VOIP_UNMUTED = 31; public final static int ACTION_VOIP_REMOVED = 32; public final static int ACTION_VOIP_LINK_COPIED = 33; public final static int ACTION_VOIP_INVITED = 34; public final static int ACTION_VOIP_MUTED_FOR_YOU = 35; public final static int ACTION_VOIP_UNMUTED_FOR_YOU = 36; public final static int ACTION_VOIP_USER_CHANGED = 37; public final static int ACTION_VOIP_CAN_NOW_SPEAK = 38; public final static int ACTION_VOIP_RECORDING_STARTED = 39; public final static int ACTION_VOIP_RECORDING_FINISHED = 40; public final static int ACTION_VOIP_INVITE_LINK_SENT = 41; public final static int ACTION_VOIP_SOUND_MUTED = 42; public final static int ACTION_VOIP_SOUND_UNMUTED = 43; public final static int ACTION_VOIP_USER_JOINED = 44; public final static int ACTION_VOIP_VIDEO_RECORDING_STARTED = 100; public final static int ACTION_VOIP_VIDEO_RECORDING_FINISHED = 101; public final static int ACTION_IMPORT_NOT_MUTUAL = 45; public final static int ACTION_IMPORT_GROUP_NOT_ADMIN = 46; public final static int ACTION_IMPORT_INFO = 47; public final static int ACTION_MESSAGE_COPIED = 52; public final static int ACTION_FWD_MESSAGES = 53; public final static int ACTION_NOTIFY_ON = 54; public final static int ACTION_NOTIFY_OFF = 55; public final static int ACTION_USERNAME_COPIED = 56; public final static int ACTION_HASHTAG_COPIED = 57; public final static int ACTION_TEXT_COPIED = 58; public final static int ACTION_LINK_COPIED = 59; public final static int ACTION_PHONE_COPIED = 60; public final static int ACTION_SHARE_BACKGROUND = 61; public final static int ACTION_AUTO_DELETE_ON = 70; public final static int ACTION_AUTO_DELETE_OFF = 71; public final static int ACTION_REPORT_SENT = 74; public final static int ACTION_GIGAGROUP_CANCEL = 75; public final static int ACTION_GIGAGROUP_SUCCESS = 76; public final static int ACTION_PAYMENT_SUCCESS = 77; public final static int ACTION_PIN_DIALOGS = 78; public final static int ACTION_UNPIN_DIALOGS = 79; public final static int ACTION_EMAIL_COPIED = 80; public final static int ACTION_CLEAR_DATES = 81; public final static int ACTION_PREVIEW_MEDIA_DESELECTED = 82; public static int ACTION_RINGTONE_ADDED = 83; public final static int ACTION_PREMIUM_TRANSCRIPTION = 84; public final static int ACTION_HINT_SWIPE_TO_REPLY = 85; public final static int ACTION_PREMIUM_ALL_FOLDER = 86; public final static int ACTION_PROXY_ADDED = 87; public final static int ACTION_SHARED_FOLDER_DELETED = 88; public final static int ACTION_BOOSTING_SELECTOR_WARNING_CHANNEL = 90; public final static int ACTION_BOOSTING_SELECTOR_WARNING_USERS = 91; public final static int ACTION_BOOSTING_SELECTOR_WARNING_COUNTRY = 92; public final static int ACTION_BOOSTING_AWAIT = 93; public final static int ACTION_BOOSTING_ONLY_RECIPIENT_CODE = 94; private CharSequence infoText; private int hideAnimationType = 1; Drawable backgroundDrawable; private final Theme.ResourcesProvider resourcesProvider; public class LinkMovementMethodMy extends LinkMovementMethod { @Override public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { try { boolean result; if (event.getAction() == MotionEvent.ACTION_DOWN) { CharacterStyle[] links = buffer.getSpans(widget.getSelectionStart(), widget.getSelectionEnd(), CharacterStyle.class); if (links == null || links.length == 0) { return false; } } if (event.getAction() == MotionEvent.ACTION_UP) { CharacterStyle[] links = buffer.getSpans(widget.getSelectionStart(), widget.getSelectionEnd(), CharacterStyle.class); if (links != null && links.length > 0) { didPressUrl(links[0]); } Selection.removeSelection(buffer); result = true; } else { result = super.onTouchEvent(widget, buffer, event); } return result; } catch (Exception e) { FileLog.e(e); } return false; } } public UndoView(Context context) { this(context, null, false, null); } public UndoView(Context context, BaseFragment parent) { this(context, parent, false, null); } public UndoView(Context context, BaseFragment parent, boolean top, Theme.ResourcesProvider resourcesProvider) { super(context); this.resourcesProvider = resourcesProvider; parentFragment = parent; fromTop = top; infoTextView = new TextView(context); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); infoTextView.setTextColor(getThemedColor(Theme.key_undo_infoColor)); infoTextView.setLinkTextColor(getThemedColor(Theme.key_undo_cancelColor)); infoTextView.setMovementMethod(new LinkMovementMethodMy()); addView(infoTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 45, 13, 0, 0)); subinfoTextView = new TextView(context); subinfoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13); subinfoTextView.setTextColor(getThemedColor(Theme.key_undo_infoColor)); subinfoTextView.setLinkTextColor(getThemedColor(Theme.key_undo_cancelColor)); subinfoTextView.setHighlightColor(0); subinfoTextView.setSingleLine(true); subinfoTextView.setEllipsize(TextUtils.TruncateAt.END); subinfoTextView.setMovementMethod(new AndroidUtilities.LinkMovementMethodMy()); addView(subinfoTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 58, 27, 8, 0)); leftImageView = new RLottieImageView(context); leftImageView.setScaleType(ImageView.ScaleType.CENTER); leftImageView.setLayerColor("info1.**", getThemedColor(Theme.key_undo_background) | 0xff000000); leftImageView.setLayerColor("info2.**", getThemedColor(Theme.key_undo_background) | 0xff000000); leftImageView.setLayerColor("luc12.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("luc11.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("luc10.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("luc9.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("luc8.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("luc7.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("luc6.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("luc5.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("luc4.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("luc3.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("luc2.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("luc1.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("Oval.**", getThemedColor(Theme.key_undo_infoColor)); addView(leftImageView, LayoutHelper.createFrame(54, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.LEFT, 3, 0, 0, 0)); avatarImageView = new BackupImageView(context); avatarImageView.setRoundRadius(AndroidUtilities.dp(15)); addView(avatarImageView, LayoutHelper.createFrame(30, 30, Gravity.CENTER_VERTICAL | Gravity.LEFT, 15, 0, 0, 0)); undoButton = new LinearLayout(context); undoButton.setOrientation(LinearLayout.HORIZONTAL); undoButton.setBackground(Theme.createRadSelectorDrawable(getThemedColor(Theme.key_undo_cancelColor) & 0x22ffffff, AndroidUtilities.dp(2), AndroidUtilities.dp(2))); addView(undoButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.RIGHT, 0, 0, 11, 0)); undoButton.setOnClickListener(v -> { if (!canUndo()) { return; } hide(false, 1); }); undoImageView = new ImageView(context); undoImageView.setImageResource(R.drawable.chats_undo); undoImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_undo_cancelColor), PorterDuff.Mode.MULTIPLY)); undoButton.addView(undoImageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.LEFT, 4, 4, 0, 4)); undoTextView = new TextView(context); undoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); undoTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); undoTextView.setTextColor(getThemedColor(Theme.key_undo_cancelColor)); undoTextView.setText(LocaleController.getString("Undo", R.string.Undo)); undoButton.addView(undoTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.LEFT, 6, 4, 8, 4)); rect = new RectF(AndroidUtilities.dp(15), AndroidUtilities.dp(15), AndroidUtilities.dp(15 + 18), AndroidUtilities.dp(15 + 18)); progressPaint = new Paint(Paint.ANTI_ALIAS_FLAG); progressPaint.setStyle(Paint.Style.STROKE); progressPaint.setStrokeWidth(AndroidUtilities.dp(2)); progressPaint.setStrokeCap(Paint.Cap.ROUND); progressPaint.setColor(getThemedColor(Theme.key_undo_infoColor)); textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); textPaint.setTextSize(AndroidUtilities.dp(12)); textPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textPaint.setColor(getThemedColor(Theme.key_undo_infoColor)); setWillNotDraw(false); backgroundDrawable = Theme.createRoundRectDrawable(AndroidUtilities.dp(10), getThemedColor(Theme.key_undo_background)); setOnTouchListener((v, event) -> true); setVisibility(INVISIBLE); } public void setColors(int background, int text) { Theme.setDrawableColor(backgroundDrawable, background); infoTextView.setTextColor(text); subinfoTextView.setTextColor(text); leftImageView.setLayerColor("info1.**", background | 0xff000000); leftImageView.setLayerColor("info2.**", background | 0xff000000); } private boolean isTooltipAction() { return currentAction == ACTION_ARCHIVE_HIDDEN || currentAction == ACTION_ARCHIVE_HINT || currentAction == ACTION_ARCHIVE_FEW_HINT || currentAction == ACTION_ARCHIVE_PINNED || currentAction == ACTION_CONTACT_ADDED || currentAction == ACTION_PROXY_ADDED || currentAction == ACTION_OWNER_TRANSFERED_CHANNEL || currentAction == ACTION_OWNER_TRANSFERED_GROUP || currentAction == ACTION_QUIZ_CORRECT || currentAction == ACTION_QUIZ_INCORRECT || currentAction == ACTION_CACHE_WAS_CLEARED || currentAction == ACTION_ADDED_TO_FOLDER || currentAction == ACTION_REMOVED_FROM_FOLDER || currentAction == ACTION_PROFILE_PHOTO_CHANGED || currentAction == ACTION_CHAT_UNARCHIVED || currentAction == ACTION_VOIP_MUTED || currentAction == ACTION_VOIP_UNMUTED || currentAction == ACTION_VOIP_REMOVED || currentAction == ACTION_VOIP_LINK_COPIED || currentAction == ACTION_VOIP_INVITED || currentAction == ACTION_VOIP_MUTED_FOR_YOU || currentAction == ACTION_VOIP_UNMUTED_FOR_YOU || currentAction == ACTION_REPORT_SENT || currentAction == ACTION_VOIP_USER_CHANGED || currentAction == ACTION_VOIP_CAN_NOW_SPEAK || currentAction == ACTION_VOIP_RECORDING_STARTED || currentAction == ACTION_VOIP_RECORDING_FINISHED || currentAction == ACTION_VOIP_SOUND_MUTED || currentAction == ACTION_VOIP_SOUND_UNMUTED || currentAction == ACTION_PAYMENT_SUCCESS || currentAction == ACTION_VOIP_USER_JOINED || currentAction == ACTION_PIN_DIALOGS || currentAction == ACTION_UNPIN_DIALOGS || currentAction == ACTION_VOIP_VIDEO_RECORDING_STARTED || currentAction == ACTION_VOIP_VIDEO_RECORDING_FINISHED || currentAction == ACTION_RINGTONE_ADDED; } private boolean hasSubInfo() { return currentAction == ACTION_QR_SESSION_ACCEPTED || currentAction == ACTION_PROXIMITY_SET || currentAction == ACTION_ARCHIVE_HIDDEN || currentAction == ACTION_ARCHIVE_HINT || currentAction == ACTION_ARCHIVE_FEW_HINT || currentAction == ACTION_QUIZ_CORRECT || currentAction == ACTION_QUIZ_INCORRECT || currentAction == ACTION_REPORT_SENT || currentAction == ACTION_ARCHIVE_PINNED && MessagesController.getInstance(currentAccount).dialogFilters.isEmpty() || currentAction == ACTION_RINGTONE_ADDED || currentAction == ACTION_HINT_SWIPE_TO_REPLY || currentAction == ACTION_SHARED_FOLDER_DELETED && currentInfoObject2 != null && ((Integer) currentInfoObject2) > 0; } public boolean isMultilineSubInfo() { return currentAction == ACTION_THEME_CHANGED || currentAction == ACTION_FILTERS_AVAILABLE || currentAction == ACTION_PROXIMITY_SET || currentAction == ACTION_REPORT_SENT || currentAction == ACTION_RINGTONE_ADDED; } public void setAdditionalTranslationY(float value) { if (additionalTranslationY != value) { additionalTranslationY = value; updatePosition(); } } public Object getCurrentInfoObject() { return currentInfoObject; } public void hide(boolean apply, int animated) { if (getVisibility() != VISIBLE || !isShown) { return; } currentInfoObject = null; currentInfoObject2 = null; isShown = false; if (currentActionRunnable != null) { if (apply) { currentActionRunnable.run(); } currentActionRunnable = null; } if (currentCancelRunnable != null) { if (!apply) { currentCancelRunnable.run(); } currentCancelRunnable = null; } if (currentAction == ACTION_CLEAR || currentAction == ACTION_DELETE || currentAction == ACTION_CLEAR_FEW || currentAction == ACTION_DELETE_FEW) { for (int a = 0; a < currentDialogIds.size(); a++) { long did = currentDialogIds.get(a); MessagesController.getInstance(currentAccount).removeDialogAction(did, currentAction == ACTION_CLEAR || currentAction == ACTION_CLEAR_FEW, apply); onRemoveDialogAction(did, currentAction); } } if (animated != 0) { AnimatorSet animatorSet = new AnimatorSet(); if (animated == 1) { animatorSet.playTogether(ObjectAnimator.ofFloat(this, "enterOffset", (fromTop ? -1.0f : 1.0f) * (enterOffsetMargin + undoViewHeight))); animatorSet.setDuration(250); } else { animatorSet.playTogether( ObjectAnimator.ofFloat(this, View.SCALE_X, 0.8f), ObjectAnimator.ofFloat(this, View.SCALE_Y, 0.8f), ObjectAnimator.ofFloat(this, View.ALPHA, 0.0f)); animatorSet.setDuration(180); } animatorSet.setInterpolator(new DecelerateInterpolator()); animatorSet.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { setVisibility(INVISIBLE); setScaleX(1.0f); setScaleY(1.0f); setAlpha(1.0f); } }); animatorSet.start(); } else { setEnterOffset((fromTop ? -1.0f : 1.0f) * (enterOffsetMargin + undoViewHeight)); setVisibility(INVISIBLE); } } protected void onRemoveDialogAction(long currentDialogId, int action) { } public void didPressUrl(CharacterStyle span) { } public void showWithAction(long did, int action, Runnable actionRunnable) { showWithAction(did, action, null, null, actionRunnable, null); } public void showWithAction(long did, int action, Object infoObject) { showWithAction(did, action, infoObject, null, null, null); } public void showWithAction(long did, int action, Runnable actionRunnable, Runnable cancelRunnable) { showWithAction(did, action, null, null, actionRunnable, cancelRunnable); } public void showWithAction(long did, int action, Object infoObject, Runnable actionRunnable, Runnable cancelRunnable) { showWithAction(did, action, infoObject, null, actionRunnable, cancelRunnable); } public void showWithAction(long did, int action, Object infoObject, Object infoObject2, Runnable actionRunnable, Runnable cancelRunnable) { ArrayList<Long> ids = new ArrayList<>(); ids.add(did); showWithAction(ids, action, infoObject, infoObject2, actionRunnable, cancelRunnable); } public void showWithAction(ArrayList<Long> dialogIds, int action, Object infoObject, Object infoObject2, Runnable actionRunnable, Runnable cancelRunnable) { if (!AndroidUtilities.shouldShowClipboardToast() && (currentAction == ACTION_MESSAGE_COPIED || currentAction == ACTION_USERNAME_COPIED || currentAction == ACTION_HASHTAG_COPIED || currentAction == ACTION_TEXT_COPIED || currentAction == ACTION_LINK_COPIED || currentAction == ACTION_PHONE_COPIED || currentAction == ACTION_EMAIL_COPIED || currentAction == ACTION_VOIP_LINK_COPIED)) { return; } if (currentActionRunnable != null) { currentActionRunnable.run(); } isShown = true; currentActionRunnable = actionRunnable; currentCancelRunnable = cancelRunnable; currentDialogIds = dialogIds; long did = dialogIds.get(0); currentAction = action; timeLeft = 5000; currentInfoObject = infoObject; currentInfoObject2 = infoObject2; lastUpdateTime = SystemClock.elapsedRealtime(); undoTextView.setText(LocaleController.getString("Undo", R.string.Undo)); undoImageView.setVisibility(VISIBLE); leftImageView.setPadding(0, 0, 0, 0); leftImageView.setScaleX(1); leftImageView.setScaleY(1); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); avatarImageView.setVisibility(GONE); infoTextView.setGravity(Gravity.LEFT | Gravity.TOP); FrameLayout.LayoutParams layoutParams; layoutParams = (FrameLayout.LayoutParams) subinfoTextView.getLayoutParams(); layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams = (FrameLayout.LayoutParams) infoTextView.getLayoutParams(); layoutParams.height = LayoutHelper.WRAP_CONTENT; layoutParams.topMargin = AndroidUtilities.dp(13); layoutParams.bottomMargin = 0; leftImageView.setScaleType(ImageView.ScaleType.CENTER); FrameLayout.LayoutParams layoutParams2 = (FrameLayout.LayoutParams) leftImageView.getLayoutParams(); layoutParams2.gravity = Gravity.CENTER_VERTICAL | Gravity.LEFT; layoutParams2.topMargin = layoutParams2.bottomMargin = 0; layoutParams2.leftMargin = AndroidUtilities.dp(3); layoutParams2.width = AndroidUtilities.dp(54); layoutParams2.height = LayoutHelper.WRAP_CONTENT; infoTextView.setMinHeight(0); boolean infoOnly = false; boolean reversedPlay = false; int reversedPlayEndFrame = 0; if ((actionRunnable == null && cancelRunnable == null) || action == ACTION_RINGTONE_ADDED) { setOnClickListener(view -> hide(false, 1)); setOnTouchListener(null); } else { setOnClickListener(null); setOnTouchListener((v, event) -> true); } infoTextView.setMovementMethod(null); if (isTooltipAction()) { CharSequence infoText; CharSequence subInfoText; @DrawableRes int icon; int size = 36; boolean iconIsDrawable = false; if (action == ACTION_RINGTONE_ADDED) { subinfoTextView.setSingleLine(false); infoText = LocaleController.getString("SoundAdded", R.string.SoundAdded); subInfoText = AndroidUtilities.replaceSingleTag(LocaleController.getString("SoundAddedSubtitle", R.string.SoundAddedSubtitle), actionRunnable); currentActionRunnable = null; icon = R.raw.sound_download; timeLeft = 4000; } else if (action == ACTION_REPORT_SENT) { subinfoTextView.setSingleLine(false); infoText = LocaleController.getString("ReportChatSent", R.string.ReportChatSent); subInfoText = LocaleController.formatString("ReportSentInfo", R.string.ReportSentInfo); icon = R.raw.ic_admin; timeLeft = 4000; } else if (action == ACTION_VOIP_INVITED) { TLRPC.User user = (TLRPC.User) infoObject; TLRPC.Chat chat = (TLRPC.Chat) infoObject2; if (ChatObject.isChannelOrGiga(chat)) { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipChannelInvitedUser", R.string.VoipChannelInvitedUser, UserObject.getFirstName(user))); } else { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipGroupInvitedUser", R.string.VoipGroupInvitedUser, UserObject.getFirstName(user))); } subInfoText = null; icon = 0; AvatarDrawable avatarDrawable = new AvatarDrawable(); avatarDrawable.setTextSize(AndroidUtilities.dp(12)); avatarDrawable.setInfo(user); avatarImageView.setForUserOrChat(user, avatarDrawable); avatarImageView.setVisibility(VISIBLE); timeLeft = 3000; } else if (action == ACTION_VOIP_USER_JOINED) { TLRPC.Chat currentChat = (TLRPC.Chat) infoObject2; if (infoObject instanceof TLRPC.User) { TLRPC.User user = (TLRPC.User) infoObject; if (ChatObject.isChannelOrGiga(currentChat)) { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipChannelUserJoined", R.string.VoipChannelUserJoined, UserObject.getFirstName(user))); } else { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipChatUserJoined", R.string.VoipChatUserJoined, UserObject.getFirstName(user))); } } else { TLRPC.Chat chat = (TLRPC.Chat) infoObject; if (ChatObject.isChannelOrGiga(currentChat)) { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipChannelChatJoined", R.string.VoipChannelChatJoined, chat.title)); } else { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipChatChatJoined", R.string.VoipChatChatJoined, chat.title)); } } subInfoText = null; icon = 0; AvatarDrawable avatarDrawable = new AvatarDrawable(); avatarDrawable.setTextSize(AndroidUtilities.dp(12)); avatarDrawable.setInfo((TLObject) infoObject); avatarImageView.setForUserOrChat((TLObject) infoObject, avatarDrawable); avatarImageView.setVisibility(VISIBLE); timeLeft = 3000; } else if (action == ACTION_VOIP_USER_CHANGED) { AvatarDrawable avatarDrawable = new AvatarDrawable(); avatarDrawable.setTextSize(AndroidUtilities.dp(12)); String name; if (infoObject instanceof TLRPC.User) { TLRPC.User user = (TLRPC.User) infoObject; avatarDrawable.setInfo(user); avatarImageView.setForUserOrChat(user, avatarDrawable); name = ContactsController.formatName(user.first_name, user.last_name); } else { TLRPC.Chat chat = (TLRPC.Chat) infoObject; avatarDrawable.setInfo(chat); avatarImageView.setForUserOrChat(chat, avatarDrawable); name = chat.title; } TLRPC.Chat currentChat = (TLRPC.Chat) infoObject2; if (ChatObject.isChannelOrGiga(currentChat)) { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipChannelUserChanged", R.string.VoipChannelUserChanged, name)); } else { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipGroupUserChanged", R.string.VoipGroupUserChanged, name)); } subInfoText = null; icon = 0; avatarImageView.setVisibility(VISIBLE); timeLeft = 3000; } else if (action == ACTION_VOIP_LINK_COPIED) { infoText = LocaleController.getString("VoipGroupCopyInviteLinkCopied", R.string.VoipGroupCopyInviteLinkCopied); subInfoText = null; icon = R.raw.voip_invite; timeLeft = 3000; } else if (action == ACTION_PAYMENT_SUCCESS) { infoText = (CharSequence) infoObject; subInfoText = null; icon = R.raw.payment_success; timeLeft = 5000; if (parentFragment != null && infoObject2 instanceof TLRPC.Message) { TLRPC.Message message = (TLRPC.Message) infoObject2; setOnTouchListener(null); infoTextView.setMovementMethod(null); setOnClickListener(v -> { hide(true, 1); TLRPC.TL_payments_getPaymentReceipt req = new TLRPC.TL_payments_getPaymentReceipt(); req.msg_id = message.id; req.peer = parentFragment.getMessagesController().getInputPeer(message.peer_id); parentFragment.getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { if (response instanceof TLRPC.TL_payments_paymentReceipt) { parentFragment.presentFragment(new PaymentFormActivity((TLRPC.TL_payments_paymentReceipt) response)); } }), ConnectionsManager.RequestFlagFailOnServerErrors); }); } } else if (action == ACTION_VOIP_MUTED) { String name; if (infoObject instanceof TLRPC.User) { TLRPC.User user = (TLRPC.User) infoObject; name = UserObject.getFirstName(user); } else { TLRPC.Chat chat = (TLRPC.Chat) infoObject; name = chat.title; } infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipGroupUserCantNowSpeak", R.string.VoipGroupUserCantNowSpeak, name)); subInfoText = null; icon = R.raw.voip_muted; timeLeft = 3000; } else if (action == ACTION_VOIP_MUTED_FOR_YOU) { String name; if (infoObject instanceof TLRPC.User) { TLRPC.User user = (TLRPC.User) infoObject; name = UserObject.getFirstName(user); } else if (infoObject instanceof TLRPC.Chat) { TLRPC.Chat chat = (TLRPC.Chat) infoObject; name = chat.title; } else { name = ""; } infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipGroupUserCantNowSpeakForYou", R.string.VoipGroupUserCantNowSpeakForYou, name)); subInfoText = null; icon = R.raw.voip_muted; timeLeft = 3000; } else if (action == ACTION_VOIP_UNMUTED) { String name; if (infoObject instanceof TLRPC.User) { TLRPC.User user = (TLRPC.User) infoObject; name = UserObject.getFirstName(user); } else { TLRPC.Chat chat = (TLRPC.Chat) infoObject; name = chat.title; } infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipGroupUserCanNowSpeak", R.string.VoipGroupUserCanNowSpeak, name)); subInfoText = null; icon = R.raw.voip_unmuted; timeLeft = 3000; } else if (action == ACTION_VOIP_CAN_NOW_SPEAK) { if (infoObject instanceof TLRPC.Chat) { TLRPC.Chat chat = (TLRPC.Chat) infoObject; infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipGroupYouCanNowSpeakIn", R.string.VoipGroupYouCanNowSpeakIn, chat.title)); } else { infoText = AndroidUtilities.replaceTags(LocaleController.getString("VoipGroupYouCanNowSpeak", R.string.VoipGroupYouCanNowSpeak)); } subInfoText = null; icon = R.raw.voip_allow_talk; timeLeft = 3000; } else if (action == ACTION_VOIP_SOUND_MUTED) { TLRPC.Chat chat = (TLRPC.Chat) infoObject; if (ChatObject.isChannelOrGiga(chat)) { infoText = AndroidUtilities.replaceTags(LocaleController.getString("VoipChannelSoundMuted", R.string.VoipChannelSoundMuted)); } else { infoText = AndroidUtilities.replaceTags(LocaleController.getString("VoipGroupSoundMuted", R.string.VoipGroupSoundMuted)); } subInfoText = null; icon = R.raw.ic_mute; timeLeft = 3000; } else if (action == ACTION_VOIP_SOUND_UNMUTED) { TLRPC.Chat chat = (TLRPC.Chat) infoObject; if (ChatObject.isChannelOrGiga(chat)) { infoText = AndroidUtilities.replaceTags(LocaleController.getString("VoipChannelSoundUnmuted", R.string.VoipChannelSoundUnmuted)); } else { infoText = AndroidUtilities.replaceTags(LocaleController.getString("VoipGroupSoundUnmuted", R.string.VoipGroupSoundUnmuted)); } subInfoText = null; icon = R.raw.ic_unmute; timeLeft = 3000; } else if (currentAction == ACTION_VOIP_RECORDING_STARTED || currentAction == ACTION_VOIP_VIDEO_RECORDING_STARTED) { infoText = AndroidUtilities.replaceTags(currentAction == ACTION_VOIP_RECORDING_STARTED ? LocaleController.getString("VoipGroupAudioRecordStarted", R.string.VoipGroupAudioRecordStarted) : LocaleController.getString("VoipGroupVideoRecordStarted", R.string.VoipGroupVideoRecordStarted)); subInfoText = null; icon = R.raw.voip_record_start; timeLeft = 3000; } else if (currentAction == ACTION_VOIP_RECORDING_FINISHED || currentAction == ACTION_VOIP_VIDEO_RECORDING_FINISHED) { String text = currentAction == ACTION_VOIP_RECORDING_FINISHED ? LocaleController.getString("VoipGroupAudioRecordSaved", R.string.VoipGroupAudioRecordSaved) : LocaleController.getString("VoipGroupVideoRecordSaved", R.string.VoipGroupVideoRecordSaved); subInfoText = null; icon = R.raw.voip_record_saved; timeLeft = 4000; infoTextView.setMovementMethod(new AndroidUtilities.LinkMovementMethodMy()); SpannableStringBuilder builder = new SpannableStringBuilder(text); int index1 = text.indexOf("**"); int index2 = text.lastIndexOf("**"); if (index1 >= 0 && index2 >= 0 && index1 != index2) { builder.replace(index2, index2 + 2, ""); builder.replace(index1, index1 + 2, ""); try { builder.setSpan(new URLSpanNoUnderline("tg://openmessage?user_id=" + UserConfig.getInstance(currentAccount).getClientUserId()), index1, index2 - 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } catch (Exception e) { FileLog.e(e); } } infoText = builder; } else if (action == ACTION_VOIP_UNMUTED_FOR_YOU) { String name; if (infoObject instanceof TLRPC.User) { TLRPC.User user = (TLRPC.User) infoObject; name = UserObject.getFirstName(user); } else { TLRPC.Chat chat = (TLRPC.Chat) infoObject; name = chat.title; } infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipGroupUserCanNowSpeakForYou", R.string.VoipGroupUserCanNowSpeakForYou, name)); subInfoText = null; icon = R.raw.voip_unmuted; timeLeft = 3000; } else if (action == ACTION_VOIP_REMOVED) { String name; if (infoObject instanceof TLRPC.User) { TLRPC.User user = (TLRPC.User) infoObject; name = UserObject.getFirstName(user); } else { TLRPC.Chat chat = (TLRPC.Chat) infoObject; name = chat.title; } infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipGroupRemovedFromGroup", R.string.VoipGroupRemovedFromGroup, name)); subInfoText = null; icon = R.raw.voip_group_removed; timeLeft = 3000; } else if (action == ACTION_OWNER_TRANSFERED_CHANNEL || action == ACTION_OWNER_TRANSFERED_GROUP) { TLRPC.User user = (TLRPC.User) infoObject; if (action == ACTION_OWNER_TRANSFERED_CHANNEL) { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("EditAdminTransferChannelToast", R.string.EditAdminTransferChannelToast, UserObject.getFirstName(user))); } else { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("EditAdminTransferGroupToast", R.string.EditAdminTransferGroupToast, UserObject.getFirstName(user))); } subInfoText = null; icon = R.raw.contact_check; } else if (action == ACTION_CONTACT_ADDED) { TLRPC.User user = (TLRPC.User) infoObject; infoText = LocaleController.formatString("NowInContacts", R.string.NowInContacts, UserObject.getFirstName(user)); subInfoText = null; icon = R.raw.contact_check; } else if (action == ACTION_PROXY_ADDED) { infoText = LocaleController.formatString(R.string.ProxyAddedSuccess); subInfoText = null; icon = R.raw.contact_check; } else if (action == ACTION_PROFILE_PHOTO_CHANGED) { if (DialogObject.isUserDialog(did)) { if (infoObject == null) { infoText = LocaleController.getString("MainProfilePhotoSetHint", R.string.MainProfilePhotoSetHint); } else { infoText = LocaleController.getString("MainProfileVideoSetHint", R.string.MainProfileVideoSetHint); } } else { TLRPC.Chat chat = MessagesController.getInstance(UserConfig.selectedAccount).getChat(-did); if (ChatObject.isChannel(chat) && !chat.megagroup) { if (infoObject == null) { infoText = LocaleController.getString("MainChannelProfilePhotoSetHint", R.string.MainChannelProfilePhotoSetHint); } else { infoText = LocaleController.getString("MainChannelProfileVideoSetHint", R.string.MainChannelProfileVideoSetHint); } } else { if (infoObject == null) { infoText = LocaleController.getString("MainGroupProfilePhotoSetHint", R.string.MainGroupProfilePhotoSetHint); } else { infoText = LocaleController.getString("MainGroupProfileVideoSetHint", R.string.MainGroupProfileVideoSetHint); } } } subInfoText = null; icon = R.raw.contact_check; } else if (action == ACTION_CHAT_UNARCHIVED) { infoText = LocaleController.getString("ChatWasMovedToMainList", R.string.ChatWasMovedToMainList); subInfoText = null; icon = R.raw.contact_check; } else if (action == ACTION_ARCHIVE_HIDDEN) { infoText = LocaleController.getString("ArchiveHidden", R.string.ArchiveHidden); subInfoText = LocaleController.getString("ArchiveHiddenInfo", R.string.ArchiveHiddenInfo); icon = R.raw.chats_swipearchive; size = 48; } else if (currentAction == ACTION_QUIZ_CORRECT) { infoText = LocaleController.getString("QuizWellDone", R.string.QuizWellDone); subInfoText = LocaleController.getString("QuizWellDoneInfo", R.string.QuizWellDoneInfo); icon = R.raw.wallet_congrats; size = 44; } else if (currentAction == ACTION_QUIZ_INCORRECT) { infoText = LocaleController.getString("QuizWrongAnswer", R.string.QuizWrongAnswer); subInfoText = LocaleController.getString("QuizWrongAnswerInfo", R.string.QuizWrongAnswerInfo); icon = R.raw.wallet_science; size = 44; } else if (action == ACTION_ARCHIVE_PINNED) { infoText = LocaleController.getString("ArchivePinned", R.string.ArchivePinned); if (MessagesController.getInstance(currentAccount).dialogFilters.isEmpty()) { subInfoText = LocaleController.getString("ArchivePinnedInfo", R.string.ArchivePinnedInfo); } else { subInfoText = null; } icon = R.raw.chats_infotip; } else if (action == ACTION_ADDED_TO_FOLDER || action == ACTION_REMOVED_FROM_FOLDER) { MessagesController.DialogFilter filter = (MessagesController.DialogFilter) infoObject2; if (did != 0) { long dialogId = did; if (DialogObject.isEncryptedDialog(did)) { TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(DialogObject.getEncryptedChatId(dialogId)); dialogId = encryptedChat.user_id; } if (DialogObject.isUserDialog(dialogId)) { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(dialogId); if (action == ACTION_ADDED_TO_FOLDER) { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("FilterUserAddedToExisting", R.string.FilterUserAddedToExisting, UserObject.getFirstName(user), filter.name)); } else { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("FilterUserRemovedFrom", R.string.FilterUserRemovedFrom, UserObject.getFirstName(user), filter.name)); } } else { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); if (action == ACTION_ADDED_TO_FOLDER) { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("FilterChatAddedToExisting", R.string.FilterChatAddedToExisting, chat.title, filter.name)); } else { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("FilterChatRemovedFrom", R.string.FilterChatRemovedFrom, chat.title, filter.name)); } } } else { if (action == ACTION_ADDED_TO_FOLDER) { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("FilterChatsAddedToExisting", R.string.FilterChatsAddedToExisting, LocaleController.formatPluralString("ChatsSelected", (Integer) infoObject), filter.name)); } else { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("FilterChatsRemovedFrom", R.string.FilterChatsRemovedFrom, LocaleController.formatPluralString("ChatsSelected", (Integer) infoObject), filter.name)); } } subInfoText = null; icon = action == ACTION_ADDED_TO_FOLDER ? R.raw.folder_in : R.raw.folder_out; } else if (action == ACTION_CACHE_WAS_CLEARED) { infoText = this.infoText; subInfoText = null; icon = R.raw.ic_delete; } else if (action == ACTION_PREVIEW_MEDIA_DESELECTED) { MediaController.PhotoEntry photo = (MediaController.PhotoEntry) infoObject; infoText = photo.isVideo ? LocaleController.getString("AttachMediaVideoDeselected", R.string.AttachMediaVideoDeselected) : LocaleController.getString("AttachMediaPhotoDeselected", R.string.AttachMediaPhotoDeselected); subInfoText = null; icon = 0; } else if (action == ACTION_PIN_DIALOGS || action == ACTION_UNPIN_DIALOGS) { int count = (Integer) infoObject; if (action == ACTION_PIN_DIALOGS) { infoText = LocaleController.formatPluralString("PinnedDialogsCount", count); } else { infoText = LocaleController.formatPluralString("UnpinnedDialogsCount", count); } subInfoText = null; icon = currentAction == ACTION_PIN_DIALOGS ? R.raw.ic_pin : R.raw.ic_unpin; if (infoObject2 instanceof Integer) { timeLeft = (int) infoObject2; } } else { if (action == ACTION_ARCHIVE_HINT) { infoText = LocaleController.getString("ChatArchived", R.string.ChatArchived); } else { infoText = LocaleController.getString("ChatsArchived", R.string.ChatsArchived); } if (MessagesController.getInstance(currentAccount).dialogFilters.isEmpty()) { subInfoText = LocaleController.getString("ChatArchivedInfo", R.string.ChatArchivedInfo); } else { subInfoText = null; } icon = R.raw.chats_infotip; } infoTextView.setText(infoText); if (icon != 0) { if (iconIsDrawable) { leftImageView.setImageResource(icon); } else { leftImageView.setAnimation(icon, size, size); RLottieDrawable drawable = leftImageView.getAnimatedDrawable(); drawable.setPlayInDirectionOfCustomEndFrame(reversedPlay); drawable.setCustomEndFrame(reversedPlay ? reversedPlayEndFrame : drawable.getFramesCount()); } leftImageView.setVisibility(VISIBLE); if (!iconIsDrawable) { leftImageView.setProgress(reversedPlay ? 1 : 0); leftImageView.playAnimation(); } } else { leftImageView.setVisibility(GONE); } if (subInfoText != null) { layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams.topMargin = AndroidUtilities.dp(6); layoutParams.rightMargin = AndroidUtilities.dp(8); layoutParams = (FrameLayout.LayoutParams) subinfoTextView.getLayoutParams(); layoutParams.rightMargin = AndroidUtilities.dp(8); subinfoTextView.setText(subInfoText); subinfoTextView.setVisibility(VISIBLE); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); infoTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); } else { layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams.topMargin = AndroidUtilities.dp(13); layoutParams.rightMargin = AndroidUtilities.dp(8); subinfoTextView.setVisibility(GONE); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); infoTextView.setTypeface(Typeface.DEFAULT); } undoButton.setVisibility(GONE); } else if (currentAction == ACTION_IMPORT_NOT_MUTUAL || currentAction == ACTION_IMPORT_GROUP_NOT_ADMIN || currentAction == ACTION_IMPORT_INFO || currentAction == ACTION_MESSAGE_COPIED || currentAction == ACTION_FWD_MESSAGES || currentAction == ACTION_NOTIFY_ON || currentAction == ACTION_NOTIFY_OFF || currentAction == ACTION_USERNAME_COPIED || currentAction == ACTION_HASHTAG_COPIED || currentAction == ACTION_TEXT_COPIED || currentAction == ACTION_LINK_COPIED || currentAction == ACTION_PHONE_COPIED || currentAction == ACTION_AUTO_DELETE_OFF || currentAction == ACTION_AUTO_DELETE_ON || currentAction == ACTION_GIGAGROUP_CANCEL || currentAction == ACTION_GIGAGROUP_SUCCESS || currentAction == ACTION_VOIP_INVITE_LINK_SENT || currentAction == ACTION_PIN_DIALOGS || currentAction == ACTION_UNPIN_DIALOGS || currentAction == ACTION_SHARE_BACKGROUND || currentAction == ACTION_EMAIL_COPIED) { undoImageView.setVisibility(GONE); leftImageView.setVisibility(VISIBLE); infoTextView.setTypeface(Typeface.DEFAULT); long hapticDelay = -1; if (currentAction == ACTION_GIGAGROUP_SUCCESS) { infoTextView.setText(LocaleController.getString("BroadcastGroupConvertSuccess", R.string.BroadcastGroupConvertSuccess)); leftImageView.setAnimation(R.raw.gigagroup_convert, 36, 36); infoOnly = true; layoutParams.topMargin = AndroidUtilities.dp(9); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); } else if (currentAction == ACTION_GIGAGROUP_CANCEL) { infoTextView.setText(LocaleController.getString("GigagroupConvertCancelHint", R.string.GigagroupConvertCancelHint)); leftImageView.setAnimation(R.raw.chats_infotip, 36, 36); infoOnly = true; layoutParams.topMargin = AndroidUtilities.dp(9); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); } else if (action == ACTION_AUTO_DELETE_ON) { TLRPC.User user = (TLRPC.User) infoObject; int ttl = (Integer) infoObject2; subinfoTextView.setSingleLine(false); String time = LocaleController.formatTTLString(ttl); infoTextView.setText(LocaleController.formatString("AutoDeleteHintOnText", R.string.AutoDeleteHintOnText, time)); leftImageView.setAnimation(R.raw.fire_on, 36, 36); layoutParams.topMargin = AndroidUtilities.dp(9); timeLeft = 4000; infoOnly = true; leftImageView.setPadding(0, 0, 0, AndroidUtilities.dp(3)); } else if (currentAction == ACTION_AUTO_DELETE_OFF) { infoTextView.setText(LocaleController.getString("AutoDeleteHintOffText", R.string.AutoDeleteHintOffText)); leftImageView.setAnimation(R.raw.fire_off, 36, 36); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); timeLeft = 3000; leftImageView.setPadding(0, 0, 0, AndroidUtilities.dp(4)); } else if (currentAction == ACTION_IMPORT_NOT_MUTUAL) { infoTextView.setText(LocaleController.getString("ImportMutualError", R.string.ImportMutualError)); leftImageView.setAnimation(R.raw.error, 36, 36); infoOnly = true; layoutParams.topMargin = AndroidUtilities.dp(9); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); } else if (currentAction == ACTION_IMPORT_GROUP_NOT_ADMIN) { infoTextView.setText(LocaleController.getString("ImportNotAdmin", R.string.ImportNotAdmin)); leftImageView.setAnimation(R.raw.error, 36, 36); infoOnly = true; layoutParams.topMargin = AndroidUtilities.dp(9); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); } else if (currentAction == ACTION_IMPORT_INFO) { infoTextView.setText(LocaleController.getString("ImportedInfo", R.string.ImportedInfo)); leftImageView.setAnimation(R.raw.imported, 36, 36); leftImageView.setPadding(0, 0, 0, AndroidUtilities.dp(5)); infoOnly = true; layoutParams.topMargin = AndroidUtilities.dp(9); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); } else if (currentAction == ACTION_MESSAGE_COPIED || currentAction == ACTION_USERNAME_COPIED || currentAction == ACTION_HASHTAG_COPIED || currentAction == ACTION_TEXT_COPIED || currentAction == ACTION_LINK_COPIED || currentAction == ACTION_PHONE_COPIED || currentAction == ACTION_EMAIL_COPIED) { if (!AndroidUtilities.shouldShowClipboardToast()) { return; } int iconRawId = R.raw.copy; if (currentAction == ACTION_EMAIL_COPIED) { infoTextView.setText(LocaleController.getString("EmailCopied", R.string.EmailCopied)); } else if (currentAction == ACTION_PHONE_COPIED) { infoTextView.setText(LocaleController.getString("PhoneCopied", R.string.PhoneCopied)); } else if (currentAction == ACTION_USERNAME_COPIED) { infoTextView.setText(LocaleController.getString("UsernameCopied", R.string.UsernameCopied)); } else if (currentAction == ACTION_HASHTAG_COPIED) { infoTextView.setText(LocaleController.getString("HashtagCopied", R.string.HashtagCopied)); } else if (currentAction == ACTION_MESSAGE_COPIED) { infoTextView.setText(LocaleController.getString("MessageCopied", R.string.MessageCopied)); } else if (currentAction == ACTION_LINK_COPIED) { iconRawId = R.raw.voip_invite; infoTextView.setText(LocaleController.getString("LinkCopied", R.string.LinkCopied)); } else { infoTextView.setText(LocaleController.getString("TextCopied", R.string.TextCopied)); } leftImageView.setAnimation(iconRawId, 30, 30); timeLeft = 3000; infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); } else if (currentAction == ACTION_NOTIFY_ON) { infoTextView.setText(LocaleController.getString("ChannelNotifyMembersInfoOn", R.string.ChannelNotifyMembersInfoOn)); leftImageView.setAnimation(R.raw.silent_unmute, 30, 30); timeLeft = 3000; infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); } else if (currentAction == ACTION_NOTIFY_OFF) { infoTextView.setText(LocaleController.getString("ChannelNotifyMembersInfoOff", R.string.ChannelNotifyMembersInfoOff)); leftImageView.setAnimation(R.raw.silent_mute, 30, 30); timeLeft = 3000; infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); } else if (currentAction == ACTION_VOIP_INVITE_LINK_SENT) { if (infoObject2 == null) { if (did == UserConfig.getInstance(currentAccount).clientUserId) { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.getString("InvLinkToSavedMessages", R.string.InvLinkToSavedMessages))); } else { if (DialogObject.isChatDialog(did)) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-did); infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("InvLinkToGroup", R.string.InvLinkToGroup, chat.title))); } else { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(did); infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("InvLinkToUser", R.string.InvLinkToUser, UserObject.getFirstName(user)))); } } } else { int amount = (Integer) infoObject2; infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("InvLinkToChats", R.string.InvLinkToChats, LocaleController.formatPluralString("Chats", amount)))); } leftImageView.setAnimation(R.raw.contact_check, 36, 36); timeLeft = 3000; } else if (currentAction == ACTION_FWD_MESSAGES) { Integer count = (Integer) infoObject; if (infoObject2 == null || infoObject2 instanceof TLRPC.TL_forumTopic) { if (did == UserConfig.getInstance(currentAccount).clientUserId) { if (count == 1) { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.getString("FwdMessageToSavedMessages", R.string.FwdMessageToSavedMessages))); } else { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.getString("FwdMessagesToSavedMessages", R.string.FwdMessagesToSavedMessages))); } leftImageView.setAnimation(R.raw.saved_messages, 30, 30); } else { if (DialogObject.isChatDialog(did)) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-did); TLRPC.TL_forumTopic topic = (TLRPC.TL_forumTopic) infoObject2; if (count == 1) { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("FwdMessageToGroup", R.string.FwdMessageToGroup, topic != null ? topic.title : chat.title))); } else { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("FwdMessagesToGroup", R.string.FwdMessagesToGroup, topic != null ? topic.title : chat.title))); } } else { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(did); if (count == 1) { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("FwdMessageToUser", R.string.FwdMessageToUser, UserObject.getFirstName(user)))); } else { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("FwdMessagesToUser", R.string.FwdMessagesToUser, UserObject.getFirstName(user)))); } } leftImageView.setAnimation(R.raw.forward, 30, 30); hapticDelay = 300; } } else { int amount = (Integer) infoObject2; if (count == 1) { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatPluralString("FwdMessageToManyChats", amount))); } else { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatPluralString("FwdMessagesToManyChats", amount))); } leftImageView.setAnimation(R.raw.forward, 30, 30); hapticDelay = 300; } timeLeft = 3000; } else if (currentAction == ACTION_SHARE_BACKGROUND) { Integer count = (Integer) infoObject; if (infoObject2 == null) { if (did == UserConfig.getInstance(currentAccount).clientUserId) { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.getString("BackgroundToSavedMessages", R.string.BackgroundToSavedMessages))); leftImageView.setAnimation(R.raw.saved_messages, 30, 30); } else { if (DialogObject.isChatDialog(did)) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-did); infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("BackgroundToGroup", R.string.BackgroundToGroup, chat.title))); } else { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(did); infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("BackgroundToUser", R.string.BackgroundToUser, UserObject.getFirstName(user)))); } leftImageView.setAnimation(R.raw.forward, 30, 30); } } else { int amount = (Integer) infoObject2; infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("BackgroundToChats", R.string.BackgroundToChats, LocaleController.formatPluralString("Chats", amount)))); leftImageView.setAnimation(R.raw.forward, 30, 30); } timeLeft = 3000; } subinfoTextView.setVisibility(GONE); undoTextView.setTextColor(getThemedColor(Theme.key_undo_cancelColor)); undoButton.setVisibility(GONE); layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams.rightMargin = AndroidUtilities.dp(8); leftImageView.setProgress(0); leftImageView.playAnimation(); if (hapticDelay > 0) { leftImageView.postDelayed(() -> { leftImageView.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING); }, hapticDelay); } } else if (currentAction == ACTION_PROXIMITY_SET || currentAction == ACTION_PROXIMITY_REMOVED) { int radius = (Integer) infoObject; TLRPC.User user = (TLRPC.User) infoObject2; undoImageView.setVisibility(GONE); leftImageView.setVisibility(VISIBLE); if (radius != 0) { infoTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); leftImageView.clearLayerColors(); leftImageView.setLayerColor("BODY.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("Wibe Big.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("Wibe Big 3.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("Wibe Small.**", getThemedColor(Theme.key_undo_infoColor)); infoTextView.setText(LocaleController.getString("ProximityAlertSet", R.string.ProximityAlertSet)); leftImageView.setAnimation(R.raw.ic_unmute, 28, 28); subinfoTextView.setVisibility(VISIBLE); subinfoTextView.setSingleLine(false); subinfoTextView.setMaxLines(3); if (user != null) { subinfoTextView.setText(LocaleController.formatString("ProximityAlertSetInfoUser", R.string.ProximityAlertSetInfoUser, UserObject.getFirstName(user), LocaleController.formatDistance(radius, 2))); } else { subinfoTextView.setText(LocaleController.formatString("ProximityAlertSetInfoGroup2", R.string.ProximityAlertSetInfoGroup2, LocaleController.formatDistance(radius, 2))); } undoButton.setVisibility(GONE); layoutParams.topMargin = AndroidUtilities.dp(6); } else { infoTextView.setTypeface(Typeface.DEFAULT); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); leftImageView.clearLayerColors(); leftImageView.setLayerColor("Body Main.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("Body Top.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("Line.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("Curve Big.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("Curve Small.**", getThemedColor(Theme.key_undo_infoColor)); layoutParams.topMargin = AndroidUtilities.dp(14); infoTextView.setText(LocaleController.getString("ProximityAlertCancelled", R.string.ProximityAlertCancelled)); leftImageView.setAnimation(R.raw.ic_mute, 28, 28); subinfoTextView.setVisibility(GONE); undoTextView.setTextColor(getThemedColor(Theme.key_undo_cancelColor)); undoButton.setVisibility(VISIBLE); } layoutParams.leftMargin = AndroidUtilities.dp(58); leftImageView.setProgress(0); leftImageView.playAnimation(); } else if (currentAction == ACTION_QR_SESSION_ACCEPTED) { TLRPC.TL_authorization authorization = (TLRPC.TL_authorization) infoObject; infoTextView.setText(LocaleController.getString("AuthAnotherClientOk", R.string.AuthAnotherClientOk)); leftImageView.setAnimation(R.raw.contact_check, 36, 36); layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams.topMargin = AndroidUtilities.dp(6); subinfoTextView.setText(authorization.app_name); subinfoTextView.setVisibility(VISIBLE); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); infoTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); undoTextView.setTextColor(getThemedColor(Theme.key_text_RedRegular)); undoImageView.setVisibility(GONE); undoButton.setVisibility(VISIBLE); leftImageView.setVisibility(VISIBLE); leftImageView.setProgress(0); leftImageView.playAnimation(); } else if (currentAction == ACTION_FILTERS_AVAILABLE) { timeLeft = 10000; undoTextView.setText(LocaleController.getString("Open", R.string.Open)); infoTextView.setText(LocaleController.getString("FilterAvailableTitle", R.string.FilterAvailableTitle)); leftImageView.setAnimation(R.raw.filter_new, 36, 36); int margin = (int) Math.ceil(undoTextView.getPaint().measureText(undoTextView.getText().toString())) + AndroidUtilities.dp(26); layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams.rightMargin = margin; layoutParams.topMargin = AndroidUtilities.dp(6); layoutParams = (FrameLayout.LayoutParams) subinfoTextView.getLayoutParams(); layoutParams.rightMargin = margin; String text = LocaleController.getString("FilterAvailableText", R.string.FilterAvailableText); SpannableStringBuilder builder = new SpannableStringBuilder(text); int index1 = text.indexOf('*'); int index2 = text.lastIndexOf('*'); if (index1 >= 0 && index2 >= 0 && index1 != index2) { builder.replace(index2, index2 + 1, ""); builder.replace(index1, index1 + 1, ""); builder.setSpan(new URLSpanNoUnderline("tg://settings/folders"), index1, index2 - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } subinfoTextView.setText(builder); subinfoTextView.setVisibility(VISIBLE); subinfoTextView.setSingleLine(false); subinfoTextView.setMaxLines(2); undoButton.setVisibility(VISIBLE); undoImageView.setVisibility(GONE); leftImageView.setVisibility(VISIBLE); leftImageView.setProgress(0); leftImageView.playAnimation(); } else if (currentAction == ACTION_DICE_INFO || currentAction == ACTION_DICE_NO_SEND_INFO) { timeLeft = 4000; infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); infoTextView.setGravity(Gravity.CENTER_VERTICAL); infoTextView.setMinHeight(AndroidUtilities.dp(30)); String emoji = (String) infoObject; if ("\uD83C\uDFB2".equals(emoji)) { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.getString("DiceInfo2", R.string.DiceInfo2))); leftImageView.setImageResource(R.drawable.dice); } else { if ("\uD83C\uDFAF".equals(emoji)) { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.getString("DartInfo", R.string.DartInfo))); } else { String info = LocaleController.getServerString("DiceEmojiInfo_" + emoji); if (!TextUtils.isEmpty(info)) { infoTextView.setText(Emoji.replaceEmoji(info, infoTextView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(14), false)); } else { infoTextView.setText(Emoji.replaceEmoji(LocaleController.formatString("DiceEmojiInfo", R.string.DiceEmojiInfo, emoji), infoTextView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(14), false)); } } leftImageView.setImageDrawable(Emoji.getEmojiDrawable(emoji)); leftImageView.setScaleType(ImageView.ScaleType.FIT_XY); layoutParams.topMargin = AndroidUtilities.dp(14); layoutParams.bottomMargin = AndroidUtilities.dp(14); layoutParams2.leftMargin = AndroidUtilities.dp(14); layoutParams2.width = AndroidUtilities.dp(26); layoutParams2.height = AndroidUtilities.dp(26); } undoTextView.setText(LocaleController.getString("SendDice", R.string.SendDice)); int margin; if (currentAction == ACTION_DICE_INFO) { margin = (int) Math.ceil(undoTextView.getPaint().measureText(undoTextView.getText().toString())) + AndroidUtilities.dp(26); undoTextView.setVisibility(VISIBLE); undoTextView.setTextColor(getThemedColor(Theme.key_undo_cancelColor)); undoImageView.setVisibility(GONE); undoButton.setVisibility(VISIBLE); } else { margin = AndroidUtilities.dp(8); undoTextView.setVisibility(GONE); undoButton.setVisibility(GONE); } layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams.rightMargin = margin; layoutParams.topMargin = AndroidUtilities.dp(6); layoutParams.bottomMargin = AndroidUtilities.dp(7); layoutParams.height = TableLayout.LayoutParams.MATCH_PARENT; subinfoTextView.setVisibility(GONE); leftImageView.setVisibility(VISIBLE); } else if (currentAction == ACTION_TEXT_INFO) { CharSequence info = (CharSequence) infoObject; timeLeft = Math.max(4000, Math.min(info.length() / 50 * 1600, 10000)); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); infoTextView.setGravity(Gravity.CENTER_VERTICAL); infoTextView.setText(info); undoTextView.setVisibility(GONE); undoButton.setVisibility(GONE); layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams.rightMargin = AndroidUtilities.dp(8); layoutParams.topMargin = AndroidUtilities.dp(6); layoutParams.bottomMargin = AndroidUtilities.dp(7); layoutParams.height = TableLayout.LayoutParams.MATCH_PARENT; layoutParams2.gravity = Gravity.TOP | Gravity.LEFT; layoutParams2.topMargin = layoutParams2.bottomMargin = AndroidUtilities.dp(8); leftImageView.setVisibility(VISIBLE); leftImageView.setAnimation(R.raw.chats_infotip, 36, 36); leftImageView.setProgress(0); leftImageView.playAnimation(); infoTextView.setMovementMethod(new AndroidUtilities.LinkMovementMethodMy()); } else if (currentAction == ACTION_THEME_CHANGED) { infoTextView.setText(LocaleController.getString("ColorThemeChanged", R.string.ColorThemeChanged)); leftImageView.setImageResource(R.drawable.toast_pallete); layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams.rightMargin = AndroidUtilities.dp(48); layoutParams.topMargin = AndroidUtilities.dp(6); layoutParams = (FrameLayout.LayoutParams) subinfoTextView.getLayoutParams(); layoutParams.rightMargin = AndroidUtilities.dp(48); String text = LocaleController.getString("ColorThemeChangedInfo", R.string.ColorThemeChangedInfo); SpannableStringBuilder builder = new SpannableStringBuilder(text); int index1 = text.indexOf('*'); int index2 = text.lastIndexOf('*'); if (index1 >= 0 && index2 >= 0 && index1 != index2) { builder.replace(index2, index2 + 1, ""); builder.replace(index1, index1 + 1, ""); builder.setSpan(new URLSpanNoUnderline("tg://settings/themes"), index1, index2 - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } subinfoTextView.setText(builder); subinfoTextView.setVisibility(VISIBLE); subinfoTextView.setSingleLine(false); subinfoTextView.setMaxLines(2); undoTextView.setVisibility(GONE); undoButton.setVisibility(VISIBLE); leftImageView.setVisibility(VISIBLE); } else if (currentAction == ACTION_PREMIUM_TRANSCRIPTION) { infoTextView.setVisibility(VISIBLE); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); infoTextView.setTypeface(Typeface.DEFAULT); infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.getString("UnlockPremiumTranscriptionHint", R.string.UnlockPremiumTranscriptionHint))); leftImageView.setVisibility(VISIBLE); leftImageView.setAnimation(R.raw.voice_to_text, 36, 36); leftImageView.setProgress(0); leftImageView.playAnimation(); undoTextView.setText(LocaleController.getString("PremiumMore", R.string.PremiumMore)); layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams.rightMargin = (int) Math.ceil(undoTextView.getPaint().measureText(undoTextView.getText().toString())) + AndroidUtilities.dp(26); layoutParams.topMargin = layoutParams.bottomMargin = AndroidUtilities.dp(6); layoutParams.height = TableLayout.LayoutParams.WRAP_CONTENT; avatarImageView.setVisibility(GONE); subinfoTextView.setVisibility(GONE); undoTextView.setVisibility(VISIBLE); undoButton.setVisibility(VISIBLE); undoImageView.setVisibility(GONE); } else if (currentAction == ACTION_HINT_SWIPE_TO_REPLY) { infoTextView.setVisibility(VISIBLE); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); infoTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); infoTextView.setText(LocaleController.getString("SwipeToReplyHint", R.string.SwipeToReplyHint)); leftImageView.setVisibility(VISIBLE); leftImageView.setAnimation(R.raw.hint_swipe_reply, (int) (36 * 1.8f), (int) (36 * 1.8f)); leftImageView.setProgress(0); leftImageView.playAnimation(); subinfoTextView.setVisibility(VISIBLE); subinfoTextView.setText(LocaleController.getString("SwipeToReplyHintMessage", R.string.SwipeToReplyHintMessage)); layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams.rightMargin = (int) Math.ceil(undoTextView.getPaint().measureText(undoTextView.getText().toString())) + AndroidUtilities.dp(26); layoutParams.topMargin = AndroidUtilities.dp(6); layoutParams.height = TableLayout.LayoutParams.WRAP_CONTENT; avatarImageView.setVisibility(GONE); undoButton.setVisibility(GONE); } else if (currentAction == ACTION_BOOSTING_SELECTOR_WARNING_CHANNEL || currentAction == ACTION_BOOSTING_SELECTOR_WARNING_USERS || currentAction == ACTION_BOOSTING_SELECTOR_WARNING_COUNTRY || currentAction == ACTION_BOOSTING_AWAIT || currentAction == ACTION_BOOSTING_ONLY_RECIPIENT_CODE ) { switch (currentAction) { case ACTION_BOOSTING_ONLY_RECIPIENT_CODE: infoTextView.setText(LocaleController.getString("BoostingOnlyRecipientCode", R.string.BoostingOnlyRecipientCode)); break; case ACTION_BOOSTING_SELECTOR_WARNING_USERS: infoTextView.setText(LocaleController.getString("BoostingSelectUpToWarningUsers", R.string.BoostingSelectUpToWarningUsers)); break; case ACTION_BOOSTING_SELECTOR_WARNING_CHANNEL: infoTextView.setText(LocaleController.formatPluralString("BoostingSelectUpToWarningChannelsPlural", (int) BoostRepository.giveawayAddPeersMax())); break; case ACTION_BOOSTING_SELECTOR_WARNING_COUNTRY: infoTextView.setText(LocaleController.formatPluralString("BoostingSelectUpToWarningCountriesPlural", (int) BoostRepository.giveawayCountriesMax())); break; case ACTION_BOOSTING_AWAIT: infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatPluralString("BoostingWaitWarningPlural", BoostRepository.boostsPerSentGift()))); break; } layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams.rightMargin = AndroidUtilities.dp(8); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); undoButton.setVisibility(GONE); infoTextView.setTypeface(Typeface.DEFAULT); subinfoTextView.setVisibility(GONE); leftImageView.setVisibility(VISIBLE); leftImageView.setAnimation(R.raw.chats_infotip, 36, 36); leftImageView.setProgress(0); leftImageView.playAnimation(); } else if (currentAction == ACTION_ARCHIVE || currentAction == ACTION_ARCHIVE_FEW) { if (action == ACTION_ARCHIVE) { infoTextView.setText(LocaleController.getString("ChatArchived", R.string.ChatArchived)); } else { infoTextView.setText(LocaleController.getString("ChatsArchived", R.string.ChatsArchived)); } layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams.topMargin = AndroidUtilities.dp(13); layoutParams.rightMargin = 0; infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); undoButton.setVisibility(VISIBLE); infoTextView.setTypeface(Typeface.DEFAULT); subinfoTextView.setVisibility(GONE); leftImageView.setVisibility(VISIBLE); leftImageView.setAnimation(R.raw.chats_archived, 36, 36); leftImageView.setProgress(0); leftImageView.playAnimation(); } else if (action == ACTION_PREVIEW_MEDIA_DESELECTED) { layoutParams.leftMargin = AndroidUtilities.dp(58); MediaController.PhotoEntry photoEntry = (MediaController.PhotoEntry) infoObject; infoTextView.setText(photoEntry.isVideo ? LocaleController.getString("AttachMediaVideoDeselected", R.string.AttachMediaVideoDeselected) : LocaleController.getString("AttachMediaPhotoDeselected", R.string.AttachMediaPhotoDeselected)); undoButton.setVisibility(VISIBLE); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); infoTextView.setTypeface(Typeface.DEFAULT); subinfoTextView.setVisibility(GONE); avatarImageView.setVisibility(VISIBLE); avatarImageView.setRoundRadius(AndroidUtilities.dp(2)); if (photoEntry.thumbPath != null) { avatarImageView.setImage(photoEntry.thumbPath, null, Theme.chat_attachEmptyDrawable); } else if (photoEntry.path != null) { avatarImageView.setOrientation(photoEntry.orientation, photoEntry.invert, true); if (photoEntry.isVideo) { avatarImageView.setImage("vthumb://" + photoEntry.imageId + ":" + photoEntry.path, null, Theme.chat_attachEmptyDrawable); } else { avatarImageView.setImage("thumb://" + photoEntry.imageId + ":" + photoEntry.path, null, Theme.chat_attachEmptyDrawable); } } else { avatarImageView.setImageDrawable(Theme.chat_attachEmptyDrawable); } } else { layoutParams.leftMargin = AndroidUtilities.dp(45); layoutParams.topMargin = AndroidUtilities.dp(13); layoutParams.rightMargin = 0; infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); undoButton.setVisibility(VISIBLE); infoTextView.setTypeface(Typeface.DEFAULT); subinfoTextView.setVisibility(GONE); leftImageView.setVisibility(GONE); if (currentAction == ACTION_SHARED_FOLDER_DELETED) { String folderName = (String) infoObject; int chatsCount = (Integer) infoObject2; if (chatsCount > 0) { int margin = (int) Math.ceil(undoTextView.getPaint().measureText(undoTextView.getText().toString())) + AndroidUtilities.dp(26); layoutParams.leftMargin = AndroidUtilities.dp(48); layoutParams.rightMargin = margin; layoutParams.topMargin = AndroidUtilities.dp(6); layoutParams = (FrameLayout.LayoutParams) subinfoTextView.getLayoutParams(); layoutParams.leftMargin = AndroidUtilities.dp(48); layoutParams.rightMargin = margin; infoTextView.setText(LocaleController.formatString("FolderLinkDeletedTitle", R.string.FolderLinkDeletedTitle, folderName)); infoTextView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); subinfoTextView.setVisibility(VISIBLE); subinfoTextView.setText(LocaleController.formatPluralString("FolderLinkDeletedSubtitle", chatsCount)); } else { infoTextView.setTypeface(Typeface.DEFAULT); infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("FolderLinkDeleted", R.string.FolderLinkDeleted, (folderName == null ? "" : folderName).replace('*', '✱')))); } } else if (currentAction == ACTION_CLEAR_DATES || currentAction == ACTION_CLEAR || currentAction == ACTION_CLEAR_FEW) { infoTextView.setText(LocaleController.getString("HistoryClearedUndo", R.string.HistoryClearedUndo)); } else if (currentAction == ACTION_DELETE_FEW) { infoTextView.setText(LocaleController.getString("ChatsDeletedUndo", R.string.ChatsDeletedUndo)); } else { if (DialogObject.isChatDialog(did)) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-did); if (ChatObject.isChannel(chat) && !chat.megagroup) { infoTextView.setText(LocaleController.getString("ChannelDeletedUndo", R.string.ChannelDeletedUndo)); } else { infoTextView.setText(LocaleController.getString("GroupDeletedUndo", R.string.GroupDeletedUndo)); } } else { infoTextView.setText(LocaleController.getString("ChatDeletedUndo", R.string.ChatDeletedUndo)); } } if (currentAction != ACTION_CLEAR_DATES) { for (int a = 0; a < dialogIds.size(); a++) { MessagesController.getInstance(currentAccount).addDialogAction(dialogIds.get(a), currentAction == ACTION_CLEAR || currentAction == ACTION_CLEAR_FEW); } } } AndroidUtilities.makeAccessibilityAnnouncement(infoTextView.getText() + (subinfoTextView.getVisibility() == VISIBLE ? ". " + subinfoTextView.getText() : "")); if (isMultilineSubInfo()) { ViewGroup parent = (ViewGroup) getParent(); int width = parent.getMeasuredWidth(); if (width == 0) { width = AndroidUtilities.displaySize.x; } width -= AndroidUtilities.dp(16); measureChildWithMargins(subinfoTextView, MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), 0, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 0); undoViewHeight = subinfoTextView.getMeasuredHeight() + AndroidUtilities.dp(27 + 10); } else if (hasSubInfo()) { undoViewHeight = AndroidUtilities.dp(52); } else if (getParent() instanceof ViewGroup) { ViewGroup parent = (ViewGroup) getParent(); int width = parent.getMeasuredWidth() - parent.getPaddingLeft() - parent.getPaddingRight(); if (width <= 0) { width = AndroidUtilities.displaySize.x; } width -= AndroidUtilities.dp(16); measureChildWithMargins(infoTextView, MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), 0, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 0); undoViewHeight = infoTextView.getMeasuredHeight() + AndroidUtilities.dp(currentAction == ACTION_DICE_INFO || currentAction == ACTION_DICE_NO_SEND_INFO || currentAction == ACTION_TEXT_INFO || currentAction == ACTION_PREMIUM_TRANSCRIPTION || currentAction == ACTION_PREMIUM_ALL_FOLDER ? 14 : 28); if (currentAction == ACTION_TEXT_INFO) { undoViewHeight = Math.max(undoViewHeight, AndroidUtilities.dp(52)); } else if (currentAction == ACTION_PROXIMITY_REMOVED) { undoViewHeight = Math.max(undoViewHeight, AndroidUtilities.dp(50)); } else if (infoOnly) { undoViewHeight -= AndroidUtilities.dp(8); } } if (getVisibility() != VISIBLE) { setVisibility(VISIBLE); setEnterOffset((fromTop ? -1.0f : 1.0f) * (enterOffsetMargin + undoViewHeight)); AnimatorSet animatorSet = new AnimatorSet(); animatorSet.playTogether(ObjectAnimator.ofFloat(this, "enterOffset", (fromTop ? -1.0f : 1.0f) * (enterOffsetMargin + undoViewHeight), (fromTop ? 1.0f : -1.0f))); animatorSet.setInterpolator(new DecelerateInterpolator()); animatorSet.setDuration(180); animatorSet.start(); } } private int enterOffsetMargin = AndroidUtilities.dp(8); public void setEnterOffsetMargin(int enterOffsetMargin) { this.enterOffsetMargin = enterOffsetMargin; } protected boolean canUndo() { return true; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(undoViewHeight, MeasureSpec.EXACTLY)); backgroundDrawable.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight()); } StaticLayout timeLayout; StaticLayout timeLayoutOut; int textWidthOut; float timeReplaceProgress = 1f; @Override protected void dispatchDraw(Canvas canvas) { if (additionalTranslationY != 0) { canvas.save(); float bottom = getMeasuredHeight() - enterOffset + AndroidUtilities.dp(9); if (bottom > 0) { canvas.clipRect(0, 0, getMeasuredWidth(), bottom); super.dispatchDraw(canvas); } canvas.restore(); } else { super.dispatchDraw(canvas); } } @Override protected void onDraw(Canvas canvas) { if (additionalTranslationY != 0) { canvas.save(); float bottom = getMeasuredHeight() - enterOffset + enterOffsetMargin + AndroidUtilities.dp(1); if (bottom > 0) { canvas.clipRect(0, 0, getMeasuredWidth(), bottom); super.dispatchDraw(canvas); } backgroundDrawable.draw(canvas); canvas.restore(); } else { backgroundDrawable.draw(canvas); } if (currentAction == ACTION_DELETE || currentAction == ACTION_CLEAR || currentAction == ACTION_DELETE_FEW || currentAction == ACTION_CLEAR_FEW || currentAction == ACTION_CLEAR_DATES || currentAction == ACTION_SHARED_FOLDER_DELETED) { int newSeconds = timeLeft > 0 ? (int) Math.ceil(timeLeft / 1000.0f) : 0; if (prevSeconds != newSeconds) { prevSeconds = newSeconds; timeLeftString = String.format("%d", Math.max(1, newSeconds)); if (timeLayout != null) { timeLayoutOut = timeLayout; timeReplaceProgress = 0; textWidthOut = textWidth; } textWidth = (int) Math.ceil(textPaint.measureText(timeLeftString)); timeLayout = new StaticLayout(timeLeftString, textPaint, Integer.MAX_VALUE, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); } if (timeReplaceProgress < 1f) { timeReplaceProgress += 16f / 150f; if (timeReplaceProgress > 1f) { timeReplaceProgress = 1f; } else { invalidate(); } } int alpha = textPaint.getAlpha(); if (timeLayoutOut != null && timeReplaceProgress < 1f) { textPaint.setAlpha((int) (alpha * (1f - timeReplaceProgress))); canvas.save(); canvas.translate(rect.centerX() - textWidth / 2, AndroidUtilities.dp(17.2f) + AndroidUtilities.dp(10) * timeReplaceProgress); timeLayoutOut.draw(canvas); textPaint.setAlpha(alpha); canvas.restore(); } if (timeLayout != null) { if (timeReplaceProgress != 1f) { textPaint.setAlpha((int) (alpha * timeReplaceProgress)); } canvas.save(); canvas.translate(rect.centerX() - textWidth / 2, AndroidUtilities.dp(17.2f) - AndroidUtilities.dp(10) * (1f - timeReplaceProgress)); timeLayout.draw(canvas); if (timeReplaceProgress != 1f) { textPaint.setAlpha(alpha); } canvas.restore(); } // canvas.drawText(timeLeftString, rect.centerX() - textWidth / 2, AndroidUtilities.dp(28.2f), textPaint); // canvas.drawText(timeLeftString, , textPaint); canvas.drawArc(rect, -90, -360 * (timeLeft / 5000.0f), false, progressPaint); } long newTime = SystemClock.elapsedRealtime(); long dt = newTime - lastUpdateTime; timeLeft -= dt; lastUpdateTime = newTime; if (timeLeft <= 0) { hide(true, hideAnimationType); } if (currentAction != ACTION_PREVIEW_MEDIA_DESELECTED) { invalidate(); } } @Override public void invalidate() { super.invalidate(); infoTextView.invalidate(); leftImageView.invalidate(); } public void setInfoText(CharSequence text) { infoText = text; } public void setHideAnimationType(int hideAnimationType) { this.hideAnimationType = hideAnimationType; } float enterOffset; @Keep public float getEnterOffset() { return enterOffset; } @Keep public void setEnterOffset(float enterOffset) { if (this.enterOffset != enterOffset) { this.enterOffset = enterOffset; updatePosition(); } } private void updatePosition() { setTranslationY(enterOffset - enterOffsetMargin + AndroidUtilities.dp(8) - additionalTranslationY); invalidate(); } @Override public Drawable getBackground() { return backgroundDrawable; } private int getThemedColor(int key) { return Theme.getColor(key, resourcesProvider); } }
alimy/Telegram
TMessagesProj/src/main/java/org/telegram/ui/Components/UndoView.java
41,710
package org.telegram.ui.Components; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.RectF; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.SystemClock; import android.text.Layout; import android.text.Selection; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.StaticLayout; import android.text.TextPaint; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.text.style.CharacterStyle; import android.util.TypedValue; import android.view.Gravity; import android.view.HapticFeedbackConstants; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.DecelerateInterpolator; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.DrawableRes; import androidx.annotation.Keep; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ChatObject; import org.telegram.messenger.ContactsController; import org.telegram.messenger.DialogObject; import org.telegram.messenger.Emoji; import org.telegram.messenger.FileLog; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MediaController; import org.telegram.messenger.MessagesController; import org.telegram.messenger.R; import org.telegram.messenger.UserConfig; import org.telegram.messenger.UserObject; import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.PaymentFormActivity; import java.util.ArrayList; @SuppressWarnings("FieldCanBeLocal") public class UndoView extends FrameLayout { private TextView infoTextView; private TextView subinfoTextView; private TextView undoTextView; private ImageView undoImageView; private RLottieImageView leftImageView; private BackupImageView avatarImageView; private LinearLayout undoButton; private int undoViewHeight; private BaseFragment parentFragment; private Object currentInfoObject; private int currentAccount = UserConfig.selectedAccount; private TextPaint textPaint; private Paint progressPaint; private RectF rect; private long timeLeft; private int prevSeconds; private String timeLeftString; private int textWidth; private int currentAction = -1; private ArrayList<Long> currentDialogIds; private Runnable currentActionRunnable; private Runnable currentCancelRunnable; private long lastUpdateTime; private float additionalTranslationY; private boolean isShown; private boolean fromTop; public final static int ACTION_CLEAR = 0; public final static int ACTION_DELETE = 1; public final static int ACTION_ARCHIVE = 2; public final static int ACTION_ARCHIVE_HINT = 3; public final static int ACTION_ARCHIVE_FEW = 4; public final static int ACTION_ARCHIVE_FEW_HINT = 5; public final static int ACTION_ARCHIVE_HIDDEN = 6; public final static int ACTION_ARCHIVE_PINNED = 7; public final static int ACTION_CONTACT_ADDED = 8; public final static int ACTION_OWNER_TRANSFERED_CHANNEL = 9; public final static int ACTION_OWNER_TRANSFERED_GROUP = 10; public final static int ACTION_QR_SESSION_ACCEPTED = 11; public final static int ACTION_THEME_CHANGED = 12; public final static int ACTION_QUIZ_CORRECT = 13; public final static int ACTION_QUIZ_INCORRECT = 14; public final static int ACTION_FILTERS_AVAILABLE = 15; public final static int ACTION_DICE_INFO = 16; public final static int ACTION_DICE_NO_SEND_INFO = 17; public final static int ACTION_TEXT_INFO = 18; public final static int ACTION_CACHE_WAS_CLEARED = 19; public final static int ACTION_ADDED_TO_FOLDER = 20; public final static int ACTION_REMOVED_FROM_FOLDER = 21; public final static int ACTION_PROFILE_PHOTO_CHANGED = 22; public final static int ACTION_CHAT_UNARCHIVED = 23; public final static int ACTION_PROXIMITY_SET = 24; public final static int ACTION_PROXIMITY_REMOVED = 25; public final static int ACTION_CLEAR_FEW = 26; public final static int ACTION_DELETE_FEW = 27; public final static int ACTION_VOIP_MUTED = 30; public final static int ACTION_VOIP_UNMUTED = 31; public final static int ACTION_VOIP_REMOVED = 32; public final static int ACTION_VOIP_LINK_COPIED = 33; public final static int ACTION_VOIP_INVITED = 34; public final static int ACTION_VOIP_MUTED_FOR_YOU = 35; public final static int ACTION_VOIP_UNMUTED_FOR_YOU = 36; public final static int ACTION_VOIP_USER_CHANGED = 37; public final static int ACTION_VOIP_CAN_NOW_SPEAK = 38; public final static int ACTION_VOIP_RECORDING_STARTED = 39; public final static int ACTION_VOIP_RECORDING_FINISHED = 40; public final static int ACTION_VOIP_INVITE_LINK_SENT = 41; public final static int ACTION_VOIP_SOUND_MUTED = 42; public final static int ACTION_VOIP_SOUND_UNMUTED = 43; public final static int ACTION_VOIP_USER_JOINED = 44; public final static int ACTION_VOIP_VIDEO_RECORDING_STARTED = 100; public final static int ACTION_VOIP_VIDEO_RECORDING_FINISHED = 101; public final static int ACTION_IMPORT_NOT_MUTUAL = 45; public final static int ACTION_IMPORT_GROUP_NOT_ADMIN = 46; public final static int ACTION_IMPORT_INFO = 47; public final static int ACTION_MESSAGE_COPIED = 52; public final static int ACTION_FWD_MESSAGES = 53; public final static int ACTION_NOTIFY_ON = 54; public final static int ACTION_NOTIFY_OFF = 55; public final static int ACTION_USERNAME_COPIED = 56; public final static int ACTION_HASHTAG_COPIED = 57; public final static int ACTION_TEXT_COPIED = 58; public final static int ACTION_LINK_COPIED = 59; public final static int ACTION_PHONE_COPIED = 60; public final static int ACTION_SHARE_BACKGROUND = 61; public final static int ACTION_AUTO_DELETE_ON = 70; public final static int ACTION_AUTO_DELETE_OFF = 71; public final static int ACTION_REPORT_SENT = 74; public final static int ACTION_GIGAGROUP_CANCEL = 75; public final static int ACTION_GIGAGROUP_SUCCESS = 76; public final static int ACTION_PAYMENT_SUCCESS = 77; public final static int ACTION_PIN_DIALOGS = 78; public final static int ACTION_UNPIN_DIALOGS = 79; public final static int ACTION_EMAIL_COPIED = 80; public final static int ACTION_CLEAR_DATES = 81; public final static int ACTION_PREVIEW_MEDIA_DESELECTED = 82; public static int ACTION_RINGTONE_ADDED = 83; public final static int ACTION_PREMIUM_TRANSCRIPTION = 84; public final static int ACTION_HINT_SWIPE_TO_REPLY = 85; public final static int ACTION_PREMIUM_ALL_FOLDER = 86; public final static int ACTION_PROXY_ADDED = 87; private CharSequence infoText; private int hideAnimationType = 1; Drawable backgroundDrawable; private final Theme.ResourcesProvider resourcesProvider; public class LinkMovementMethodMy extends LinkMovementMethod { @Override public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { try { boolean result; if (event.getAction() == MotionEvent.ACTION_DOWN) { CharacterStyle[] links = buffer.getSpans(widget.getSelectionStart(), widget.getSelectionEnd(), CharacterStyle.class); if (links == null || links.length == 0) { return false; } } if (event.getAction() == MotionEvent.ACTION_UP) { CharacterStyle[] links = buffer.getSpans(widget.getSelectionStart(), widget.getSelectionEnd(), CharacterStyle.class); if (links != null && links.length > 0) { didPressUrl(links[0]); } Selection.removeSelection(buffer); result = true; } else { result = super.onTouchEvent(widget, buffer, event); } return result; } catch (Exception e) { FileLog.e(e); } return false; } } public UndoView(Context context) { this(context, null, false, null); } public UndoView(Context context, BaseFragment parent) { this(context, parent, false, null); } public UndoView(Context context, BaseFragment parent, boolean top, Theme.ResourcesProvider resourcesProvider) { super(context); this.resourcesProvider = resourcesProvider; parentFragment = parent; fromTop = top; infoTextView = new TextView(context); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); infoTextView.setTextColor(getThemedColor(Theme.key_undo_infoColor)); infoTextView.setLinkTextColor(getThemedColor(Theme.key_undo_cancelColor)); infoTextView.setMovementMethod(new LinkMovementMethodMy()); addView(infoTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 45, 13, 0, 0)); subinfoTextView = new TextView(context); subinfoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13); subinfoTextView.setTextColor(getThemedColor(Theme.key_undo_infoColor)); subinfoTextView.setLinkTextColor(getThemedColor(Theme.key_undo_cancelColor)); subinfoTextView.setHighlightColor(0); subinfoTextView.setSingleLine(true); subinfoTextView.setEllipsize(TextUtils.TruncateAt.END); subinfoTextView.setMovementMethod(new AndroidUtilities.LinkMovementMethodMy()); addView(subinfoTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 58, 27, 8, 0)); leftImageView = new RLottieImageView(context); leftImageView.setScaleType(ImageView.ScaleType.CENTER); leftImageView.setLayerColor("info1.**", getThemedColor(Theme.key_undo_background) | 0xff000000); leftImageView.setLayerColor("info2.**", getThemedColor(Theme.key_undo_background) | 0xff000000); leftImageView.setLayerColor("luc12.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("luc11.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("luc10.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("luc9.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("luc8.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("luc7.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("luc6.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("luc5.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("luc4.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("luc3.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("luc2.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("luc1.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("Oval.**", getThemedColor(Theme.key_undo_infoColor)); addView(leftImageView, LayoutHelper.createFrame(54, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.LEFT, 3, 0, 0, 0)); avatarImageView = new BackupImageView(context); avatarImageView.setRoundRadius(AndroidUtilities.dp(15)); addView(avatarImageView, LayoutHelper.createFrame(30, 30, Gravity.CENTER_VERTICAL | Gravity.LEFT, 15, 0, 0, 0)); undoButton = new LinearLayout(context); undoButton.setOrientation(LinearLayout.HORIZONTAL); undoButton.setBackground(Theme.createRadSelectorDrawable(getThemedColor(Theme.key_undo_cancelColor) & 0x22ffffff, AndroidUtilities.dp(2), AndroidUtilities.dp(2))); addView(undoButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.RIGHT, 0, 0, 11, 0)); undoButton.setOnClickListener(v -> { if (!canUndo()) { return; } hide(false, 1); }); undoImageView = new ImageView(context); undoImageView.setImageResource(R.drawable.chats_undo); undoImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_undo_cancelColor), PorterDuff.Mode.MULTIPLY)); undoButton.addView(undoImageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.LEFT, 4, 4, 0, 4)); undoTextView = new TextView(context); undoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); undoTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); undoTextView.setTextColor(getThemedColor(Theme.key_undo_cancelColor)); undoTextView.setText(LocaleController.getString("Undo", R.string.Undo)); undoButton.addView(undoTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.LEFT, 6, 4, 8, 4)); rect = new RectF(AndroidUtilities.dp(15), AndroidUtilities.dp(15), AndroidUtilities.dp(15 + 18), AndroidUtilities.dp(15 + 18)); progressPaint = new Paint(Paint.ANTI_ALIAS_FLAG); progressPaint.setStyle(Paint.Style.STROKE); progressPaint.setStrokeWidth(AndroidUtilities.dp(2)); progressPaint.setStrokeCap(Paint.Cap.ROUND); progressPaint.setColor(getThemedColor(Theme.key_undo_infoColor)); textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); textPaint.setTextSize(AndroidUtilities.dp(12)); textPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textPaint.setColor(getThemedColor(Theme.key_undo_infoColor)); setWillNotDraw(false); backgroundDrawable = Theme.createRoundRectDrawable(AndroidUtilities.dp(10), getThemedColor(Theme.key_undo_background)); setOnTouchListener((v, event) -> true); setVisibility(INVISIBLE); } public void setColors(int background, int text) { Theme.setDrawableColor(backgroundDrawable, background); infoTextView.setTextColor(text); subinfoTextView.setTextColor(text); leftImageView.setLayerColor("info1.**", background | 0xff000000); leftImageView.setLayerColor("info2.**", background | 0xff000000); } private boolean isTooltipAction() { return currentAction == ACTION_ARCHIVE_HIDDEN || currentAction == ACTION_ARCHIVE_HINT || currentAction == ACTION_ARCHIVE_FEW_HINT || currentAction == ACTION_ARCHIVE_PINNED || currentAction == ACTION_CONTACT_ADDED || currentAction == ACTION_PROXY_ADDED || currentAction == ACTION_OWNER_TRANSFERED_CHANNEL || currentAction == ACTION_OWNER_TRANSFERED_GROUP || currentAction == ACTION_QUIZ_CORRECT || currentAction == ACTION_QUIZ_INCORRECT || currentAction == ACTION_CACHE_WAS_CLEARED || currentAction == ACTION_ADDED_TO_FOLDER || currentAction == ACTION_REMOVED_FROM_FOLDER || currentAction == ACTION_PROFILE_PHOTO_CHANGED || currentAction == ACTION_CHAT_UNARCHIVED || currentAction == ACTION_VOIP_MUTED || currentAction == ACTION_VOIP_UNMUTED || currentAction == ACTION_VOIP_REMOVED || currentAction == ACTION_VOIP_LINK_COPIED || currentAction == ACTION_VOIP_INVITED || currentAction == ACTION_VOIP_MUTED_FOR_YOU || currentAction == ACTION_VOIP_UNMUTED_FOR_YOU || currentAction == ACTION_REPORT_SENT || currentAction == ACTION_VOIP_USER_CHANGED || currentAction == ACTION_VOIP_CAN_NOW_SPEAK || currentAction == ACTION_VOIP_RECORDING_STARTED || currentAction == ACTION_VOIP_RECORDING_FINISHED || currentAction == ACTION_VOIP_SOUND_MUTED || currentAction == ACTION_VOIP_SOUND_UNMUTED || currentAction == ACTION_PAYMENT_SUCCESS || currentAction == ACTION_VOIP_USER_JOINED || currentAction == ACTION_PIN_DIALOGS || currentAction == ACTION_UNPIN_DIALOGS || currentAction == ACTION_VOIP_VIDEO_RECORDING_STARTED || currentAction == ACTION_VOIP_VIDEO_RECORDING_FINISHED || currentAction == ACTION_RINGTONE_ADDED; } private boolean hasSubInfo() { return currentAction == ACTION_QR_SESSION_ACCEPTED || currentAction == ACTION_PROXIMITY_SET || currentAction == ACTION_ARCHIVE_HIDDEN || currentAction == ACTION_ARCHIVE_HINT || currentAction == ACTION_ARCHIVE_FEW_HINT || currentAction == ACTION_QUIZ_CORRECT || currentAction == ACTION_QUIZ_INCORRECT || currentAction == ACTION_REPORT_SENT || currentAction == ACTION_ARCHIVE_PINNED && MessagesController.getInstance(currentAccount).dialogFilters.isEmpty() || currentAction == ACTION_RINGTONE_ADDED || currentAction == ACTION_HINT_SWIPE_TO_REPLY; } public boolean isMultilineSubInfo() { return currentAction == ACTION_THEME_CHANGED || currentAction == ACTION_FILTERS_AVAILABLE || currentAction == ACTION_PROXIMITY_SET || currentAction == ACTION_REPORT_SENT || currentAction == ACTION_RINGTONE_ADDED; } public void setAdditionalTranslationY(float value) { if (additionalTranslationY != value) { additionalTranslationY = value; updatePosition(); } } public Object getCurrentInfoObject() { return currentInfoObject; } public void hide(boolean apply, int animated) { if (getVisibility() != VISIBLE || !isShown) { return; } currentInfoObject = null; isShown = false; if (currentActionRunnable != null) { if (apply) { currentActionRunnable.run(); } currentActionRunnable = null; } if (currentCancelRunnable != null) { if (!apply) { currentCancelRunnable.run(); } currentCancelRunnable = null; } if (currentAction == ACTION_CLEAR || currentAction == ACTION_DELETE || currentAction == ACTION_CLEAR_FEW || currentAction == ACTION_DELETE_FEW) { for (int a = 0; a < currentDialogIds.size(); a++) { long did = currentDialogIds.get(a); MessagesController.getInstance(currentAccount).removeDialogAction(did, currentAction == ACTION_CLEAR || currentAction == ACTION_CLEAR_FEW, apply); onRemoveDialogAction(did, currentAction); } } if (animated != 0) { AnimatorSet animatorSet = new AnimatorSet(); if (animated == 1) { animatorSet.playTogether(ObjectAnimator.ofFloat(this, "enterOffset", (fromTop ? -1.0f : 1.0f) * (enterOffsetMargin + undoViewHeight))); animatorSet.setDuration(250); } else { animatorSet.playTogether( ObjectAnimator.ofFloat(this, View.SCALE_X, 0.8f), ObjectAnimator.ofFloat(this, View.SCALE_Y, 0.8f), ObjectAnimator.ofFloat(this, View.ALPHA, 0.0f)); animatorSet.setDuration(180); } animatorSet.setInterpolator(new DecelerateInterpolator()); animatorSet.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { setVisibility(INVISIBLE); setScaleX(1.0f); setScaleY(1.0f); setAlpha(1.0f); } }); animatorSet.start(); } else { setEnterOffset((fromTop ? -1.0f : 1.0f) * (enterOffsetMargin + undoViewHeight)); setVisibility(INVISIBLE); } } protected void onRemoveDialogAction(long currentDialogId, int action) { } public void didPressUrl(CharacterStyle span) { } public void showWithAction(long did, int action, Runnable actionRunnable) { showWithAction(did, action, null, null, actionRunnable, null); } public void showWithAction(long did, int action, Object infoObject) { showWithAction(did, action, infoObject, null, null, null); } public void showWithAction(long did, int action, Runnable actionRunnable, Runnable cancelRunnable) { showWithAction(did, action, null, null, actionRunnable, cancelRunnable); } public void showWithAction(long did, int action, Object infoObject, Runnable actionRunnable, Runnable cancelRunnable) { showWithAction(did, action, infoObject, null, actionRunnable, cancelRunnable); } public void showWithAction(long did, int action, Object infoObject, Object infoObject2, Runnable actionRunnable, Runnable cancelRunnable) { ArrayList<Long> ids = new ArrayList<>(); ids.add(did); showWithAction(ids, action, infoObject, infoObject2, actionRunnable, cancelRunnable); } public void showWithAction(ArrayList<Long> dialogIds, int action, Object infoObject, Object infoObject2, Runnable actionRunnable, Runnable cancelRunnable) { if (!AndroidUtilities.shouldShowClipboardToast() && (currentAction == ACTION_MESSAGE_COPIED || currentAction == ACTION_USERNAME_COPIED || currentAction == ACTION_HASHTAG_COPIED || currentAction == ACTION_TEXT_COPIED || currentAction == ACTION_LINK_COPIED || currentAction == ACTION_PHONE_COPIED || currentAction == ACTION_EMAIL_COPIED || currentAction == ACTION_VOIP_LINK_COPIED)) { return; } if (currentActionRunnable != null) { currentActionRunnable.run(); } isShown = true; currentActionRunnable = actionRunnable; currentCancelRunnable = cancelRunnable; currentDialogIds = dialogIds; long did = dialogIds.get(0); currentAction = action; timeLeft = 5000; currentInfoObject = infoObject; lastUpdateTime = SystemClock.elapsedRealtime(); undoTextView.setText(LocaleController.getString("Undo", R.string.Undo).toUpperCase()); undoImageView.setVisibility(VISIBLE); leftImageView.setPadding(0, 0, 0, 0); leftImageView.setScaleX(1); leftImageView.setScaleY(1); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); avatarImageView.setVisibility(GONE); infoTextView.setGravity(Gravity.LEFT | Gravity.TOP); FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) infoTextView.getLayoutParams(); layoutParams.height = LayoutHelper.WRAP_CONTENT; layoutParams.topMargin = AndroidUtilities.dp(13); layoutParams.bottomMargin = 0; leftImageView.setScaleType(ImageView.ScaleType.CENTER); FrameLayout.LayoutParams layoutParams2 = (FrameLayout.LayoutParams) leftImageView.getLayoutParams(); layoutParams2.gravity = Gravity.CENTER_VERTICAL | Gravity.LEFT; layoutParams2.topMargin = layoutParams2.bottomMargin = 0; layoutParams2.leftMargin = AndroidUtilities.dp(3); layoutParams2.width = AndroidUtilities.dp(54); layoutParams2.height = LayoutHelper.WRAP_CONTENT; infoTextView.setMinHeight(0); boolean infoOnly = false; boolean reversedPlay = false; int reversedPlayEndFrame = 0; if ((actionRunnable == null && cancelRunnable == null) || action == ACTION_RINGTONE_ADDED) { setOnClickListener(view -> hide(false, 1)); setOnTouchListener(null); } else { setOnClickListener(null); setOnTouchListener((v, event) -> true); } infoTextView.setMovementMethod(null); if (isTooltipAction()) { CharSequence infoText; CharSequence subInfoText; @DrawableRes int icon; int size = 36; boolean iconIsDrawable = false; if (action == ACTION_RINGTONE_ADDED) { subinfoTextView.setSingleLine(false); infoText = LocaleController.getString("SoundAdded", R.string.SoundAdded); subInfoText = AndroidUtilities.replaceSingleTag(LocaleController.getString("SoundAddedSubtitle", R.string.SoundAddedSubtitle), actionRunnable); currentActionRunnable = null; icon = R.raw.sound_download; timeLeft = 4000; } else if (action == ACTION_REPORT_SENT) { subinfoTextView.setSingleLine(false); infoText = LocaleController.getString("ReportChatSent", R.string.ReportChatSent); subInfoText = LocaleController.formatString("ReportSentInfo", R.string.ReportSentInfo); icon = R.raw.ic_admin; timeLeft = 4000; } else if (action == ACTION_VOIP_INVITED) { TLRPC.User user = (TLRPC.User) infoObject; TLRPC.Chat chat = (TLRPC.Chat) infoObject2; if (ChatObject.isChannelOrGiga(chat)) { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipChannelInvitedUser", R.string.VoipChannelInvitedUser, UserObject.getFirstName(user))); } else { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipGroupInvitedUser", R.string.VoipGroupInvitedUser, UserObject.getFirstName(user))); } subInfoText = null; icon = 0; AvatarDrawable avatarDrawable = new AvatarDrawable(); avatarDrawable.setTextSize(AndroidUtilities.dp(12)); avatarDrawable.setInfo(user); avatarImageView.setForUserOrChat(user, avatarDrawable); avatarImageView.setVisibility(VISIBLE); timeLeft = 3000; } else if (action == ACTION_VOIP_USER_JOINED) { TLRPC.Chat currentChat = (TLRPC.Chat) infoObject2; if (infoObject instanceof TLRPC.User) { TLRPC.User user = (TLRPC.User) infoObject; if (ChatObject.isChannelOrGiga(currentChat)) { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipChannelUserJoined", R.string.VoipChannelUserJoined, UserObject.getFirstName(user))); } else { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipChatUserJoined", R.string.VoipChatUserJoined, UserObject.getFirstName(user))); } } else { TLRPC.Chat chat = (TLRPC.Chat) infoObject; if (ChatObject.isChannelOrGiga(currentChat)) { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipChannelChatJoined", R.string.VoipChannelChatJoined, chat.title)); } else { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipChatChatJoined", R.string.VoipChatChatJoined, chat.title)); } } subInfoText = null; icon = 0; AvatarDrawable avatarDrawable = new AvatarDrawable(); avatarDrawable.setTextSize(AndroidUtilities.dp(12)); avatarDrawable.setInfo((TLObject) infoObject); avatarImageView.setForUserOrChat((TLObject) infoObject, avatarDrawable); avatarImageView.setVisibility(VISIBLE); timeLeft = 3000; } else if (action == ACTION_VOIP_USER_CHANGED) { AvatarDrawable avatarDrawable = new AvatarDrawable(); avatarDrawable.setTextSize(AndroidUtilities.dp(12)); String name; if (infoObject instanceof TLRPC.User) { TLRPC.User user = (TLRPC.User) infoObject; avatarDrawable.setInfo(user); avatarImageView.setForUserOrChat(user, avatarDrawable); name = ContactsController.formatName(user.first_name, user.last_name); } else { TLRPC.Chat chat = (TLRPC.Chat) infoObject; avatarDrawable.setInfo(chat); avatarImageView.setForUserOrChat(chat, avatarDrawable); name = chat.title; } TLRPC.Chat currentChat = (TLRPC.Chat) infoObject2; if (ChatObject.isChannelOrGiga(currentChat)) { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipChannelUserChanged", R.string.VoipChannelUserChanged, name)); } else { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipGroupUserChanged", R.string.VoipGroupUserChanged, name)); } subInfoText = null; icon = 0; avatarImageView.setVisibility(VISIBLE); timeLeft = 3000; } else if (action == ACTION_VOIP_LINK_COPIED) { infoText = LocaleController.getString("VoipGroupCopyInviteLinkCopied", R.string.VoipGroupCopyInviteLinkCopied); subInfoText = null; icon = R.raw.voip_invite; timeLeft = 3000; } else if (action == ACTION_PAYMENT_SUCCESS) { infoText = (CharSequence) infoObject; subInfoText = null; icon = R.raw.payment_success; timeLeft = 5000; if (parentFragment != null && infoObject2 instanceof TLRPC.Message) { TLRPC.Message message = (TLRPC.Message) infoObject2; setOnTouchListener(null); infoTextView.setMovementMethod(null); setOnClickListener(v -> { hide(true, 1); TLRPC.TL_payments_getPaymentReceipt req = new TLRPC.TL_payments_getPaymentReceipt(); req.msg_id = message.id; req.peer = parentFragment.getMessagesController().getInputPeer(message.peer_id); parentFragment.getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { if (response instanceof TLRPC.TL_payments_paymentReceipt) { parentFragment.presentFragment(new PaymentFormActivity((TLRPC.TL_payments_paymentReceipt) response)); } }), ConnectionsManager.RequestFlagFailOnServerErrors); }); } } else if (action == ACTION_VOIP_MUTED) { String name; if (infoObject instanceof TLRPC.User) { TLRPC.User user = (TLRPC.User) infoObject; name = UserObject.getFirstName(user); } else { TLRPC.Chat chat = (TLRPC.Chat) infoObject; name = chat.title; } infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipGroupUserCantNowSpeak", R.string.VoipGroupUserCantNowSpeak, name)); subInfoText = null; icon = R.raw.voip_muted; timeLeft = 3000; } else if (action == ACTION_VOIP_MUTED_FOR_YOU) { String name; if (infoObject instanceof TLRPC.User) { TLRPC.User user = (TLRPC.User) infoObject; name = UserObject.getFirstName(user); } else if (infoObject instanceof TLRPC.Chat) { TLRPC.Chat chat = (TLRPC.Chat) infoObject; name = chat.title; } else { name = ""; } infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipGroupUserCantNowSpeakForYou", R.string.VoipGroupUserCantNowSpeakForYou, name)); subInfoText = null; icon = R.raw.voip_muted; timeLeft = 3000; } else if (action == ACTION_VOIP_UNMUTED) { String name; if (infoObject instanceof TLRPC.User) { TLRPC.User user = (TLRPC.User) infoObject; name = UserObject.getFirstName(user); } else { TLRPC.Chat chat = (TLRPC.Chat) infoObject; name = chat.title; } infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipGroupUserCanNowSpeak", R.string.VoipGroupUserCanNowSpeak, name)); subInfoText = null; icon = R.raw.voip_unmuted; timeLeft = 3000; } else if (action == ACTION_VOIP_CAN_NOW_SPEAK) { if (infoObject instanceof TLRPC.Chat) { TLRPC.Chat chat = (TLRPC.Chat) infoObject; infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipGroupYouCanNowSpeakIn", R.string.VoipGroupYouCanNowSpeakIn, chat.title)); } else { infoText = AndroidUtilities.replaceTags(LocaleController.getString("VoipGroupYouCanNowSpeak", R.string.VoipGroupYouCanNowSpeak)); } subInfoText = null; icon = R.raw.voip_allow_talk; timeLeft = 3000; } else if (action == ACTION_VOIP_SOUND_MUTED) { TLRPC.Chat chat = (TLRPC.Chat) infoObject; if (ChatObject.isChannelOrGiga(chat)) { infoText = AndroidUtilities.replaceTags(LocaleController.getString("VoipChannelSoundMuted", R.string.VoipChannelSoundMuted)); } else { infoText = AndroidUtilities.replaceTags(LocaleController.getString("VoipGroupSoundMuted", R.string.VoipGroupSoundMuted)); } subInfoText = null; icon = R.raw.ic_mute; timeLeft = 3000; } else if (action == ACTION_VOIP_SOUND_UNMUTED) { TLRPC.Chat chat = (TLRPC.Chat) infoObject; if (ChatObject.isChannelOrGiga(chat)) { infoText = AndroidUtilities.replaceTags(LocaleController.getString("VoipChannelSoundUnmuted", R.string.VoipChannelSoundUnmuted)); } else { infoText = AndroidUtilities.replaceTags(LocaleController.getString("VoipGroupSoundUnmuted", R.string.VoipGroupSoundUnmuted)); } subInfoText = null; icon = R.raw.ic_unmute; timeLeft = 3000; } else if (currentAction == ACTION_VOIP_RECORDING_STARTED || currentAction == ACTION_VOIP_VIDEO_RECORDING_STARTED) { infoText = AndroidUtilities.replaceTags(currentAction == ACTION_VOIP_RECORDING_STARTED ? LocaleController.getString("VoipGroupAudioRecordStarted", R.string.VoipGroupAudioRecordStarted) : LocaleController.getString("VoipGroupVideoRecordStarted", R.string.VoipGroupVideoRecordStarted)); subInfoText = null; icon = R.raw.voip_record_start; timeLeft = 3000; } else if (currentAction == ACTION_VOIP_RECORDING_FINISHED || currentAction == ACTION_VOIP_VIDEO_RECORDING_FINISHED) { String text = currentAction == ACTION_VOIP_RECORDING_FINISHED ? LocaleController.getString("VoipGroupAudioRecordSaved", R.string.VoipGroupAudioRecordSaved) : LocaleController.getString("VoipGroupVideoRecordSaved", R.string.VoipGroupVideoRecordSaved); subInfoText = null; icon = R.raw.voip_record_saved; timeLeft = 4000; infoTextView.setMovementMethod(new AndroidUtilities.LinkMovementMethodMy()); SpannableStringBuilder builder = new SpannableStringBuilder(text); int index1 = text.indexOf("**"); int index2 = text.lastIndexOf("**"); if (index1 >= 0 && index2 >= 0 && index1 != index2) { builder.replace(index2, index2 + 2, ""); builder.replace(index1, index1 + 2, ""); try { builder.setSpan(new URLSpanNoUnderline("tg://openmessage?user_id=" + UserConfig.getInstance(currentAccount).getClientUserId()), index1, index2 - 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } catch (Exception e) { FileLog.e(e); } } infoText = builder; } else if (action == ACTION_VOIP_UNMUTED_FOR_YOU) { String name; if (infoObject instanceof TLRPC.User) { TLRPC.User user = (TLRPC.User) infoObject; name = UserObject.getFirstName(user); } else { TLRPC.Chat chat = (TLRPC.Chat) infoObject; name = chat.title; } infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipGroupUserCanNowSpeakForYou", R.string.VoipGroupUserCanNowSpeakForYou, name)); subInfoText = null; icon = R.raw.voip_unmuted; timeLeft = 3000; } else if (action == ACTION_VOIP_REMOVED) { String name; if (infoObject instanceof TLRPC.User) { TLRPC.User user = (TLRPC.User) infoObject; name = UserObject.getFirstName(user); } else { TLRPC.Chat chat = (TLRPC.Chat) infoObject; name = chat.title; } infoText = AndroidUtilities.replaceTags(LocaleController.formatString("VoipGroupRemovedFromGroup", R.string.VoipGroupRemovedFromGroup, name)); subInfoText = null; icon = R.raw.voip_group_removed; timeLeft = 3000; } else if (action == ACTION_OWNER_TRANSFERED_CHANNEL || action == ACTION_OWNER_TRANSFERED_GROUP) { TLRPC.User user = (TLRPC.User) infoObject; if (action == ACTION_OWNER_TRANSFERED_CHANNEL) { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("EditAdminTransferChannelToast", R.string.EditAdminTransferChannelToast, UserObject.getFirstName(user))); } else { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("EditAdminTransferGroupToast", R.string.EditAdminTransferGroupToast, UserObject.getFirstName(user))); } subInfoText = null; icon = R.raw.contact_check; } else if (action == ACTION_CONTACT_ADDED) { TLRPC.User user = (TLRPC.User) infoObject; infoText = LocaleController.formatString("NowInContacts", R.string.NowInContacts, UserObject.getFirstName(user)); subInfoText = null; icon = R.raw.contact_check; } else if (action == ACTION_PROXY_ADDED) { infoText = LocaleController.formatString(R.string.ProxyAddedSuccess); subInfoText = null; icon = R.raw.contact_check; } else if (action == ACTION_PROFILE_PHOTO_CHANGED) { if (DialogObject.isUserDialog(did)) { if (infoObject == null) { infoText = LocaleController.getString("MainProfilePhotoSetHint", R.string.MainProfilePhotoSetHint); } else { infoText = LocaleController.getString("MainProfileVideoSetHint", R.string.MainProfileVideoSetHint); } } else { TLRPC.Chat chat = MessagesController.getInstance(UserConfig.selectedAccount).getChat(-did); if (ChatObject.isChannel(chat) && !chat.megagroup) { if (infoObject == null) { infoText = LocaleController.getString("MainChannelProfilePhotoSetHint", R.string.MainChannelProfilePhotoSetHint); } else { infoText = LocaleController.getString("MainChannelProfileVideoSetHint", R.string.MainChannelProfileVideoSetHint); } } else { if (infoObject == null) { infoText = LocaleController.getString("MainGroupProfilePhotoSetHint", R.string.MainGroupProfilePhotoSetHint); } else { infoText = LocaleController.getString("MainGroupProfileVideoSetHint", R.string.MainGroupProfileVideoSetHint); } } } subInfoText = null; icon = R.raw.contact_check; } else if (action == ACTION_CHAT_UNARCHIVED) { infoText = LocaleController.getString("ChatWasMovedToMainList", R.string.ChatWasMovedToMainList); subInfoText = null; icon = R.raw.contact_check; } else if (action == ACTION_ARCHIVE_HIDDEN) { infoText = LocaleController.getString("ArchiveHidden", R.string.ArchiveHidden); subInfoText = LocaleController.getString("ArchiveHiddenInfo", R.string.ArchiveHiddenInfo); icon = R.raw.chats_swipearchive; size = 48; } else if (currentAction == ACTION_QUIZ_CORRECT) { infoText = LocaleController.getString("QuizWellDone", R.string.QuizWellDone); subInfoText = LocaleController.getString("QuizWellDoneInfo", R.string.QuizWellDoneInfo); icon = R.raw.wallet_congrats; size = 44; } else if (currentAction == ACTION_QUIZ_INCORRECT) { infoText = LocaleController.getString("QuizWrongAnswer", R.string.QuizWrongAnswer); subInfoText = LocaleController.getString("QuizWrongAnswerInfo", R.string.QuizWrongAnswerInfo); icon = R.raw.wallet_science; size = 44; } else if (action == ACTION_ARCHIVE_PINNED) { infoText = LocaleController.getString("ArchivePinned", R.string.ArchivePinned); if (MessagesController.getInstance(currentAccount).dialogFilters.isEmpty()) { subInfoText = LocaleController.getString("ArchivePinnedInfo", R.string.ArchivePinnedInfo); } else { subInfoText = null; } icon = R.raw.chats_infotip; } else if (action == ACTION_ADDED_TO_FOLDER || action == ACTION_REMOVED_FROM_FOLDER) { MessagesController.DialogFilter filter = (MessagesController.DialogFilter) infoObject2; if (did != 0) { long dialogId = did; if (DialogObject.isEncryptedDialog(did)) { TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(DialogObject.getEncryptedChatId(dialogId)); dialogId = encryptedChat.user_id; } if (DialogObject.isUserDialog(dialogId)) { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(dialogId); if (action == ACTION_ADDED_TO_FOLDER) { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("FilterUserAddedToExisting", R.string.FilterUserAddedToExisting, UserObject.getFirstName(user), filter.name)); } else { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("FilterUserRemovedFrom", R.string.FilterUserRemovedFrom, UserObject.getFirstName(user), filter.name)); } } else { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); if (action == ACTION_ADDED_TO_FOLDER) { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("FilterChatAddedToExisting", R.string.FilterChatAddedToExisting, chat.title, filter.name)); } else { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("FilterChatRemovedFrom", R.string.FilterChatRemovedFrom, chat.title, filter.name)); } } } else { if (action == ACTION_ADDED_TO_FOLDER) { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("FilterChatsAddedToExisting", R.string.FilterChatsAddedToExisting, LocaleController.formatPluralString("ChatsSelected", (Integer) infoObject), filter.name)); } else { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("FilterChatsRemovedFrom", R.string.FilterChatsRemovedFrom, LocaleController.formatPluralString("ChatsSelected", (Integer) infoObject), filter.name)); } } subInfoText = null; icon = action == ACTION_ADDED_TO_FOLDER ? R.raw.folder_in : R.raw.folder_out; } else if (action == ACTION_CACHE_WAS_CLEARED) { infoText = this.infoText; subInfoText = null; icon = R.raw.ic_delete; } else if (action == ACTION_PREVIEW_MEDIA_DESELECTED) { MediaController.PhotoEntry photo = (MediaController.PhotoEntry) infoObject; infoText = photo.isVideo ? LocaleController.getString("AttachMediaVideoDeselected", R.string.AttachMediaVideoDeselected) : LocaleController.getString("AttachMediaPhotoDeselected", R.string.AttachMediaPhotoDeselected); subInfoText = null; icon = 0; } else if (action == ACTION_PIN_DIALOGS || action == ACTION_UNPIN_DIALOGS) { int count = (Integer) infoObject; if (action == ACTION_PIN_DIALOGS) { infoText = LocaleController.formatPluralString("PinnedDialogsCount", count); } else { infoText = LocaleController.formatPluralString("UnpinnedDialogsCount", count); } subInfoText = null; icon = currentAction == ACTION_PIN_DIALOGS ? R.raw.ic_pin : R.raw.ic_unpin; if (infoObject2 instanceof Integer) { timeLeft = (int) infoObject2; } } else { if (action == ACTION_ARCHIVE_HINT) { infoText = LocaleController.getString("ChatArchived", R.string.ChatArchived); } else { infoText = LocaleController.getString("ChatsArchived", R.string.ChatsArchived); } if (MessagesController.getInstance(currentAccount).dialogFilters.isEmpty()) { subInfoText = LocaleController.getString("ChatArchivedInfo", R.string.ChatArchivedInfo); } else { subInfoText = null; } icon = R.raw.chats_infotip; } infoTextView.setText(infoText); if (icon != 0) { if (iconIsDrawable) { leftImageView.setImageResource(icon); } else { leftImageView.setAnimation(icon, size, size); RLottieDrawable drawable = leftImageView.getAnimatedDrawable(); drawable.setPlayInDirectionOfCustomEndFrame(reversedPlay); drawable.setCustomEndFrame(reversedPlay ? reversedPlayEndFrame : drawable.getFramesCount()); } leftImageView.setVisibility(VISIBLE); if (!iconIsDrawable) { leftImageView.setProgress(reversedPlay ? 1 : 0); leftImageView.playAnimation(); } } else { leftImageView.setVisibility(GONE); } if (subInfoText != null) { layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams.topMargin = AndroidUtilities.dp(6); layoutParams.rightMargin = AndroidUtilities.dp(8); layoutParams = (FrameLayout.LayoutParams) subinfoTextView.getLayoutParams(); layoutParams.rightMargin = AndroidUtilities.dp(8); subinfoTextView.setText(subInfoText); subinfoTextView.setVisibility(VISIBLE); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); infoTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); } else { layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams.topMargin = AndroidUtilities.dp(13); layoutParams.rightMargin = AndroidUtilities.dp(8); subinfoTextView.setVisibility(GONE); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); infoTextView.setTypeface(Typeface.DEFAULT); } undoButton.setVisibility(GONE); } else if (currentAction == ACTION_IMPORT_NOT_MUTUAL || currentAction == ACTION_IMPORT_GROUP_NOT_ADMIN || currentAction == ACTION_IMPORT_INFO || currentAction == ACTION_MESSAGE_COPIED || currentAction == ACTION_FWD_MESSAGES || currentAction == ACTION_NOTIFY_ON || currentAction == ACTION_NOTIFY_OFF || currentAction == ACTION_USERNAME_COPIED || currentAction == ACTION_HASHTAG_COPIED || currentAction == ACTION_TEXT_COPIED || currentAction == ACTION_LINK_COPIED || currentAction == ACTION_PHONE_COPIED || currentAction == ACTION_AUTO_DELETE_OFF || currentAction == ACTION_AUTO_DELETE_ON || currentAction == ACTION_GIGAGROUP_CANCEL || currentAction == ACTION_GIGAGROUP_SUCCESS || currentAction == ACTION_VOIP_INVITE_LINK_SENT || currentAction == ACTION_PIN_DIALOGS || currentAction == ACTION_UNPIN_DIALOGS || currentAction == ACTION_SHARE_BACKGROUND || currentAction == ACTION_EMAIL_COPIED) { undoImageView.setVisibility(GONE); leftImageView.setVisibility(VISIBLE); infoTextView.setTypeface(Typeface.DEFAULT); long hapticDelay = -1; if (currentAction == ACTION_GIGAGROUP_SUCCESS) { infoTextView.setText(LocaleController.getString("BroadcastGroupConvertSuccess", R.string.BroadcastGroupConvertSuccess)); leftImageView.setAnimation(R.raw.gigagroup_convert, 36, 36); infoOnly = true; layoutParams.topMargin = AndroidUtilities.dp(9); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); } else if (currentAction == ACTION_GIGAGROUP_CANCEL) { infoTextView.setText(LocaleController.getString("GigagroupConvertCancelHint", R.string.GigagroupConvertCancelHint)); leftImageView.setAnimation(R.raw.chats_infotip, 36, 36); infoOnly = true; layoutParams.topMargin = AndroidUtilities.dp(9); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); } else if (action == ACTION_AUTO_DELETE_ON) { TLRPC.User user = (TLRPC.User) infoObject; int ttl = (Integer) infoObject2; subinfoTextView.setSingleLine(false); String time = LocaleController.formatTTLString(ttl); infoTextView.setText(LocaleController.formatString("AutoDeleteHintOnText", R.string.AutoDeleteHintOnText, time)); leftImageView.setAnimation(R.raw.fire_on, 36, 36); layoutParams.topMargin = AndroidUtilities.dp(9); timeLeft = 4000; infoOnly = true; leftImageView.setPadding(0, 0, 0, AndroidUtilities.dp(3)); } else if (currentAction == ACTION_AUTO_DELETE_OFF) { infoTextView.setText(LocaleController.getString("AutoDeleteHintOffText", R.string.AutoDeleteHintOffText)); leftImageView.setAnimation(R.raw.fire_off, 36, 36); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); timeLeft = 3000; leftImageView.setPadding(0, 0, 0, AndroidUtilities.dp(4)); } else if (currentAction == ACTION_IMPORT_NOT_MUTUAL) { infoTextView.setText(LocaleController.getString("ImportMutualError", R.string.ImportMutualError)); leftImageView.setAnimation(R.raw.error, 36, 36); infoOnly = true; layoutParams.topMargin = AndroidUtilities.dp(9); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); } else if (currentAction == ACTION_IMPORT_GROUP_NOT_ADMIN) { infoTextView.setText(LocaleController.getString("ImportNotAdmin", R.string.ImportNotAdmin)); leftImageView.setAnimation(R.raw.error, 36, 36); infoOnly = true; layoutParams.topMargin = AndroidUtilities.dp(9); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); } else if (currentAction == ACTION_IMPORT_INFO) { infoTextView.setText(LocaleController.getString("ImportedInfo", R.string.ImportedInfo)); leftImageView.setAnimation(R.raw.imported, 36, 36); leftImageView.setPadding(0, 0, 0, AndroidUtilities.dp(5)); infoOnly = true; layoutParams.topMargin = AndroidUtilities.dp(9); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); } else if (currentAction == ACTION_MESSAGE_COPIED || currentAction == ACTION_USERNAME_COPIED || currentAction == ACTION_HASHTAG_COPIED || currentAction == ACTION_TEXT_COPIED || currentAction == ACTION_LINK_COPIED || currentAction == ACTION_PHONE_COPIED || currentAction == ACTION_EMAIL_COPIED) { if (!AndroidUtilities.shouldShowClipboardToast()) { return; } int iconRawId = R.raw.copy; if (currentAction == ACTION_EMAIL_COPIED) { infoTextView.setText(LocaleController.getString("EmailCopied", R.string.EmailCopied)); } else if (currentAction == ACTION_PHONE_COPIED) { infoTextView.setText(LocaleController.getString("PhoneCopied", R.string.PhoneCopied)); } else if (currentAction == ACTION_USERNAME_COPIED) { infoTextView.setText(LocaleController.getString("UsernameCopied", R.string.UsernameCopied)); } else if (currentAction == ACTION_HASHTAG_COPIED) { infoTextView.setText(LocaleController.getString("HashtagCopied", R.string.HashtagCopied)); } else if (currentAction == ACTION_MESSAGE_COPIED) { infoTextView.setText(LocaleController.getString("MessageCopied", R.string.MessageCopied)); } else if (currentAction == ACTION_LINK_COPIED) { iconRawId = R.raw.voip_invite; infoTextView.setText(LocaleController.getString("LinkCopied", R.string.LinkCopied)); } else { infoTextView.setText(LocaleController.getString("TextCopied", R.string.TextCopied)); } leftImageView.setAnimation(iconRawId, 30, 30); timeLeft = 3000; infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); } else if (currentAction == ACTION_NOTIFY_ON) { infoTextView.setText(LocaleController.getString("ChannelNotifyMembersInfoOn", R.string.ChannelNotifyMembersInfoOn)); leftImageView.setAnimation(R.raw.silent_unmute, 30, 30); timeLeft = 3000; infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); } else if (currentAction == ACTION_NOTIFY_OFF) { infoTextView.setText(LocaleController.getString("ChannelNotifyMembersInfoOff", R.string.ChannelNotifyMembersInfoOff)); leftImageView.setAnimation(R.raw.silent_mute, 30, 30); timeLeft = 3000; infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); } else if (currentAction == ACTION_VOIP_INVITE_LINK_SENT) { if (infoObject2 == null) { if (did == UserConfig.getInstance(currentAccount).clientUserId) { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.getString("InvLinkToSavedMessages", R.string.InvLinkToSavedMessages))); } else { if (DialogObject.isChatDialog(did)) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-did); infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("InvLinkToGroup", R.string.InvLinkToGroup, chat.title))); } else { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(did); infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("InvLinkToUser", R.string.InvLinkToUser, UserObject.getFirstName(user)))); } } } else { int amount = (Integer) infoObject2; infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("InvLinkToChats", R.string.InvLinkToChats, LocaleController.formatPluralString("Chats", amount)))); } leftImageView.setAnimation(R.raw.contact_check, 36, 36); timeLeft = 3000; } else if (currentAction == ACTION_FWD_MESSAGES) { Integer count = (Integer) infoObject; if (infoObject2 == null || infoObject2 instanceof TLRPC.TL_forumTopic) { if (did == UserConfig.getInstance(currentAccount).clientUserId) { if (count == 1) { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.getString("FwdMessageToSavedMessages", R.string.FwdMessageToSavedMessages))); } else { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.getString("FwdMessagesToSavedMessages", R.string.FwdMessagesToSavedMessages))); } leftImageView.setAnimation(R.raw.saved_messages, 30, 30); } else { if (DialogObject.isChatDialog(did)) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-did); TLRPC.TL_forumTopic topic = (TLRPC.TL_forumTopic) infoObject2; if (count == 1) { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("FwdMessageToGroup", R.string.FwdMessageToGroup, topic != null ? topic.title : chat.title))); } else { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("FwdMessagesToGroup", R.string.FwdMessagesToGroup, topic != null ? topic.title : chat.title))); } } else { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(did); if (count == 1) { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("FwdMessageToUser", R.string.FwdMessageToUser, UserObject.getFirstName(user)))); } else { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("FwdMessagesToUser", R.string.FwdMessagesToUser, UserObject.getFirstName(user)))); } } leftImageView.setAnimation(R.raw.forward, 30, 30); hapticDelay = 300; } } else { int amount = (Integer) infoObject2; if (count == 1) { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatPluralString("FwdMessageToManyChats", amount))); } else { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatPluralString("FwdMessagesToManyChats", amount))); } leftImageView.setAnimation(R.raw.forward, 30, 30); hapticDelay = 300; } timeLeft = 3000; } else if (currentAction == ACTION_SHARE_BACKGROUND) { Integer count = (Integer) infoObject; if (infoObject2 == null) { if (did == UserConfig.getInstance(currentAccount).clientUserId) { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.getString("BackgroundToSavedMessages", R.string.BackgroundToSavedMessages))); leftImageView.setAnimation(R.raw.saved_messages, 30, 30); } else { if (DialogObject.isChatDialog(did)) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-did); infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("BackgroundToGroup", R.string.BackgroundToGroup, chat.title))); } else { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(did); infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("BackgroundToUser", R.string.BackgroundToUser, UserObject.getFirstName(user)))); } leftImageView.setAnimation(R.raw.forward, 30, 30); } } else { int amount = (Integer) infoObject2; infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("BackgroundToChats", R.string.BackgroundToChats, LocaleController.formatPluralString("Chats", amount)))); leftImageView.setAnimation(R.raw.forward, 30, 30); } timeLeft = 3000; } subinfoTextView.setVisibility(GONE); undoTextView.setTextColor(getThemedColor(Theme.key_undo_cancelColor)); undoButton.setVisibility(GONE); layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams.rightMargin = AndroidUtilities.dp(8); leftImageView.setProgress(0); leftImageView.playAnimation(); if (hapticDelay > 0) { leftImageView.postDelayed(() -> { leftImageView.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING); }, hapticDelay); } } else if (currentAction == ACTION_PROXIMITY_SET || currentAction == ACTION_PROXIMITY_REMOVED) { int radius = (Integer) infoObject; TLRPC.User user = (TLRPC.User) infoObject2; undoImageView.setVisibility(GONE); leftImageView.setVisibility(VISIBLE); if (radius != 0) { infoTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); leftImageView.clearLayerColors(); leftImageView.setLayerColor("BODY.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("Wibe Big.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("Wibe Big 3.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("Wibe Small.**", getThemedColor(Theme.key_undo_infoColor)); infoTextView.setText(LocaleController.getString("ProximityAlertSet", R.string.ProximityAlertSet)); leftImageView.setAnimation(R.raw.ic_unmute, 28, 28); subinfoTextView.setVisibility(VISIBLE); subinfoTextView.setSingleLine(false); subinfoTextView.setMaxLines(3); if (user != null) { subinfoTextView.setText(LocaleController.formatString("ProximityAlertSetInfoUser", R.string.ProximityAlertSetInfoUser, UserObject.getFirstName(user), LocaleController.formatDistance(radius, 2))); } else { subinfoTextView.setText(LocaleController.formatString("ProximityAlertSetInfoGroup2", R.string.ProximityAlertSetInfoGroup2, LocaleController.formatDistance(radius, 2))); } undoButton.setVisibility(GONE); layoutParams.topMargin = AndroidUtilities.dp(6); } else { infoTextView.setTypeface(Typeface.DEFAULT); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); leftImageView.clearLayerColors(); leftImageView.setLayerColor("Body Main.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("Body Top.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("Line.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("Curve Big.**", getThemedColor(Theme.key_undo_infoColor)); leftImageView.setLayerColor("Curve Small.**", getThemedColor(Theme.key_undo_infoColor)); layoutParams.topMargin = AndroidUtilities.dp(14); infoTextView.setText(LocaleController.getString("ProximityAlertCancelled", R.string.ProximityAlertCancelled)); leftImageView.setAnimation(R.raw.ic_mute, 28, 28); subinfoTextView.setVisibility(GONE); undoTextView.setTextColor(getThemedColor(Theme.key_undo_cancelColor)); undoButton.setVisibility(VISIBLE); } layoutParams.leftMargin = AndroidUtilities.dp(58); leftImageView.setProgress(0); leftImageView.playAnimation(); } else if (currentAction == ACTION_QR_SESSION_ACCEPTED) { TLRPC.TL_authorization authorization = (TLRPC.TL_authorization) infoObject; infoTextView.setText(LocaleController.getString("AuthAnotherClientOk", R.string.AuthAnotherClientOk)); leftImageView.setAnimation(R.raw.contact_check, 36, 36); layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams.topMargin = AndroidUtilities.dp(6); subinfoTextView.setText(authorization.app_name); subinfoTextView.setVisibility(VISIBLE); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); infoTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); undoTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteRedText2)); undoImageView.setVisibility(GONE); undoButton.setVisibility(VISIBLE); leftImageView.setVisibility(VISIBLE); leftImageView.setProgress(0); leftImageView.playAnimation(); } else if (currentAction == ACTION_FILTERS_AVAILABLE) { timeLeft = 10000; undoTextView.setText(LocaleController.getString("Open", R.string.Open)); infoTextView.setText(LocaleController.getString("FilterAvailableTitle", R.string.FilterAvailableTitle)); leftImageView.setAnimation(R.raw.filter_new, 36, 36); int margin = (int) Math.ceil(undoTextView.getPaint().measureText(undoTextView.getText().toString())) + AndroidUtilities.dp(26); layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams.rightMargin = margin; layoutParams.topMargin = AndroidUtilities.dp(6); layoutParams = (FrameLayout.LayoutParams) subinfoTextView.getLayoutParams(); layoutParams.rightMargin = margin; String text = LocaleController.getString("FilterAvailableText", R.string.FilterAvailableText); SpannableStringBuilder builder = new SpannableStringBuilder(text); int index1 = text.indexOf('*'); int index2 = text.lastIndexOf('*'); if (index1 >= 0 && index2 >= 0 && index1 != index2) { builder.replace(index2, index2 + 1, ""); builder.replace(index1, index1 + 1, ""); builder.setSpan(new URLSpanNoUnderline("tg://settings/folders"), index1, index2 - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } subinfoTextView.setText(builder); subinfoTextView.setVisibility(VISIBLE); subinfoTextView.setSingleLine(false); subinfoTextView.setMaxLines(2); undoButton.setVisibility(VISIBLE); undoImageView.setVisibility(GONE); leftImageView.setVisibility(VISIBLE); leftImageView.setProgress(0); leftImageView.playAnimation(); } else if (currentAction == ACTION_DICE_INFO || currentAction == ACTION_DICE_NO_SEND_INFO) { timeLeft = 4000; infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); infoTextView.setGravity(Gravity.CENTER_VERTICAL); infoTextView.setMinHeight(AndroidUtilities.dp(30)); String emoji = (String) infoObject; if ("\uD83C\uDFB2".equals(emoji)) { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.getString("DiceInfo2", R.string.DiceInfo2))); leftImageView.setImageResource(R.drawable.dice); } else { if ("\uD83C\uDFAF".equals(emoji)) { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.getString("DartInfo", R.string.DartInfo))); } else { String info = LocaleController.getServerString("DiceEmojiInfo_" + emoji); if (!TextUtils.isEmpty(info)) { infoTextView.setText(Emoji.replaceEmoji(info, infoTextView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(14), false)); } else { infoTextView.setText(Emoji.replaceEmoji(LocaleController.formatString("DiceEmojiInfo", R.string.DiceEmojiInfo, emoji), infoTextView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(14), false)); } } leftImageView.setImageDrawable(Emoji.getEmojiDrawable(emoji)); leftImageView.setScaleType(ImageView.ScaleType.FIT_XY); layoutParams.topMargin = AndroidUtilities.dp(14); layoutParams.bottomMargin = AndroidUtilities.dp(14); layoutParams2.leftMargin = AndroidUtilities.dp(14); layoutParams2.width = AndroidUtilities.dp(26); layoutParams2.height = AndroidUtilities.dp(26); } undoTextView.setText(LocaleController.getString("SendDice", R.string.SendDice)); int margin; if (currentAction == ACTION_DICE_INFO) { margin = (int) Math.ceil(undoTextView.getPaint().measureText(undoTextView.getText().toString())) + AndroidUtilities.dp(26); undoTextView.setVisibility(VISIBLE); undoTextView.setTextColor(getThemedColor(Theme.key_undo_cancelColor)); undoImageView.setVisibility(GONE); undoButton.setVisibility(VISIBLE); } else { margin = AndroidUtilities.dp(8); undoTextView.setVisibility(GONE); undoButton.setVisibility(GONE); } layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams.rightMargin = margin; layoutParams.topMargin = AndroidUtilities.dp(6); layoutParams.bottomMargin = AndroidUtilities.dp(7); layoutParams.height = TableLayout.LayoutParams.MATCH_PARENT; subinfoTextView.setVisibility(GONE); leftImageView.setVisibility(VISIBLE); } else if (currentAction == ACTION_TEXT_INFO) { CharSequence info = (CharSequence) infoObject; timeLeft = Math.max(4000, Math.min(info.length() / 50 * 1600, 10000)); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); infoTextView.setGravity(Gravity.CENTER_VERTICAL); infoTextView.setText(info); undoTextView.setVisibility(GONE); undoButton.setVisibility(GONE); layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams.rightMargin = AndroidUtilities.dp(8); layoutParams.topMargin = AndroidUtilities.dp(6); layoutParams.bottomMargin = AndroidUtilities.dp(7); layoutParams.height = TableLayout.LayoutParams.MATCH_PARENT; layoutParams2.gravity = Gravity.TOP | Gravity.LEFT; layoutParams2.topMargin = layoutParams2.bottomMargin = AndroidUtilities.dp(8); leftImageView.setVisibility(VISIBLE); leftImageView.setAnimation(R.raw.chats_infotip, 36, 36); leftImageView.setProgress(0); leftImageView.playAnimation(); infoTextView.setMovementMethod(new AndroidUtilities.LinkMovementMethodMy()); } else if (currentAction == ACTION_THEME_CHANGED) { infoTextView.setText(LocaleController.getString("ColorThemeChanged", R.string.ColorThemeChanged)); leftImageView.setImageResource(R.drawable.toast_pallete); layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams.rightMargin = AndroidUtilities.dp(48); layoutParams.topMargin = AndroidUtilities.dp(6); layoutParams = (FrameLayout.LayoutParams) subinfoTextView.getLayoutParams(); layoutParams.rightMargin = AndroidUtilities.dp(48); String text = LocaleController.getString("ColorThemeChangedInfo", R.string.ColorThemeChangedInfo); SpannableStringBuilder builder = new SpannableStringBuilder(text); int index1 = text.indexOf('*'); int index2 = text.lastIndexOf('*'); if (index1 >= 0 && index2 >= 0 && index1 != index2) { builder.replace(index2, index2 + 1, ""); builder.replace(index1, index1 + 1, ""); builder.setSpan(new URLSpanNoUnderline("tg://settings/themes"), index1, index2 - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } subinfoTextView.setText(builder); subinfoTextView.setVisibility(VISIBLE); subinfoTextView.setSingleLine(false); subinfoTextView.setMaxLines(2); undoTextView.setVisibility(GONE); undoButton.setVisibility(VISIBLE); leftImageView.setVisibility(VISIBLE); } else if (currentAction == ACTION_PREMIUM_TRANSCRIPTION) { infoTextView.setVisibility(VISIBLE); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); infoTextView.setTypeface(Typeface.DEFAULT); infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.getString("UnlockPremiumTranscriptionHint", R.string.UnlockPremiumTranscriptionHint))); leftImageView.setVisibility(VISIBLE); leftImageView.setAnimation(R.raw.voice_to_text, 36, 36); leftImageView.setProgress(0); leftImageView.playAnimation(); undoTextView.setText(LocaleController.getString("PremiumMore", R.string.PremiumMore)); layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams.rightMargin = (int) Math.ceil(undoTextView.getPaint().measureText(undoTextView.getText().toString())) + AndroidUtilities.dp(26); layoutParams.topMargin = layoutParams.bottomMargin = AndroidUtilities.dp(6); layoutParams.height = TableLayout.LayoutParams.WRAP_CONTENT; avatarImageView.setVisibility(GONE); subinfoTextView.setVisibility(GONE); undoTextView.setVisibility(VISIBLE); undoButton.setVisibility(VISIBLE); undoImageView.setVisibility(GONE); } else if (currentAction == ACTION_HINT_SWIPE_TO_REPLY) { infoTextView.setVisibility(VISIBLE); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); infoTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); infoTextView.setText(LocaleController.getString("SwipeToReplyHint", R.string.SwipeToReplyHint)); leftImageView.setVisibility(VISIBLE); leftImageView.setAnimation(R.raw.hint_swipe_reply, (int) (36 * 1.8f), (int) (36 * 1.8f)); leftImageView.setProgress(0); leftImageView.playAnimation(); subinfoTextView.setVisibility(VISIBLE); subinfoTextView.setText(LocaleController.getString("SwipeToReplyHintMessage", R.string.SwipeToReplyHintMessage)); layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams.rightMargin = (int) Math.ceil(undoTextView.getPaint().measureText(undoTextView.getText().toString())) + AndroidUtilities.dp(26); layoutParams.topMargin = AndroidUtilities.dp(6); layoutParams.height = TableLayout.LayoutParams.WRAP_CONTENT; avatarImageView.setVisibility(GONE); undoButton.setVisibility(GONE); } else if (currentAction == ACTION_ARCHIVE || currentAction == ACTION_ARCHIVE_FEW) { if (action == ACTION_ARCHIVE) { infoTextView.setText(LocaleController.getString("ChatArchived", R.string.ChatArchived)); } else { infoTextView.setText(LocaleController.getString("ChatsArchived", R.string.ChatsArchived)); } layoutParams.leftMargin = AndroidUtilities.dp(58); layoutParams.topMargin = AndroidUtilities.dp(13); layoutParams.rightMargin = 0; infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); undoButton.setVisibility(VISIBLE); infoTextView.setTypeface(Typeface.DEFAULT); subinfoTextView.setVisibility(GONE); leftImageView.setVisibility(VISIBLE); leftImageView.setAnimation(R.raw.chats_archived, 36, 36); leftImageView.setProgress(0); leftImageView.playAnimation(); } else if (action == ACTION_PREVIEW_MEDIA_DESELECTED) { layoutParams.leftMargin = AndroidUtilities.dp(58); MediaController.PhotoEntry photoEntry = (MediaController.PhotoEntry) infoObject; infoTextView.setText(photoEntry.isVideo ? LocaleController.getString("AttachMediaVideoDeselected", R.string.AttachMediaVideoDeselected) : LocaleController.getString("AttachMediaPhotoDeselected", R.string.AttachMediaPhotoDeselected)); undoButton.setVisibility(VISIBLE); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); infoTextView.setTypeface(Typeface.DEFAULT); subinfoTextView.setVisibility(GONE); avatarImageView.setVisibility(VISIBLE); avatarImageView.setRoundRadius(AndroidUtilities.dp(2)); if (photoEntry.thumbPath != null) { avatarImageView.setImage(photoEntry.thumbPath, null, Theme.chat_attachEmptyDrawable); } else if (photoEntry.path != null) { avatarImageView.setOrientation(photoEntry.orientation, true); if (photoEntry.isVideo) { avatarImageView.setImage("vthumb://" + photoEntry.imageId + ":" + photoEntry.path, null, Theme.chat_attachEmptyDrawable); } else { avatarImageView.setImage("thumb://" + photoEntry.imageId + ":" + photoEntry.path, null, Theme.chat_attachEmptyDrawable); } } else { avatarImageView.setImageDrawable(Theme.chat_attachEmptyDrawable); } } else { layoutParams.leftMargin = AndroidUtilities.dp(45); layoutParams.topMargin = AndroidUtilities.dp(13); layoutParams.rightMargin = 0; infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); undoButton.setVisibility(VISIBLE); infoTextView.setTypeface(Typeface.DEFAULT); subinfoTextView.setVisibility(GONE); leftImageView.setVisibility(GONE); if (currentAction == ACTION_CLEAR_DATES || currentAction == ACTION_CLEAR || currentAction == ACTION_CLEAR_FEW) { infoTextView.setText(LocaleController.getString("HistoryClearedUndo", R.string.HistoryClearedUndo)); } else if (currentAction == ACTION_DELETE_FEW) { infoTextView.setText(LocaleController.getString("ChatsDeletedUndo", R.string.ChatsDeletedUndo)); } else { if (DialogObject.isChatDialog(did)) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-did); if (ChatObject.isChannel(chat) && !chat.megagroup) { infoTextView.setText(LocaleController.getString("ChannelDeletedUndo", R.string.ChannelDeletedUndo)); } else { infoTextView.setText(LocaleController.getString("GroupDeletedUndo", R.string.GroupDeletedUndo)); } } else { infoTextView.setText(LocaleController.getString("ChatDeletedUndo", R.string.ChatDeletedUndo)); } } if (currentAction != ACTION_CLEAR_DATES) { for (int a = 0; a < dialogIds.size(); a++) { MessagesController.getInstance(currentAccount).addDialogAction(dialogIds.get(a), currentAction == ACTION_CLEAR || currentAction == ACTION_CLEAR_FEW); } } } AndroidUtilities.makeAccessibilityAnnouncement(infoTextView.getText() + (subinfoTextView.getVisibility() == VISIBLE ? ". " + subinfoTextView.getText() : "")); if (isMultilineSubInfo()) { ViewGroup parent = (ViewGroup) getParent(); int width = parent.getMeasuredWidth(); if (width == 0) { width = AndroidUtilities.displaySize.x; } width -= AndroidUtilities.dp(16); measureChildWithMargins(subinfoTextView, MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), 0, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 0); undoViewHeight = subinfoTextView.getMeasuredHeight() + AndroidUtilities.dp(27 + 10); } else if (hasSubInfo()) { undoViewHeight = AndroidUtilities.dp(52); } else if (getParent() instanceof ViewGroup) { ViewGroup parent = (ViewGroup) getParent(); int width = parent.getMeasuredWidth() - parent.getPaddingLeft() - parent.getPaddingRight(); if (width <= 0) { width = AndroidUtilities.displaySize.x; } width -= AndroidUtilities.dp(16); measureChildWithMargins(infoTextView, MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), 0, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 0); undoViewHeight = infoTextView.getMeasuredHeight() + AndroidUtilities.dp(currentAction == ACTION_DICE_INFO || currentAction == ACTION_DICE_NO_SEND_INFO || currentAction == ACTION_TEXT_INFO || currentAction == ACTION_PREMIUM_TRANSCRIPTION || currentAction == ACTION_PREMIUM_ALL_FOLDER ? 14 : 28); if (currentAction == ACTION_TEXT_INFO) { undoViewHeight = Math.max(undoViewHeight, AndroidUtilities.dp(52)); } else if (currentAction == ACTION_PROXIMITY_REMOVED) { undoViewHeight = Math.max(undoViewHeight, AndroidUtilities.dp(50)); } else if (infoOnly) { undoViewHeight -= AndroidUtilities.dp(8); } } if (getVisibility() != VISIBLE) { setVisibility(VISIBLE); setEnterOffset((fromTop ? -1.0f : 1.0f) * (enterOffsetMargin + undoViewHeight)); AnimatorSet animatorSet = new AnimatorSet(); animatorSet.playTogether(ObjectAnimator.ofFloat(this, "enterOffset", (fromTop ? -1.0f : 1.0f) * (enterOffsetMargin + undoViewHeight), (fromTop ? 1.0f : -1.0f))); animatorSet.setInterpolator(new DecelerateInterpolator()); animatorSet.setDuration(180); animatorSet.start(); } } private int enterOffsetMargin = AndroidUtilities.dp(8); public void setEnterOffsetMargin(int enterOffsetMargin) { this.enterOffsetMargin = enterOffsetMargin; } protected boolean canUndo() { return true; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(undoViewHeight, MeasureSpec.EXACTLY)); backgroundDrawable.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight()); } StaticLayout timeLayout; StaticLayout timeLayoutOut; int textWidthOut; float timeReplaceProgress = 1f; @Override protected void dispatchDraw(Canvas canvas) { if (additionalTranslationY != 0) { canvas.save(); float bottom = getMeasuredHeight() - enterOffset + AndroidUtilities.dp(9); if (bottom > 0) { canvas.clipRect(0, 0, getMeasuredWidth(), bottom); super.dispatchDraw(canvas); } canvas.restore(); } else { super.dispatchDraw(canvas); } } @Override protected void onDraw(Canvas canvas) { if (additionalTranslationY != 0) { canvas.save(); float bottom = getMeasuredHeight() - enterOffset + enterOffsetMargin + AndroidUtilities.dp(1); if (bottom > 0) { canvas.clipRect(0, 0, getMeasuredWidth(), bottom); super.dispatchDraw(canvas); } backgroundDrawable.draw(canvas); canvas.restore(); } else { backgroundDrawable.draw(canvas); } if (currentAction == ACTION_DELETE || currentAction == ACTION_CLEAR || currentAction == ACTION_DELETE_FEW || currentAction == ACTION_CLEAR_FEW || currentAction == ACTION_CLEAR_DATES) { int newSeconds = timeLeft > 0 ? (int) Math.ceil(timeLeft / 1000.0f) : 0; if (prevSeconds != newSeconds) { prevSeconds = newSeconds; timeLeftString = String.format("%d", Math.max(1, newSeconds)); if (timeLayout != null) { timeLayoutOut = timeLayout; timeReplaceProgress = 0; textWidthOut = textWidth; } textWidth = (int) Math.ceil(textPaint.measureText(timeLeftString)); timeLayout = new StaticLayout(timeLeftString, textPaint, Integer.MAX_VALUE, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); } if (timeReplaceProgress < 1f) { timeReplaceProgress += 16f / 150f; if (timeReplaceProgress > 1f) { timeReplaceProgress = 1f; } else { invalidate(); } } int alpha = textPaint.getAlpha(); if (timeLayoutOut != null && timeReplaceProgress < 1f) { textPaint.setAlpha((int) (alpha * (1f - timeReplaceProgress))); canvas.save(); canvas.translate(rect.centerX() - textWidth / 2, AndroidUtilities.dp(17.2f) + AndroidUtilities.dp(10) * timeReplaceProgress); timeLayoutOut.draw(canvas); textPaint.setAlpha(alpha); canvas.restore(); } if (timeLayout != null) { if (timeReplaceProgress != 1f) { textPaint.setAlpha((int) (alpha * timeReplaceProgress)); } canvas.save(); canvas.translate(rect.centerX() - textWidth / 2, AndroidUtilities.dp(17.2f) - AndroidUtilities.dp(10) * (1f - timeReplaceProgress)); timeLayout.draw(canvas); if (timeReplaceProgress != 1f) { textPaint.setAlpha(alpha); } canvas.restore(); } // canvas.drawText(timeLeftString, rect.centerX() - textWidth / 2, AndroidUtilities.dp(28.2f), textPaint); // canvas.drawText(timeLeftString, , textPaint); canvas.drawArc(rect, -90, -360 * (timeLeft / 5000.0f), false, progressPaint); } long newTime = SystemClock.elapsedRealtime(); long dt = newTime - lastUpdateTime; timeLeft -= dt; lastUpdateTime = newTime; if (timeLeft <= 0) { hide(true, hideAnimationType); } if (currentAction != ACTION_PREVIEW_MEDIA_DESELECTED) { invalidate(); } } @Override public void invalidate() { super.invalidate(); infoTextView.invalidate(); leftImageView.invalidate(); } public void setInfoText(CharSequence text) { infoText = text; } public void setHideAnimationType(int hideAnimationType) { this.hideAnimationType = hideAnimationType; } float enterOffset; @Keep public float getEnterOffset() { return enterOffset; } @Keep public void setEnterOffset(float enterOffset) { if (this.enterOffset != enterOffset) { this.enterOffset = enterOffset; updatePosition(); } } private void updatePosition() { setTranslationY(enterOffset - enterOffsetMargin + AndroidUtilities.dp(8) - additionalTranslationY); invalidate(); } @Override public Drawable getBackground() { return backgroundDrawable; } private int getThemedColor(String key) { Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; return color != null ? color : Theme.getColor(key); } }
dawitys/Telegram
TMessagesProj/src/main/java/org/telegram/ui/Components/UndoView.java
41,711
/* * 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-2018. */ package org.telegram.ui; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Outline; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.os.Build; import android.text.InputFilter; import android.text.TextPaint; import android.util.TypedValue; import android.view.Gravity; import android.view.HapticFeedbackConstants; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.Surface; import android.view.View; import android.view.ViewGroup; import android.view.ViewOutlineProvider; import android.view.ViewTreeObserver; import android.view.WindowManager; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MediaController; import org.telegram.messenger.MessagesController; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.SendMessagesHelper; import org.telegram.messenger.SharedConfig; import org.telegram.messenger.UserConfig; import org.telegram.messenger.UserObject; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.ActionBar; import org.telegram.ui.ActionBar.ActionBarMenu; import org.telegram.ui.ActionBar.ActionBarMenuItem; import org.telegram.ui.ActionBar.ActionBarMenuSubItem; import org.telegram.ui.ActionBar.ActionBarPopupWindow; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.ThemeDescription; import org.telegram.ui.Cells.PhotoPickerAlbumsCell; import org.telegram.ui.Components.AlertsCreator; import org.telegram.ui.Components.CombinedDrawable; import org.telegram.ui.Components.EditTextBoldCursor; import org.telegram.ui.Components.EditTextEmoji; import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.RadialProgressView; import org.telegram.ui.Components.RecyclerListView; import org.telegram.ui.Components.SizeNotifierFrameLayout; import java.util.ArrayList; import java.util.HashMap; public class PhotoAlbumPickerActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate { public interface PhotoAlbumPickerActivityDelegate { void didSelectPhotos(ArrayList<SendMessagesHelper.SendingMediaInfo> photos, boolean notify, int scheduleDate); void startPhotoSelectActivity(); } private CharSequence caption; private HashMap<Object, Object> selectedPhotos = new HashMap<>(); private ArrayList<Object> selectedPhotosOrder = new ArrayList<>(); private ArrayList<MediaController.AlbumEntry> albumsSorted = null; private boolean loading = false; private int columnsCount = 2; private RecyclerListView listView; private ListAdapter listAdapter; private FrameLayout progressView; private TextView emptyView; private boolean sendPressed; private int selectPhotoType; private boolean allowSearchImages = true; private boolean allowGifs; private boolean allowCaption; private ChatActivity chatActivity; private int maxSelectedPhotos; private boolean allowOrder = true; private ActionBarPopupWindow sendPopupWindow; private ActionBarPopupWindow.ActionBarPopupWindowLayout sendPopupLayout; private ActionBarMenuSubItem[] itemCells; private FrameLayout frameLayout2; private EditTextEmoji commentTextView; private FrameLayout writeButtonContainer; private ImageView writeButton; private Drawable writeButtonDrawable; private SizeNotifierFrameLayout sizeNotifierFrameLayout; private View selectedCountView; private View shadow; private TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); private RectF rect = new RectF(); private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); private PhotoAlbumPickerActivityDelegate delegate; public static int SELECT_TYPE_ALL = 0; public static int SELECT_TYPE_AVATAR = 1; public static int SELECT_TYPE_WALLPAPER = 2; public static int SELECT_TYPE_AVATAR_VIDEO = 3; public static int SELECT_TYPE_QR = 10; public PhotoAlbumPickerActivity(int selectPhotoType, boolean allowGifs, boolean allowCaption, ChatActivity chatActivity) { super(); this.chatActivity = chatActivity; this.selectPhotoType = selectPhotoType; this.allowGifs = allowGifs; this.allowCaption = allowCaption; } @Override public boolean onFragmentCreate() { if (selectPhotoType == SELECT_TYPE_AVATAR || selectPhotoType == SELECT_TYPE_WALLPAPER || selectPhotoType == SELECT_TYPE_QR || !allowSearchImages) { albumsSorted = MediaController.allPhotoAlbums; } else { albumsSorted = MediaController.allMediaAlbums; } loading = albumsSorted == null; MediaController.loadGalleryPhotosAlbums(classGuid); NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.albumsDidLoad); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.closeChats); return super.onFragmentCreate(); } @Override public void onFragmentDestroy() { if (commentTextView != null) { commentTextView.onDestroy(); } NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.albumsDidLoad); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.closeChats); super.onFragmentDestroy(); } @Override public View createView(Context context) { actionBar.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground)); actionBar.setTitleColor(Theme.getColor(Theme.key_dialogTextBlack)); actionBar.setItemsColor(Theme.getColor(Theme.key_dialogTextBlack), false); actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_dialogButtonSelector), false); actionBar.setBackButtonImage(R.drawable.ic_ab_back); actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override public void onItemClick(int id) { if (id == -1) { finishFragment(); } else if (id == 1) { if (delegate != null) { finishFragment(false); delegate.startPhotoSelectActivity(); } } else if (id == 2) { openPhotoPicker(null, 0); } } }); ActionBarMenu menu = actionBar.createMenu(); if (allowSearchImages) { menu.addItem(2, R.drawable.ic_ab_search).setContentDescription(LocaleController.getString("Search", R.string.Search)); } ActionBarMenuItem menuItem = menu.addItem(0, R.drawable.ic_ab_other); menuItem.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions)); menuItem.addSubItem(1, R.drawable.msg_openin, LocaleController.getString("OpenInExternalApp", R.string.OpenInExternalApp)); sizeNotifierFrameLayout = new SizeNotifierFrameLayout(context) { private int lastNotifyWidth; private boolean ignoreLayout; @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); setMeasuredDimension(widthSize, heightSize); int keyboardSize = SharedConfig.smoothKeyboard ? 0 : measureKeyboardHeight(); if (keyboardSize <= AndroidUtilities.dp(20)) { if (!AndroidUtilities.isInMultiwindow) { heightSize -= commentTextView.getEmojiPadding(); heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY); } } else { ignoreLayout = true; commentTextView.hideEmojiView(); ignoreLayout = false; } int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); if (child == null || child.getVisibility() == GONE) { continue; } if (commentTextView != null && commentTextView.isPopupView(child)) { if (AndroidUtilities.isInMultiwindow || AndroidUtilities.isTablet()) { if (AndroidUtilities.isTablet()) { child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(Math.min(AndroidUtilities.dp(AndroidUtilities.isTablet() ? 200 : 320), heightSize - AndroidUtilities.statusBarHeight + getPaddingTop()), MeasureSpec.EXACTLY)); } else { child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSize - AndroidUtilities.statusBarHeight + getPaddingTop(), MeasureSpec.EXACTLY)); } } else { child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(child.getLayoutParams().height, MeasureSpec.EXACTLY)); } } else { measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0); } } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { if (lastNotifyWidth != r - l) { lastNotifyWidth = r - l; if (sendPopupWindow != null && sendPopupWindow.isShowing()) { sendPopupWindow.dismiss(); } } final int count = getChildCount(); int keyboardSize = SharedConfig.smoothKeyboard ? 0 : measureKeyboardHeight(); int paddingBottom = keyboardSize <= AndroidUtilities.dp(20) && !AndroidUtilities.isInMultiwindow && !AndroidUtilities.isTablet() ? commentTextView.getEmojiPadding() : 0; setBottomClip(paddingBottom); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int width = child.getMeasuredWidth(); final int height = child.getMeasuredHeight(); int childLeft; int childTop; int gravity = lp.gravity; if (gravity == -1) { gravity = Gravity.TOP | Gravity.LEFT; } final int absoluteGravity = gravity & Gravity.HORIZONTAL_GRAVITY_MASK; final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK; switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { case Gravity.CENTER_HORIZONTAL: childLeft = (r - l - width) / 2 + lp.leftMargin - lp.rightMargin; break; case Gravity.RIGHT: childLeft = (r - l) - width - lp.rightMargin - getPaddingRight(); break; case Gravity.LEFT: default: childLeft = lp.leftMargin + getPaddingLeft(); } switch (verticalGravity) { case Gravity.TOP: childTop = lp.topMargin + getPaddingTop(); break; case Gravity.CENTER_VERTICAL: childTop = ((b - paddingBottom) - t - height) / 2 + lp.topMargin - lp.bottomMargin; break; case Gravity.BOTTOM: childTop = ((b - paddingBottom) - t) - height - lp.bottomMargin; break; default: childTop = lp.topMargin; } if (commentTextView != null && commentTextView.isPopupView(child)) { if (AndroidUtilities.isTablet()) { childTop = getMeasuredHeight() - child.getMeasuredHeight(); } else { childTop = getMeasuredHeight() + keyboardSize - child.getMeasuredHeight(); } } child.layout(childLeft, childTop, childLeft + width, childTop + height); } notifyHeightChanged(); } @Override public void requestLayout() { if (ignoreLayout) { return; } super.requestLayout(); } }; sizeNotifierFrameLayout.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground)); fragmentView = sizeNotifierFrameLayout; actionBar.setTitle(LocaleController.getString("Gallery", R.string.Gallery)); listView = new RecyclerListView(context); listView.setPadding(AndroidUtilities.dp(6), AndroidUtilities.dp(4), AndroidUtilities.dp(6), AndroidUtilities.dp(54)); listView.setClipToPadding(false); listView.setHorizontalScrollBarEnabled(false); listView.setVerticalScrollBarEnabled(false); listView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)); listView.setDrawingCacheEnabled(false); sizeNotifierFrameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP)); listView.setAdapter(listAdapter = new ListAdapter(context)); listView.setGlowColor(Theme.getColor(Theme.key_dialogBackground)); emptyView = new TextView(context); emptyView.setTextColor(0xff808080); emptyView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); emptyView.setGravity(Gravity.CENTER); emptyView.setVisibility(View.GONE); emptyView.setText(LocaleController.getString("NoPhotos", R.string.NoPhotos)); sizeNotifierFrameLayout.addView(emptyView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 0, 0, 48)); emptyView.setOnTouchListener((v, event) -> true); progressView = new FrameLayout(context); progressView.setVisibility(View.GONE); sizeNotifierFrameLayout.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 0, 0, 48)); RadialProgressView progressBar = new RadialProgressView(context); progressBar.setProgressColor(0xff527da3); progressView.addView(progressBar, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER)); shadow = new View(context); shadow.setBackgroundResource(R.drawable.header_shadow_reverse); shadow.setTranslationY(AndroidUtilities.dp(48)); sizeNotifierFrameLayout.addView(shadow, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 0, 48)); frameLayout2 = new FrameLayout(context); frameLayout2.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground)); frameLayout2.setVisibility(View.INVISIBLE); frameLayout2.setTranslationY(AndroidUtilities.dp(48)); sizeNotifierFrameLayout.addView(frameLayout2, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.BOTTOM)); frameLayout2.setOnTouchListener((v, event) -> true); if (commentTextView != null) { commentTextView.onDestroy(); } commentTextView = new EditTextEmoji(context, sizeNotifierFrameLayout, null, EditTextEmoji.STYLE_DIALOG, false); InputFilter[] inputFilters = new InputFilter[1]; inputFilters[0] = new InputFilter.LengthFilter(MessagesController.getInstance(UserConfig.selectedAccount).maxCaptionLength); commentTextView.setFilters(inputFilters); commentTextView.setHint(LocaleController.getString("AddCaption", R.string.AddCaption)); EditTextBoldCursor editText = commentTextView.getEditText(); editText.setMaxLines(1); editText.setSingleLine(true); frameLayout2.addView(commentTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 0, 0, 84, 0)); if (caption != null) { commentTextView.setText(caption); } writeButtonContainer = new FrameLayout(context) { @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setText(LocaleController.formatPluralString("AccDescrSendPhotos", selectedPhotos.size())); info.setClassName(Button.class.getName()); info.setLongClickable(true); info.setClickable(true); } }; writeButtonContainer.setFocusable(true); writeButtonContainer.setFocusableInTouchMode(true); writeButtonContainer.setVisibility(View.INVISIBLE); writeButtonContainer.setScaleX(0.2f); writeButtonContainer.setScaleY(0.2f); writeButtonContainer.setAlpha(0.0f); sizeNotifierFrameLayout.addView(writeButtonContainer, LayoutHelper.createFrame(60, 60, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 12, 10)); writeButton = new ImageView(context); writeButtonDrawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56), Theme.getColor(Theme.key_dialogFloatingButton), Theme.getColor(Build.VERSION.SDK_INT >= 21 ? Theme.key_dialogFloatingButtonPressed : Theme.key_dialogFloatingButton)); if (Build.VERSION.SDK_INT < 21) { Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile).mutate(); shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY)); CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, writeButtonDrawable, 0, 0); combinedDrawable.setIconSize(AndroidUtilities.dp(56), AndroidUtilities.dp(56)); writeButtonDrawable = combinedDrawable; } writeButton.setBackgroundDrawable(writeButtonDrawable); writeButton.setImageResource(R.drawable.attach_send); writeButton.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); writeButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingIcon), PorterDuff.Mode.MULTIPLY)); writeButton.setScaleType(ImageView.ScaleType.CENTER); if (Build.VERSION.SDK_INT >= 21) { writeButton.setOutlineProvider(new ViewOutlineProvider() { @SuppressLint("NewApi") @Override public void getOutline(View view, Outline outline) { outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56)); } }); } writeButtonContainer.addView(writeButton, LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 56 : 60, Build.VERSION.SDK_INT >= 21 ? 56 : 60, Gravity.LEFT | Gravity.TOP, Build.VERSION.SDK_INT >= 21 ? 2 : 0, 0, 0, 0)); writeButton.setOnClickListener(v -> { if (chatActivity != null && chatActivity.isInScheduleMode()) { AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), chatActivity.getDialogId(), (notify, scheduleDate) -> { sendSelectedPhotos(selectedPhotos, selectedPhotosOrder, notify, scheduleDate); finishFragment(); }); } else { sendSelectedPhotos(selectedPhotos, selectedPhotosOrder, true, 0); finishFragment(); } }); writeButton.setOnLongClickListener(view -> { if (chatActivity == null || maxSelectedPhotos == 1) { return false; } TLRPC.Chat chat = chatActivity.getCurrentChat(); TLRPC.User user = chatActivity.getCurrentUser(); if (sendPopupLayout == null) { sendPopupLayout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(getParentActivity()); sendPopupLayout.setAnimationEnabled(false); sendPopupLayout.setOnTouchListener(new View.OnTouchListener() { private android.graphics.Rect popupRect = new android.graphics.Rect(); @Override public boolean onTouch(View v, MotionEvent event) { if (event.getActionMasked() == MotionEvent.ACTION_DOWN) { if (sendPopupWindow != null && sendPopupWindow.isShowing()) { v.getHitRect(popupRect); if (!popupRect.contains((int) event.getX(), (int) event.getY())) { sendPopupWindow.dismiss(); } } } return false; } }); sendPopupLayout.setDispatchKeyEventListener(keyEvent -> { if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_BACK && keyEvent.getRepeatCount() == 0 && sendPopupWindow != null && sendPopupWindow.isShowing()) { sendPopupWindow.dismiss(); } }); sendPopupLayout.setShownFromBottom(false); itemCells = new ActionBarMenuSubItem[2]; for (int a = 0; a < 2; a++) { if (a == 0 && !chatActivity.canScheduleMessage() || a == 1 && UserObject.isUserSelf(user)) { continue; } int num = a; itemCells[a] = new ActionBarMenuSubItem(getParentActivity(), a == 0, a == 1); if (num == 0) { if (UserObject.isUserSelf(user)) { itemCells[a].setTextAndIcon(LocaleController.getString("SetReminder", R.string.SetReminder), R.drawable.msg_calendar2); } else { itemCells[a].setTextAndIcon(LocaleController.getString("ScheduleMessage", R.string.ScheduleMessage), R.drawable.msg_calendar2); } } else { itemCells[a].setTextAndIcon(LocaleController.getString("SendWithoutSound", R.string.SendWithoutSound), R.drawable.input_notify_off); } itemCells[a].setMinimumWidth(AndroidUtilities.dp(196)); sendPopupLayout.addView(itemCells[a], LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48)); itemCells[a].setOnClickListener(v -> { if (sendPopupWindow != null && sendPopupWindow.isShowing()) { sendPopupWindow.dismiss(); } if (num == 0) { AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), chatActivity.getDialogId(), (notify, scheduleDate) -> { sendSelectedPhotos(selectedPhotos, selectedPhotosOrder, notify, scheduleDate); finishFragment(); }); } else { sendSelectedPhotos(selectedPhotos, selectedPhotosOrder, true, 0); finishFragment(); } }); } sendPopupLayout.setupRadialSelectors(Theme.getColor(Theme.key_dialogButtonSelector)); sendPopupWindow = new ActionBarPopupWindow(sendPopupLayout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT); sendPopupWindow.setAnimationEnabled(false); sendPopupWindow.setAnimationStyle(R.style.PopupContextAnimation2); sendPopupWindow.setOutsideTouchable(true); sendPopupWindow.setClippingEnabled(true); sendPopupWindow.setInputMethodMode(ActionBarPopupWindow.INPUT_METHOD_NOT_NEEDED); sendPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED); sendPopupWindow.getContentView().setFocusableInTouchMode(true); } sendPopupLayout.measure(View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST)); sendPopupWindow.setFocusable(true); int[] location = new int[2]; view.getLocationInWindow(location); sendPopupWindow.showAtLocation(view, Gravity.LEFT | Gravity.TOP, location[0] + view.getMeasuredWidth() - sendPopupLayout.getMeasuredWidth() + AndroidUtilities.dp(8), location[1] - sendPopupLayout.getMeasuredHeight() - AndroidUtilities.dp(2)); sendPopupWindow.dimBehind(); view.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING); return false; }); textPaint.setTextSize(AndroidUtilities.dp(12)); textPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); selectedCountView = new View(context) { @Override protected void onDraw(Canvas canvas) { String text = String.format("%d", Math.max(1, selectedPhotosOrder.size())); int textSize = (int) Math.ceil(textPaint.measureText(text)); int size = Math.max(AndroidUtilities.dp(16) + textSize, AndroidUtilities.dp(24)); int cx = getMeasuredWidth() / 2; int cy = getMeasuredHeight() / 2; textPaint.setColor(Theme.getColor(Theme.key_dialogRoundCheckBoxCheck)); paint.setColor(Theme.getColor(Theme.key_dialogBackground)); rect.set(cx - size / 2, 0, cx + size / 2, getMeasuredHeight()); canvas.drawRoundRect(rect, AndroidUtilities.dp(12), AndroidUtilities.dp(12), paint); paint.setColor(Theme.getColor(Theme.key_dialogRoundCheckBox)); rect.set(cx - size / 2 + AndroidUtilities.dp(2), AndroidUtilities.dp(2), cx + size / 2 - AndroidUtilities.dp(2), getMeasuredHeight() - AndroidUtilities.dp(2)); canvas.drawRoundRect(rect, AndroidUtilities.dp(10), AndroidUtilities.dp(10), paint); canvas.drawText(text, cx - textSize / 2, AndroidUtilities.dp(16.2f), textPaint); } }; selectedCountView.setAlpha(0.0f); selectedCountView.setScaleX(0.2f); selectedCountView.setScaleY(0.2f); sizeNotifierFrameLayout.addView(selectedCountView, LayoutHelper.createFrame(42, 24, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, -2, 9)); if (selectPhotoType != SELECT_TYPE_ALL) { commentTextView.setVisibility(View.GONE); } if (loading && (albumsSorted == null || albumsSorted.isEmpty())) { progressView.setVisibility(View.VISIBLE); listView.setEmptyView(null); } else { progressView.setVisibility(View.GONE); listView.setEmptyView(emptyView); } return fragmentView; } @Override public void onResume() { super.onResume(); if (listAdapter != null) { listAdapter.notifyDataSetChanged(); } if (commentTextView != null) { commentTextView.onResume(); } fixLayout(); } @Override public void onPause() { super.onPause(); } @Override public void onConfigurationChanged(android.content.res.Configuration newConfig) { super.onConfigurationChanged(newConfig); fixLayout(); } @SuppressWarnings("unchecked") @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.albumsDidLoad) { int guid = (Integer) args[0]; if (classGuid == guid) { if (selectPhotoType == SELECT_TYPE_AVATAR || selectPhotoType == SELECT_TYPE_WALLPAPER || selectPhotoType == SELECT_TYPE_QR || !allowSearchImages) { albumsSorted = (ArrayList<MediaController.AlbumEntry>) args[2]; } else { albumsSorted = (ArrayList<MediaController.AlbumEntry>) args[1]; } if (progressView != null) { progressView.setVisibility(View.GONE); } if (listView != null && listView.getEmptyView() == null) { listView.setEmptyView(emptyView); } if (listAdapter != null) { listAdapter.notifyDataSetChanged(); } loading = false; } } else if (id == NotificationCenter.closeChats) { removeSelfFromStack(true); } } @Override public boolean onBackPressed() { if (commentTextView != null && commentTextView.isPopupShowing()) { commentTextView.hidePopup(true); return false; } return super.onBackPressed(); } public void setMaxSelectedPhotos(int value, boolean order) { maxSelectedPhotos = value; allowOrder = order; } public void setAllowSearchImages(boolean value) { allowSearchImages = value; } public void setDelegate(PhotoAlbumPickerActivityDelegate delegate) { this.delegate = delegate; } private void sendSelectedPhotos(HashMap<Object, Object> photos, ArrayList<Object> order, boolean notify, int scheduleDate) { if (photos.isEmpty() || delegate == null || sendPressed) { return; } sendPressed = true; ArrayList<SendMessagesHelper.SendingMediaInfo> media = new ArrayList<>(); for (int a = 0; a < order.size(); a++) { Object object = photos.get(order.get(a)); SendMessagesHelper.SendingMediaInfo info = new SendMessagesHelper.SendingMediaInfo(); media.add(info); if (object instanceof MediaController.PhotoEntry) { MediaController.PhotoEntry photoEntry = (MediaController.PhotoEntry) object; if (photoEntry.imagePath != null) { info.path = photoEntry.imagePath; } else { info.path = photoEntry.path; } info.thumbPath = photoEntry.thumbPath; info.videoEditedInfo = photoEntry.editedInfo; info.isVideo = photoEntry.isVideo; info.caption = photoEntry.caption != null ? photoEntry.caption.toString() : null; info.entities = photoEntry.entities; info.masks = photoEntry.stickers; info.ttl = photoEntry.ttl; } else if (object instanceof MediaController.SearchImage) { MediaController.SearchImage searchImage = (MediaController.SearchImage) object; if (searchImage.imagePath != null) { info.path = searchImage.imagePath; } else { info.searchImage = searchImage; } info.thumbPath = searchImage.thumbPath; info.videoEditedInfo = searchImage.editedInfo; info.caption = searchImage.caption != null ? searchImage.caption.toString() : null; info.entities = searchImage.entities; info.masks = searchImage.stickers; info.ttl = searchImage.ttl; if (searchImage.inlineResult != null && searchImage.type == 1) { info.inlineResult = searchImage.inlineResult; info.params = searchImage.params; } searchImage.date = (int) (System.currentTimeMillis() / 1000); } } delegate.didSelectPhotos(media, notify, scheduleDate); } private void fixLayout() { if (listView != null) { ViewTreeObserver obs = listView.getViewTreeObserver(); obs.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { fixLayoutInternal(); if (listView != null) { listView.getViewTreeObserver().removeOnPreDrawListener(this); } return true; } }); } } private void applyCaption() { if (commentTextView.length() <= 0) { return; } int imageId = (Integer) selectedPhotosOrder.get(0); Object entry = selectedPhotos.get(imageId); if (entry instanceof MediaController.PhotoEntry) { MediaController.PhotoEntry photoEntry = (MediaController.PhotoEntry) entry; photoEntry.caption = commentTextView.getText().toString(); } else if (entry instanceof MediaController.SearchImage) { MediaController.SearchImage searchImage = (MediaController.SearchImage) entry; searchImage.caption = commentTextView.getText().toString(); } } private void fixLayoutInternal() { if (getParentActivity() == null) { return; } WindowManager manager = (WindowManager) ApplicationLoader.applicationContext.getSystemService(Activity.WINDOW_SERVICE); int rotation = manager.getDefaultDisplay().getRotation(); columnsCount = 2; if (!AndroidUtilities.isTablet() && (rotation == Surface.ROTATION_270 || rotation == Surface.ROTATION_90)) { columnsCount = 4; } listAdapter.notifyDataSetChanged(); } private boolean showCommentTextView(boolean show) { if (show == (frameLayout2.getTag() != null)) { return false; } frameLayout2.setTag(show ? 1 : null); if (commentTextView.getEditText().isFocused()) { AndroidUtilities.hideKeyboard(commentTextView.getEditText()); } commentTextView.hidePopup(true); if (show) { frameLayout2.setVisibility(View.VISIBLE); writeButtonContainer.setVisibility(View.VISIBLE); } else { frameLayout2.setVisibility(View.INVISIBLE); writeButtonContainer.setVisibility(View.INVISIBLE); } writeButtonContainer.setScaleX(show ? 1.0f : 0.2f); writeButtonContainer.setScaleY(show ? 1.0f : 0.2f); writeButtonContainer.setAlpha(show ? 1.0f : 0.0f); selectedCountView.setScaleX(show ? 1.0f : 0.2f); selectedCountView.setScaleY(show ? 1.0f : 0.2f); selectedCountView.setAlpha(show ? 1.0f : 0.0f); frameLayout2.setTranslationY(show ? 0 : AndroidUtilities.dp(48)); shadow.setTranslationY(show ? 0 : AndroidUtilities.dp(48)); return true; } private void updatePhotosButton() { int count = selectedPhotos.size(); if (count == 0) { selectedCountView.setPivotX(0); selectedCountView.setPivotY(0); showCommentTextView(false); } else { selectedCountView.invalidate(); showCommentTextView(true); } } private void openPhotoPicker(MediaController.AlbumEntry albumEntry, int type) { if (albumEntry != null) { PhotoPickerActivity fragment = new PhotoPickerActivity(type, albumEntry, selectedPhotos, selectedPhotosOrder, selectPhotoType, allowCaption, chatActivity, false); fragment.setCaption(caption = commentTextView.getText()); fragment.setDelegate(new PhotoPickerActivity.PhotoPickerActivityDelegate() { @Override public void selectedPhotosChanged() { updatePhotosButton(); } @Override public void actionButtonPressed(boolean canceled, boolean notify, int scheduleDate) { removeSelfFromStack(); if (!canceled) { sendSelectedPhotos(selectedPhotos, selectedPhotosOrder, notify, scheduleDate); } } @Override public void onCaptionChanged(CharSequence text) { commentTextView.setText(caption = text); } }); fragment.setMaxSelectedPhotos(maxSelectedPhotos, allowOrder); presentFragment(fragment); } else { final HashMap<Object, Object> photos = new HashMap<>(); final ArrayList<Object> order = new ArrayList<>(); if (allowGifs) { PhotoPickerSearchActivity fragment = new PhotoPickerSearchActivity(photos, order, selectPhotoType, allowCaption, chatActivity); fragment.setCaption(caption = commentTextView.getText()); fragment.setDelegate(new PhotoPickerActivity.PhotoPickerActivityDelegate() { @Override public void selectedPhotosChanged() { } @Override public void actionButtonPressed(boolean canceled, boolean notify, int scheduleDate) { removeSelfFromStack(); if (!canceled) { sendSelectedPhotos(photos, order, notify, scheduleDate); } } @Override public void onCaptionChanged(CharSequence text) { commentTextView.setText(caption = text); } }); fragment.setMaxSelectedPhotos(maxSelectedPhotos, allowOrder); presentFragment(fragment); } else { PhotoPickerActivity fragment = new PhotoPickerActivity(0, albumEntry, photos, order, selectPhotoType, allowCaption, chatActivity, false); fragment.setCaption(caption = commentTextView.getText()); fragment.setDelegate(new PhotoPickerActivity.PhotoPickerActivityDelegate() { @Override public void selectedPhotosChanged() { } @Override public void actionButtonPressed(boolean canceled, boolean notify, int scheduleDate) { removeSelfFromStack(); if (!canceled) { sendSelectedPhotos(photos, order, notify, scheduleDate); } } @Override public void onCaptionChanged(CharSequence text) { commentTextView.setText(caption = text); } }); fragment.setMaxSelectedPhotos(maxSelectedPhotos, allowOrder); presentFragment(fragment); } } } private class ListAdapter extends RecyclerListView.SelectionAdapter { private Context mContext; public ListAdapter(Context context) { mContext = context; } @Override public boolean isEnabled(RecyclerView.ViewHolder holder) { return true; } @Override public int getItemCount() { return albumsSorted != null ? (int) Math.ceil(albumsSorted.size() / (float) columnsCount) : 0; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { PhotoPickerAlbumsCell cell = new PhotoPickerAlbumsCell(mContext); cell.setDelegate(albumEntry -> openPhotoPicker(albumEntry, 0)); return new RecyclerListView.Holder(cell); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { PhotoPickerAlbumsCell photoPickerAlbumsCell = (PhotoPickerAlbumsCell) holder.itemView; photoPickerAlbumsCell.setAlbumsCount(columnsCount); for (int a = 0; a < columnsCount; a++) { int index = position * columnsCount + a; if (index < albumsSorted.size()) { MediaController.AlbumEntry albumEntry = albumsSorted.get(index); photoPickerAlbumsCell.setAlbum(a, albumEntry); } else { photoPickerAlbumsCell.setAlbum(a, null); } } photoPickerAlbumsCell.requestLayout(); } @Override public int getItemViewType(int i) { return 0; } } @Override public ArrayList<ThemeDescription> getThemeDescriptions() { ArrayList<ThemeDescription> themeDescriptions = new ArrayList<>(); themeDescriptions.add(new ThemeDescription(fragmentView, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_dialogBackground)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_dialogBackground)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_ITEMSCOLOR, null, null, null, null, Theme.key_dialogTextBlack)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_TITLECOLOR, null, null, null, null, Theme.key_dialogTextBlack)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SELECTORCOLOR, null, null, null, null, Theme.key_dialogButtonSelector)); themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_LISTGLOWCOLOR, null, null, null, null, Theme.key_dialogBackground)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{View.class}, null, new Drawable[]{Theme.chat_attachEmptyDrawable}, null, Theme.key_chat_attachEmptyImage)); themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{View.class}, null, null, null, Theme.key_chat_attachPhotoBackground)); return themeDescriptions; } }
dawitys/Telegram
TMessagesProj/src/main/java/org/telegram/ui/PhotoAlbumPickerActivity.java
41,712
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.ui.Components; import android.Manifest; import android.app.Activity; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; import android.util.Pair; import android.view.View; import androidx.core.content.FileProvider; import androidx.exifinterface.media.ExifInterface; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.BuildVars; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.ImageLoader; import org.telegram.messenger.ImageLocation; import org.telegram.messenger.ImageReceiver; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MediaController; import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessagesController; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.SendMessagesHelper; import org.telegram.messenger.SharedConfig; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; import org.telegram.messenger.VideoEditedInfo; import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.BottomSheet; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.BasePermissionsActivity; import org.telegram.ui.LaunchActivity; import org.telegram.ui.PhotoAlbumPickerActivity; import org.telegram.ui.PhotoCropActivity; import org.telegram.ui.PhotoPickerActivity; import org.telegram.ui.PhotoViewer; import java.io.File; import java.util.ArrayList; import java.util.HashMap; public class ImageUpdater implements NotificationCenter.NotificationCenterDelegate, PhotoCropActivity.PhotoEditActivityDelegate { private final static int ID_TAKE_PHOTO = 0, ID_UPLOAD_FROM_GALLERY = 1, ID_SEARCH_WEB = 2, ID_REMOVE_PHOTO = 3, ID_RECORD_VIDEO = 4; public final static int FOR_TYPE_USER = 0; public final static int FOR_TYPE_CHANNEL = 1; public final static int FOR_TYPE_GROUP = 2; public BaseFragment parentFragment; private ImageUpdaterDelegate delegate; private ChatAttachAlert chatAttachAlert; private int currentAccount = UserConfig.selectedAccount; private ImageReceiver imageReceiver; public String currentPicturePath; private TLRPC.PhotoSize bigPhoto; private TLRPC.PhotoSize smallPhoto; private boolean isVideo; private String uploadingImage; private String uploadingVideo; private String videoPath; private MessageObject convertingVideo; private File picturePath = null; private String finalPath; private boolean clearAfterUpdate; private boolean useAttachMenu = true; private boolean openWithFrontfaceCamera; private boolean supportEmojiMarkup; private boolean searchAvailable = true; private boolean uploadAfterSelect = true; private TLRPC.User user; private boolean isUser; private TLRPC.InputFile uploadedPhoto; private TLRPC.InputFile uploadedVideo; private TLRPC.VideoSize vectorMarkup; private double videoTimestamp; private boolean canSelectVideo; private boolean forceDarkTheme; private boolean showingFromDialog; private boolean canceled; private boolean forUser; private final static int attach_photo = 0; public final static int TYPE_DEFAULT = 0; public final static int TYPE_SET_PHOTO_FOR_USER = 1; public final static int TYPE_SUGGEST_PHOTO_FOR_USER = 2; private int type; public final int setForType; public void processEntry(MediaController.PhotoEntry photoEntry) { String path = null; if (photoEntry.imagePath != null) { path = photoEntry.imagePath; } else { path = photoEntry.path; } MessageObject avatarObject = null; Bitmap bitmap; if (photoEntry.isVideo || photoEntry.editedInfo != null) { TLRPC.TL_message message = new TLRPC.TL_message(); message.id = 0; message.message = ""; message.media = new TLRPC.TL_messageMediaEmpty(); message.action = new TLRPC.TL_messageActionEmpty(); message.dialog_id = 0; avatarObject = new MessageObject(UserConfig.selectedAccount, message, false, false); avatarObject.messageOwner.attachPath = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE), SharedConfig.getLastLocalId() + "_avatar.mp4").getAbsolutePath(); avatarObject.videoEditedInfo = photoEntry.editedInfo; avatarObject.emojiMarkup = photoEntry.emojiMarkup; bitmap = ImageLoader.loadBitmap(photoEntry.thumbPath, null, 800, 800, true); } else { bitmap = ImageLoader.loadBitmap(path, null, 800, 800, true); } processBitmap(bitmap, avatarObject); } public void cancel() { canceled = true; if (uploadingImage != null) { FileLoader.getInstance(currentAccount).cancelFileUpload(uploadingImage, false); } if (uploadingVideo != null) { FileLoader.getInstance(currentAccount).cancelFileUpload(uploadingVideo, false); } if (delegate != null) { delegate.didUploadFailed(); } } public boolean isCanceled() { return canceled; } public void showAvatarConstructor(TLRPC.VideoSize emojiMarkup) { createChatAttachView(); chatAttachAlert.getPhotoLayout().showAvatarConstructorFragment(null, emojiMarkup); } public interface ImageUpdaterDelegate { void didUploadPhoto(TLRPC.InputFile photo, TLRPC.InputFile video, double videoStartTimestamp, String videoPath, TLRPC.PhotoSize bigSize, TLRPC.PhotoSize smallSize, boolean isVideo, TLRPC.VideoSize emojiMarkup); default String getInitialSearchString() { return null; } default void onUploadProgressChanged(float progress) { } default void didStartUpload(boolean isVideo) { } default void didUploadFailed() { } default boolean canFinishFragment() { return true; } } public boolean isUploadingImage() { return uploadingImage != null || uploadingVideo != null || convertingVideo != null; } public void clear() { canceled = false; if (uploadingImage != null || uploadingVideo != null || convertingVideo != null) { clearAfterUpdate = true; } else { parentFragment = null; delegate = null; } if (chatAttachAlert != null) { chatAttachAlert.dismissInternal(); chatAttachAlert.onDestroy(); } } public void setOpenWithFrontfaceCamera(boolean value) { openWithFrontfaceCamera = value; } public ImageUpdater(boolean allowVideo, int setForType, boolean supportEmojiMarkup) { imageReceiver = new ImageReceiver(null); canSelectVideo = allowVideo; this.supportEmojiMarkup = supportEmojiMarkup; this.setForType = setForType; } public void setCanSelectVideo(boolean canSelectVideo) { this.canSelectVideo = canSelectVideo; } public void setDelegate(ImageUpdaterDelegate imageUpdaterDelegate) { delegate = imageUpdaterDelegate; } public void openMenu(boolean hasAvatar, Runnable onDeleteAvatar, DialogInterface.OnDismissListener onDismiss, int type) { if (parentFragment == null || parentFragment.getParentActivity() == null) { return; } canceled = false; this.type = type; if (useAttachMenu) { openAttachMenu(onDismiss); return; } BottomSheet.Builder builder = new BottomSheet.Builder(parentFragment.getParentActivity()); if (type == TYPE_SET_PHOTO_FOR_USER) { builder.setTitle(LocaleController.formatString("SetPhotoFor", R.string.SetPhotoFor, user.first_name), true); } else if (type == TYPE_SUGGEST_PHOTO_FOR_USER) { builder.setTitle(LocaleController.formatString("SuggestPhotoFor", R.string.SuggestPhotoFor, user.first_name), true); } else { builder.setTitle(LocaleController.getString("ChoosePhoto", R.string.ChoosePhoto), true); } ArrayList<CharSequence> items = new ArrayList<>(); ArrayList<Integer> icons = new ArrayList<>(); ArrayList<Integer> ids = new ArrayList<>(); items.add(LocaleController.getString("ChooseTakePhoto", R.string.ChooseTakePhoto)); icons.add(R.drawable.msg_camera); ids.add(ID_TAKE_PHOTO); if (canSelectVideo) { items.add(LocaleController.getString("ChooseRecordVideo", R.string.ChooseRecordVideo)); icons.add(R.drawable.msg_video); ids.add(ID_RECORD_VIDEO); } items.add(LocaleController.getString("ChooseFromGallery", R.string.ChooseFromGallery)); icons.add(R.drawable.msg_photos); ids.add(ID_UPLOAD_FROM_GALLERY); if (searchAvailable) { items.add(LocaleController.getString("ChooseFromSearch", R.string.ChooseFromSearch)); icons.add(R.drawable.msg_search); ids.add(ID_SEARCH_WEB); } if (hasAvatar) { items.add(LocaleController.getString("DeletePhoto", R.string.DeletePhoto)); icons.add(R.drawable.msg_delete); ids.add(ID_REMOVE_PHOTO); } int[] iconsRes = new int[icons.size()]; for (int i = 0, N = icons.size(); i < N; i++) { iconsRes[i] = icons.get(i); } builder.setItems(items.toArray(new CharSequence[0]), iconsRes, (dialogInterface, i) -> { int id = ids.get(i); switch (id) { case ID_TAKE_PHOTO: openCamera(); break; case ID_UPLOAD_FROM_GALLERY: openGallery(); break; case ID_SEARCH_WEB: openSearch(); break; case ID_REMOVE_PHOTO: onDeleteAvatar.run(); break; case ID_RECORD_VIDEO: openVideoCamera(); break; } }); BottomSheet sheet = builder.create(); sheet.setOnHideListener(onDismiss); parentFragment.showDialog(sheet); if (hasAvatar) { sheet.setItemColor(items.size() - 1, Theme.getColor(Theme.key_text_RedBold), Theme.getColor(Theme.key_text_RedRegular)); } } public void setSearchAvailable(boolean value) { useAttachMenu = searchAvailable = value; } public void setSearchAvailable(boolean value, boolean useAttachMenu) { this.useAttachMenu = useAttachMenu; searchAvailable = value; } public void setUploadAfterSelect(boolean value) { uploadAfterSelect = value; } public void onResume() { if (chatAttachAlert != null) { chatAttachAlert.onResume(); } } public void onPause() { if (chatAttachAlert != null) { chatAttachAlert.onPause(); } } public boolean dismissDialogOnPause(Dialog dialog) { return dialog != chatAttachAlert; } public boolean dismissCurrentDialog(Dialog dialog) { if (chatAttachAlert != null && dialog == chatAttachAlert) { chatAttachAlert.getPhotoLayout().closeCamera(false); chatAttachAlert.dismissInternal(); chatAttachAlert.getPhotoLayout().hideCamera(true); return true; } return false; } public void openSearch() { if (parentFragment == null) { return; } final HashMap<Object, Object> photos = new HashMap<>(); final ArrayList<Object> order = new ArrayList<>(); PhotoPickerActivity fragment = new PhotoPickerActivity(0, null, photos, order, 1, false, null, forceDarkTheme); fragment.setDelegate(new PhotoPickerActivity.PhotoPickerActivityDelegate() { private boolean sendPressed; @Override public void selectedPhotosChanged() { } private void sendSelectedPhotos(HashMap<Object, Object> photos, ArrayList<Object> order, boolean notify, int scheduleDate) { } @Override public void actionButtonPressed(boolean canceled, boolean notify, int scheduleDate) { if (photos.isEmpty() || delegate == null || sendPressed || canceled) { return; } sendPressed = true; ArrayList<SendMessagesHelper.SendingMediaInfo> media = new ArrayList<>(); for (int a = 0; a < order.size(); a++) { Object object = photos.get(order.get(a)); SendMessagesHelper.SendingMediaInfo info = new SendMessagesHelper.SendingMediaInfo(); media.add(info); if (object instanceof MediaController.SearchImage) { MediaController.SearchImage searchImage = (MediaController.SearchImage) object; if (searchImage.imagePath != null) { info.path = searchImage.imagePath; } else { info.searchImage = searchImage; } info.videoEditedInfo = searchImage.editedInfo; info.thumbPath = searchImage.thumbPath; info.caption = searchImage.caption != null ? searchImage.caption.toString() : null; info.entities = searchImage.entities; info.masks = searchImage.stickers; info.ttl = searchImage.ttl; } } didSelectPhotos(media); } @Override public void onCaptionChanged(CharSequence caption) { } @Override public boolean canFinishFragment() { return delegate.canFinishFragment(); } }); fragment.setMaxSelectedPhotos(1, false); fragment.setInitialSearchString(delegate.getInitialSearchString()); if (showingFromDialog) { parentFragment.showAsSheet(fragment); } else { parentFragment.presentFragment(fragment); } } private void openAttachMenu(DialogInterface.OnDismissListener onDismissListener) { if (parentFragment == null || parentFragment.getParentActivity() == null) { return; } createChatAttachView(); chatAttachAlert.setOpenWithFrontFaceCamera(openWithFrontfaceCamera); chatAttachAlert.setMaxSelectedPhotos(1, false); chatAttachAlert.getPhotoLayout().loadGalleryPhotos(); if (Build.VERSION.SDK_INT == 21 || Build.VERSION.SDK_INT == 22) { AndroidUtilities.hideKeyboard(parentFragment.getFragmentView().findFocus()); } chatAttachAlert.init(); chatAttachAlert.setOnHideListener(onDismissListener); if (type != 0) { chatAttachAlert.avatarFor(new AvatarFor(user, type)); } chatAttachAlert.forUser = forUser; parentFragment.showDialog(chatAttachAlert); } private void createChatAttachView() { if (parentFragment == null || parentFragment.getParentActivity() == null) { return; } if (chatAttachAlert == null) { chatAttachAlert = new ChatAttachAlert(parentFragment.getParentActivity(), parentFragment, forceDarkTheme, showingFromDialog); chatAttachAlert.setAvatarPicker(canSelectVideo ? 2 : 1, searchAvailable); chatAttachAlert.setDelegate(new ChatAttachAlert.ChatAttachViewDelegate() { @Override public void didPressedButton(int button, boolean arg, boolean notify, int scheduleDate, boolean forceDocument) { if (parentFragment == null || parentFragment.getParentActivity() == null || chatAttachAlert == null) { return; } if (button == 8 || button == 7) { HashMap<Object, Object> photos = chatAttachAlert.getPhotoLayout().getSelectedPhotos(); ArrayList<Object> order = chatAttachAlert.getPhotoLayout().getSelectedPhotosOrder(); ArrayList<SendMessagesHelper.SendingMediaInfo> media = new ArrayList<>(); for (int a = 0; a < order.size(); a++) { Object object = photos.get(order.get(a)); SendMessagesHelper.SendingMediaInfo info = new SendMessagesHelper.SendingMediaInfo(); media.add(info); if (object instanceof MediaController.PhotoEntry) { MediaController.PhotoEntry photoEntry = (MediaController.PhotoEntry) object; if (photoEntry.imagePath != null) { info.path = photoEntry.imagePath; } else { info.path = photoEntry.path; } info.thumbPath = photoEntry.thumbPath; info.videoEditedInfo = photoEntry.editedInfo; info.isVideo = photoEntry.isVideo; info.caption = photoEntry.caption != null ? photoEntry.caption.toString() : null; info.entities = photoEntry.entities; info.masks = photoEntry.stickers; info.ttl = photoEntry.ttl; info.emojiMarkup = photoEntry.emojiMarkup; } else if (object instanceof MediaController.SearchImage) { MediaController.SearchImage searchImage = (MediaController.SearchImage) object; if (searchImage.imagePath != null) { info.path = searchImage.imagePath; } else { info.searchImage = searchImage; } info.thumbPath = searchImage.thumbPath; info.videoEditedInfo = searchImage.editedInfo; info.caption = searchImage.caption != null ? searchImage.caption.toString() : null; info.entities = searchImage.entities; info.masks = searchImage.stickers; info.ttl = searchImage.ttl; if (searchImage.inlineResult != null && searchImage.type == 1) { info.inlineResult = searchImage.inlineResult; info.params = searchImage.params; } searchImage.date = (int) (System.currentTimeMillis() / 1000); } } didSelectPhotos(media); if (button != 8) { chatAttachAlert.dismiss(true); } return; } else { chatAttachAlert.dismissWithButtonClick(button); } processSelectedAttach(button); } @Override public View getRevealView() { return null; } @Override public void didSelectBot(TLRPC.User user) { } @Override public void onCameraOpened() { AndroidUtilities.hideKeyboard(parentFragment.getFragmentView().findFocus()); } @Override public boolean needEnterComment() { return false; } @Override public void doOnIdle(Runnable runnable) { runnable.run(); } private void processSelectedAttach(int which) { if (which == attach_photo) { openCamera(); } } @Override public void openAvatarsSearch() { openSearch(); } }); chatAttachAlert.setImageUpdater(this); } if (type == TYPE_SET_PHOTO_FOR_USER) { chatAttachAlert.getSelectedTextView().setText(LocaleController.formatString("SetPhotoFor", R.string.SetPhotoFor, user.first_name)); } else if (type == TYPE_SUGGEST_PHOTO_FOR_USER) { chatAttachAlert.getSelectedTextView().setText(LocaleController.formatString("SuggestPhotoFor", R.string.SuggestPhotoFor, user.first_name)); } } private void didSelectPhotos(ArrayList<SendMessagesHelper.SendingMediaInfo> photos) { if (!photos.isEmpty()) { SendMessagesHelper.SendingMediaInfo info = photos.get(0); Bitmap bitmap = null; MessageObject avatarObject = null; if (info.isVideo || info.videoEditedInfo != null) { TLRPC.TL_message message = new TLRPC.TL_message(); message.id = 0; message.message = ""; message.media = new TLRPC.TL_messageMediaEmpty(); message.action = new TLRPC.TL_messageActionEmpty(); message.dialog_id = 0; avatarObject = new MessageObject(UserConfig.selectedAccount, message, false, false); avatarObject.messageOwner.attachPath = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE), SharedConfig.getLastLocalId() + "_avatar.mp4").getAbsolutePath(); avatarObject.videoEditedInfo = info.videoEditedInfo; avatarObject.emojiMarkup = info.emojiMarkup; bitmap = ImageLoader.loadBitmap(info.thumbPath, null, 800, 800, true); } else if (info.path != null) { bitmap = ImageLoader.loadBitmap(info.path, null, 800, 800, true); } else if (info.searchImage != null) { if (info.searchImage.photo != null) { TLRPC.PhotoSize photoSize = FileLoader.getClosestPhotoSizeWithSize(info.searchImage.photo.sizes, AndroidUtilities.getPhotoSize()); if (photoSize != null) { File path = FileLoader.getInstance(currentAccount).getPathToAttach(photoSize, true); finalPath = path.getAbsolutePath(); if (!path.exists()) { path = FileLoader.getInstance(currentAccount).getPathToAttach(photoSize, false); if (!path.exists()) { path = null; } } if (path != null) { bitmap = ImageLoader.loadBitmap(path.getAbsolutePath(), null, 800, 800, true); } else { NotificationCenter.getInstance(currentAccount).addObserver(ImageUpdater.this, NotificationCenter.fileLoaded); NotificationCenter.getInstance(currentAccount).addObserver(ImageUpdater.this, NotificationCenter.fileLoadFailed); uploadingImage = FileLoader.getAttachFileName(photoSize.location); imageReceiver.setImage(ImageLocation.getForPhoto(photoSize, info.searchImage.photo), null, null, "jpg", null, 1); } } } else if (info.searchImage.imageUrl != null) { String md5 = Utilities.MD5(info.searchImage.imageUrl) + "." + ImageLoader.getHttpUrlExtension(info.searchImage.imageUrl, "jpg"); File cacheFile = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE), md5); finalPath = cacheFile.getAbsolutePath(); if (cacheFile.exists() && cacheFile.length() != 0) { bitmap = ImageLoader.loadBitmap(cacheFile.getAbsolutePath(), null, 800, 800, true); } else { uploadingImage = info.searchImage.imageUrl; NotificationCenter.getInstance(currentAccount).addObserver(ImageUpdater.this, NotificationCenter.httpFileDidLoad); NotificationCenter.getInstance(currentAccount).addObserver(ImageUpdater.this, NotificationCenter.httpFileDidFailedLoad); imageReceiver.setImage(info.searchImage.imageUrl, null, null, "jpg", 1); } } } processBitmap(bitmap, avatarObject); } } public void openCamera() { if (parentFragment == null || parentFragment.getParentActivity() == null) { return; } try { if (Build.VERSION.SDK_INT >= 23 && parentFragment.getParentActivity().checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { parentFragment.getParentActivity().requestPermissions(new String[]{Manifest.permission.CAMERA}, BasePermissionsActivity.REQUEST_CODE_OPEN_CAMERA); return; } Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File image = AndroidUtilities.generatePicturePath(); if (image != null) { if (Build.VERSION.SDK_INT >= 24) { takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(parentFragment.getParentActivity(), ApplicationLoader.getApplicationId() + ".provider", image)); takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } else { takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image)); } currentPicturePath = image.getAbsolutePath(); } parentFragment.startActivityForResult(takePictureIntent, 13); } catch (Exception e) { FileLog.e(e); } } public void openVideoCamera() { if (parentFragment == null || parentFragment.getParentActivity() == null) { return; } try { if (Build.VERSION.SDK_INT >= 23 && parentFragment.getParentActivity().checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { parentFragment.getParentActivity().requestPermissions(new String[]{Manifest.permission.CAMERA}, 19); return; } Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); File video = AndroidUtilities.generateVideoPath(); if (video != null) { if (Build.VERSION.SDK_INT >= 24) { takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(parentFragment.getParentActivity(), ApplicationLoader.getApplicationId() + ".provider", video)); takeVideoIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); takeVideoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } else if (Build.VERSION.SDK_INT >= 18) { takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(video)); } takeVideoIntent.putExtra("android.intent.extras.CAMERA_FACING", 1); takeVideoIntent.putExtra("android.intent.extras.LENS_FACING_FRONT", 1); takeVideoIntent.putExtra("android.intent.extra.USE_FRONT_CAMERA", true); takeVideoIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10); currentPicturePath = video.getAbsolutePath(); } parentFragment.startActivityForResult(takeVideoIntent, 15); } catch (Exception e) { FileLog.e(e); } } public void onRequestPermissionsResultFragment(int requestCode, String[] permissions, int[] grantResults) { if (chatAttachAlert != null) { if (requestCode == 17) { chatAttachAlert.getPhotoLayout().checkCamera(false); chatAttachAlert.getPhotoLayout().checkStorage(); } else if (requestCode == BasePermissionsActivity.REQUEST_CODE_EXTERNAL_STORAGE) { chatAttachAlert.getPhotoLayout().checkStorage(); } } } public void openGallery() { if (parentFragment == null) { return; } final Activity activity = parentFragment.getParentActivity(); if (Build.VERSION.SDK_INT >= 33 && activity != null) { if (activity.checkSelfPermission(Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED || activity.checkSelfPermission(Manifest.permission.READ_MEDIA_VIDEO) != PackageManager.PERMISSION_GRANTED) { activity.requestPermissions(new String[]{Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VIDEO}, BasePermissionsActivity.REQUEST_CODE_EXTERNAL_STORAGE_FOR_AVATAR); return; } } else if (Build.VERSION.SDK_INT >= 23 && activity != null) { if (activity.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { activity.requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, BasePermissionsActivity.REQUEST_CODE_EXTERNAL_STORAGE_FOR_AVATAR); return; } } PhotoAlbumPickerActivity fragment = new PhotoAlbumPickerActivity(canSelectVideo ? PhotoAlbumPickerActivity.SELECT_TYPE_AVATAR_VIDEO : PhotoAlbumPickerActivity.SELECT_TYPE_AVATAR, false, false, null); fragment.setAllowSearchImages(searchAvailable); fragment.setDelegate(new PhotoAlbumPickerActivity.PhotoAlbumPickerActivityDelegate() { @Override public void didSelectPhotos(ArrayList<SendMessagesHelper.SendingMediaInfo> photos, boolean notify, int scheduleDate) { ImageUpdater.this.didSelectPhotos(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(e); } } }); parentFragment.presentFragment(fragment); } private void startCrop(String path, Uri uri) { AndroidUtilities.runOnUIThread(() -> { try { LaunchActivity activity = (LaunchActivity) parentFragment.getParentActivity(); if (activity == null) { return; } Bundle args = new Bundle(); if (path != null) { args.putString("photoPath", path); } else if (uri != null) { args.putParcelable("photoUri", uri); } PhotoCropActivity photoCropActivity = new PhotoCropActivity(args); photoCropActivity.setDelegate(this); activity.presentFragment(photoCropActivity); } catch (Exception e) { FileLog.e(e); Bitmap bitmap = ImageLoader.loadBitmap(path, uri, 800, 800, true); processBitmap(bitmap, null); } }); } public void openPhotoForEdit(String path, String thumb, int orientation, boolean isVideo) { openPhotoForEdit(path, thumb, new Pair<>(orientation, 0), isVideo); } public void openPhotoForEdit(String path, String thumb, Pair<Integer, Integer> orientation, boolean isVideo) { final ArrayList<Object> arrayList = new ArrayList<>(); MediaController.PhotoEntry photoEntry = new MediaController.PhotoEntry(0, 0, 0, path, orientation.first, false, 0, 0, 0).setOrientation(orientation); photoEntry.isVideo = isVideo; photoEntry.thumbPath = thumb; arrayList.add(photoEntry); PhotoViewer.getInstance().setParentActivity(parentFragment); PhotoViewer.getInstance().openPhotoForSelect(arrayList, 0, PhotoViewer.SELECT_TYPE_AVATAR, false, new PhotoViewer.EmptyPhotoViewerProvider() { @Override public void sendButtonPressed(int index, VideoEditedInfo videoEditedInfo, boolean notify, int scheduleDate, boolean forceDocument) { MediaController.PhotoEntry photoEntry = (MediaController.PhotoEntry) arrayList.get(0); processEntry(photoEntry); } @Override public boolean allowCaption() { return false; } @Override public boolean canScrollAway() { return false; } }, null); } public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { if (requestCode == 0 || requestCode == 2) { createChatAttachView(); if (chatAttachAlert != null) { chatAttachAlert.onActivityResultFragment(requestCode, data, currentPicturePath); } currentPicturePath = null; } else if (requestCode == 13) { parentFragment.getParentActivity().overridePendingTransition(R.anim.alpha_in, R.anim.alpha_out); PhotoViewer.getInstance().setParentActivity(parentFragment); Pair<Integer, Integer> orientation = AndroidUtilities.getImageOrientation(currentPicturePath); openPhotoForEdit(currentPicturePath, null, orientation, false); AndroidUtilities.addMediaToGallery(currentPicturePath); currentPicturePath = null; } else if (requestCode == 14) { if (data == null || data.getData() == null) { return; } startCrop(null, data.getData()); } else if (requestCode == 15) { openPhotoForEdit(currentPicturePath, null, 0, true); AndroidUtilities.addMediaToGallery(currentPicturePath); currentPicturePath = null; } } } private void processBitmap(Bitmap bitmap, MessageObject avatarObject) { if (bitmap == null) { return; } uploadedVideo = null; uploadedPhoto = null; convertingVideo = null; videoPath = null; vectorMarkup = avatarObject == null ? null : avatarObject.emojiMarkup; bigPhoto = ImageLoader.scaleAndSaveImage(bitmap, 800, 800, 80, false, 320, 320); smallPhoto = ImageLoader.scaleAndSaveImage(bitmap, 150, 150, 80, false, 150, 150); if (smallPhoto != null) { try { Bitmap b = BitmapFactory.decodeFile(FileLoader.getInstance(currentAccount).getPathToAttach(smallPhoto, true).getAbsolutePath()); String key = smallPhoto.location.volume_id + "_" + smallPhoto.location.local_id + "@50_50"; ImageLoader.getInstance().putImageToCache(new BitmapDrawable(b), key, true); } catch (Throwable ignore) { } } bitmap.recycle(); if (bigPhoto != null) { UserConfig.getInstance(currentAccount).saveConfig(false); uploadingImage = FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE) + "/" + bigPhoto.location.volume_id + "_" + bigPhoto.location.local_id + ".jpg"; if (uploadAfterSelect) { if (avatarObject != null && avatarObject.videoEditedInfo != null) { if (supportEmojiMarkup && !MessagesController.getInstance(currentAccount).uploadMarkupVideo) { if (delegate != null) { delegate.didStartUpload(true); } if (delegate != null) { //skip upload step delegate.didUploadPhoto(null, null, 0, null, bigPhoto, smallPhoto, isVideo, null); delegate.didUploadPhoto(null, null, videoTimestamp, videoPath, bigPhoto, smallPhoto, isVideo, vectorMarkup); cleanup(); } return; } convertingVideo = avatarObject; long startTime = avatarObject.videoEditedInfo.startTime < 0 ? 0 : avatarObject.videoEditedInfo.startTime; videoTimestamp = (avatarObject.videoEditedInfo.avatarStartTime - startTime) / 1000000.0; avatarObject.videoEditedInfo.shouldLimitFps = false; NotificationCenter.getInstance(currentAccount).addObserver(ImageUpdater.this, NotificationCenter.filePreparingStarted); NotificationCenter.getInstance(currentAccount).addObserver(ImageUpdater.this, NotificationCenter.filePreparingFailed); NotificationCenter.getInstance(currentAccount).addObserver(ImageUpdater.this, NotificationCenter.fileNewChunkAvailable); MediaController.getInstance().scheduleVideoConvert(avatarObject, true, true); uploadingImage = null; if (delegate != null) { delegate.didStartUpload(true); } isVideo = true; } else { if (delegate != null) { delegate.didStartUpload(false); } isVideo = false; } NotificationCenter.getInstance(currentAccount).addObserver(ImageUpdater.this, NotificationCenter.fileUploaded); NotificationCenter.getInstance(currentAccount).addObserver(ImageUpdater.this, NotificationCenter.fileUploadProgressChanged); NotificationCenter.getInstance(currentAccount).addObserver(ImageUpdater.this, NotificationCenter.fileUploadFailed); if (uploadingImage != null) { FileLoader.getInstance(currentAccount).uploadFile(uploadingImage, false, true, ConnectionsManager.FileTypePhoto); } } if (delegate != null) { delegate.didUploadPhoto(null, null, 0, null, bigPhoto, smallPhoto, isVideo, null); } } } @Override public void didFinishEdit(Bitmap bitmap) { processBitmap(bitmap, null); } private void cleanup() { uploadingImage = null; uploadingVideo = null; videoPath = null; convertingVideo = null; if (clearAfterUpdate) { imageReceiver.setImageBitmap((Drawable) null); parentFragment = null; delegate = null; } } private float currentImageProgress; @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.fileUploaded || id == NotificationCenter.fileUploadFailed) { String location = (String) args[0]; if (location.equals(uploadingImage)) { uploadingImage = null; if (id == NotificationCenter.fileUploaded) { uploadedPhoto = (TLRPC.InputFile) args[1]; } } else if (location.equals(uploadingVideo)) { uploadingVideo = null; if (id == NotificationCenter.fileUploaded) { uploadedVideo = (TLRPC.InputFile) args[1]; } } else { return; } if (uploadingImage == null && uploadingVideo == null && convertingVideo == null) { NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.fileUploaded); NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.fileUploadProgressChanged); NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.fileUploadFailed); if (id == NotificationCenter.fileUploaded) { if (delegate != null) { delegate.didUploadPhoto(uploadedPhoto, uploadedVideo, videoTimestamp, videoPath, bigPhoto, smallPhoto, isVideo, vectorMarkup); } } cleanup(); } } else if (id == NotificationCenter.fileUploadProgressChanged) { String location = (String) args[0]; String path = convertingVideo != null ? uploadingVideo : uploadingImage; if (delegate != null && location.equals(path)) { Long loadedSize = (Long) args[1]; Long totalSize = (Long) args[2]; float progress = Math.min(1f, loadedSize / (float) totalSize); delegate.onUploadProgressChanged(currentImageProgress = progress); } } else if (id == NotificationCenter.fileLoaded || id == NotificationCenter.fileLoadFailed || id == NotificationCenter.httpFileDidLoad || id == NotificationCenter.httpFileDidFailedLoad) { String path = (String) args[0]; currentImageProgress = 1f; if (path.equals(uploadingImage)) { NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.fileLoaded); NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.fileLoadFailed); NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.httpFileDidLoad); NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.httpFileDidFailedLoad); uploadingImage = null; if (id == NotificationCenter.fileLoaded || id == NotificationCenter.httpFileDidLoad) { Bitmap bitmap = ImageLoader.loadBitmap(finalPath, null, 800, 800, true); processBitmap(bitmap, null); } else { imageReceiver.setImageBitmap((Drawable) null); if (delegate != null) { delegate.didUploadFailed(); } } } } else if (id == NotificationCenter.filePreparingFailed) { MessageObject messageObject = (MessageObject) args[0]; if (messageObject != convertingVideo || parentFragment == null) { return; } NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.filePreparingStarted); NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.filePreparingFailed); NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.fileNewChunkAvailable); cleanup(); } else if (id == NotificationCenter.fileNewChunkAvailable) { MessageObject messageObject = (MessageObject) args[0]; if (messageObject != convertingVideo || parentFragment == null) { return; } String finalPath = (String) args[1]; long availableSize = (Long) args[2]; long finalSize = (Long) args[3]; parentFragment.getFileLoader().checkUploadNewDataAvailable(finalPath, false, availableSize, finalSize); if (finalSize != 0) { double lastFrameTimestamp = ((Long) args[5]) / 1000000.0; if (videoTimestamp > lastFrameTimestamp) { videoTimestamp = lastFrameTimestamp; } Bitmap bitmap = SendMessagesHelper.createVideoThumbnailAtTime(finalPath, (long) (videoTimestamp * 1000), null, true); if (bitmap != null) { File path = FileLoader.getInstance(currentAccount).getPathToAttach(smallPhoto, true); if (path != null) { if (BuildVars.LOGS_ENABLED) { FileLog.e("delete file " + path); } path.delete(); } path = FileLoader.getInstance(currentAccount).getPathToAttach(bigPhoto, true); if (path != null) { if (BuildVars.LOGS_ENABLED) { FileLog.e("delete file " + path); } path.delete(); } bigPhoto = ImageLoader.scaleAndSaveImage(bitmap, 800, 800, 80, false, 320, 320); smallPhoto = ImageLoader.scaleAndSaveImage(bitmap, 150, 150, 80, false, 150, 150); if (smallPhoto != null) { try { Bitmap b = BitmapFactory.decodeFile(FileLoader.getInstance(currentAccount).getPathToAttach(smallPhoto, true).getAbsolutePath()); String key = smallPhoto.location.volume_id + "_" + smallPhoto.location.local_id + "@50_50"; ImageLoader.getInstance().putImageToCache(new BitmapDrawable(b), key, true); } catch (Throwable ignore) { } } } NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.filePreparingStarted); NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.filePreparingFailed); NotificationCenter.getInstance(currentAccount).removeObserver(ImageUpdater.this, NotificationCenter.fileNewChunkAvailable); uploadingVideo = videoPath = finalPath; convertingVideo = null; } } else if (id == NotificationCenter.filePreparingStarted) { MessageObject messageObject = (MessageObject) args[0]; if (messageObject != convertingVideo || parentFragment == null) { return; } uploadingVideo = (String) args[1]; parentFragment.getFileLoader().uploadFile(uploadingVideo, false, false, (int) convertingVideo.videoEditedInfo.estimatedSize, ConnectionsManager.FileTypeVideo, false); } } public void setForceDarkTheme(boolean forceDarkTheme) { this.forceDarkTheme = forceDarkTheme; } public void setShowingFromDialog(boolean b) { showingFromDialog = b; } public void setUser(TLRPC.User user) { this.user = user; } public float getCurrentImageProgress() { return currentImageProgress; } public static class AvatarFor { public final TLObject object; public TLRPC.User fromObject; public final int type; public boolean self; public boolean isVideo; public AvatarFor(TLObject object, int type) { this.object = object; this.type = type; self = object instanceof TLRPC.User && ((TLRPC.User) object).self; } } }
Telegram-FOSS-Team/Telegram-FOSS
TMessagesProj/src/main/java/org/telegram/ui/Components/ImageUpdater.java
41,713
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.messenger; import android.text.TextUtils; import android.util.SparseArray; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import org.telegram.tgnet.tl.TL_stories; import org.telegram.ui.LaunchActivity; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.regex.Matcher; import java.util.regex.Pattern; public class FileLoader extends BaseController { private static final int PRIORITY_STREAM = 4; public static final int PRIORITY_HIGH = 3; public static final int PRIORITY_NORMAL_UP = 2; public static final int PRIORITY_NORMAL = 1; public static final int PRIORITY_LOW = 0; private int priorityIncreasePointer; private static Pattern sentPattern; public static FilePathDatabase.FileMeta getFileMetadataFromParent(int currentAccount, Object parentObject) { if (parentObject instanceof String) { String str = (String) parentObject; if (str.startsWith("sent_")) { if (sentPattern == null) { sentPattern = Pattern.compile("sent_.*_([0-9]+)_([0-9]+)_([0-9]+)_([0-9]+)"); } try { Matcher matcher = sentPattern.matcher(str); if (matcher.matches()) { FilePathDatabase.FileMeta fileMeta = new FilePathDatabase.FileMeta(); fileMeta.messageId = Integer.parseInt(matcher.group(1)); fileMeta.dialogId = Long.parseLong(matcher.group(2)); fileMeta.messageType = Integer.parseInt(matcher.group(3)); fileMeta.messageSize = Long.parseLong(matcher.group(4)); return fileMeta; } } catch (Exception e) { FileLog.e(e); } } } else if (parentObject instanceof MessageObject) { MessageObject messageObject = (MessageObject) parentObject; FilePathDatabase.FileMeta fileMeta = new FilePathDatabase.FileMeta(); fileMeta.messageId = messageObject.getId(); fileMeta.dialogId = messageObject.getDialogId(); fileMeta.messageType = messageObject.type; fileMeta.messageSize = messageObject.getSize(); return fileMeta; } else if (parentObject instanceof TL_stories.StoryItem) { TL_stories.StoryItem storyItem = (TL_stories.StoryItem) parentObject; FilePathDatabase.FileMeta fileMeta = new FilePathDatabase.FileMeta(); fileMeta.dialogId = storyItem.dialogId; fileMeta.messageType = MessageObject.TYPE_STORY; return fileMeta; } return null; } public static TLRPC.VideoSize getVectorMarkupVideoSize(TLRPC.Photo photo) { if (photo == null || photo.video_sizes == null) { return null; } for (int i = 0; i < photo.video_sizes.size(); i++) { TLRPC.VideoSize videoSize = photo.video_sizes.get(i); if (videoSize instanceof TLRPC.TL_videoSizeEmojiMarkup || videoSize instanceof TLRPC.TL_videoSizeStickerMarkup) { return videoSize; } } return null; } public static TLRPC.VideoSize getEmojiMarkup(ArrayList<TLRPC.VideoSize> video_sizes) { for (int i = 0; i < video_sizes.size(); i++) { if (video_sizes.get(i) instanceof TLRPC.TL_videoSizeEmojiMarkup || video_sizes.get(i) instanceof TLRPC.TL_videoSizeStickerMarkup) { return video_sizes.get(i); } } return null; } private int getPriorityValue(int priorityType) { if (priorityType == PRIORITY_STREAM) { return Integer.MAX_VALUE; } else if (priorityType == PRIORITY_HIGH) { priorityIncreasePointer++; return FileLoaderPriorityQueue.PRIORITY_VALUE_MAX + priorityIncreasePointer; } else if (priorityType == PRIORITY_NORMAL_UP) { priorityIncreasePointer++; return FileLoaderPriorityQueue.PRIORITY_VALUE_NORMAL + priorityIncreasePointer; } else if (priorityType == PRIORITY_NORMAL) { return FileLoaderPriorityQueue.PRIORITY_VALUE_NORMAL; } else { return 0; } } public DispatchQueue getFileLoaderQueue() { return fileLoaderQueue; } public void setLocalPathTo(TLObject attach, String attachPath) { long documentId = 0; int dcId = 0; int type = 0; if (attach instanceof TLRPC.Document) { TLRPC.Document document = (TLRPC.Document) attach; if (document.key != null) { type = MEDIA_DIR_CACHE; } else { if (MessageObject.isVoiceDocument(document)) { type = MEDIA_DIR_AUDIO; } else if (MessageObject.isVideoDocument(document)) { type = MEDIA_DIR_VIDEO; } else { type = MEDIA_DIR_DOCUMENT; } } documentId = document.id; dcId = document.dc_id; filePathDatabase.putPath(documentId, dcId, type, FilePathDatabase.FLAG_LOCALLY_CREATED, attachPath); } else if (attach instanceof TLRPC.PhotoSize) { TLRPC.PhotoSize photoSize = (TLRPC.PhotoSize) attach; if (photoSize instanceof TLRPC.TL_photoStrippedSize || photoSize instanceof TLRPC.TL_photoPathSize) { return; } else if (photoSize.location == null || photoSize.location.key != null || photoSize.location.volume_id == Integer.MIN_VALUE && photoSize.location.local_id < 0 || photoSize.size < 0) { type = MEDIA_DIR_CACHE; } else { type = MEDIA_DIR_IMAGE; } documentId = photoSize.location.volume_id; dcId = photoSize.location.dc_id + (photoSize.location.local_id << 16); filePathDatabase.putPath(documentId, dcId, type, FilePathDatabase.FLAG_LOCALLY_CREATED, attachPath); } } public interface FileLoaderDelegate { void fileUploadProgressChanged(FileUploadOperation operation, String location, long uploadedSize, long totalSize, boolean isEncrypted); void fileDidUploaded(String location, TLRPC.InputFile inputFile, TLRPC.InputEncryptedFile inputEncryptedFile, byte[] key, byte[] iv, long totalFileSize); void fileDidFailedUpload(String location, boolean isEncrypted); void fileDidLoaded(String location, File finalFile, Object parentObject, int type); void fileDidFailedLoad(String location, int state); void fileLoadProgressChanged(FileLoadOperation operation, String location, long uploadedSize, long totalSize); } public static final int MEDIA_DIR_IMAGE = 0; public static final int MEDIA_DIR_AUDIO = 1; public static final int MEDIA_DIR_VIDEO = 2; public static final int MEDIA_DIR_DOCUMENT = 3; public static final int MEDIA_DIR_CACHE = 4; public static final int MEDIA_DIR_FILES = 5; public static final int MEDIA_DIR_STORIES = 6; public static final int MEDIA_DIR_IMAGE_PUBLIC = 100; public static final int MEDIA_DIR_VIDEO_PUBLIC = 101; public static final int IMAGE_TYPE_LOTTIE = 1; public static final int IMAGE_TYPE_ANIMATION = 2; public static final int IMAGE_TYPE_SVG = 3; public static final int IMAGE_TYPE_SVG_WHITE = 4; public static final int IMAGE_TYPE_THEME_PREVIEW = 5; // private final FileLoaderPriorityQueue largeFilesQueue = new FileLoaderPriorityQueue("large files queue", 2); // private final FileLoaderPriorityQueue filesQueue = new FileLoaderPriorityQueue("files queue", 3); // private final FileLoaderPriorityQueue imagesQueue = new FileLoaderPriorityQueue("imagesQueue queue", 6); // private final FileLoaderPriorityQueue audioQueue = new FileLoaderPriorityQueue("audioQueue queue", 3); private final FileLoaderPriorityQueue[] smallFilesQueue = new FileLoaderPriorityQueue[5]; private final FileLoaderPriorityQueue[] largeFilesQueue = new FileLoaderPriorityQueue[5]; public final static long DEFAULT_MAX_FILE_SIZE = 1024L * 1024L * 2000L; public final static long DEFAULT_MAX_FILE_SIZE_PREMIUM = DEFAULT_MAX_FILE_SIZE * 2L; public final static int PRELOAD_CACHE_TYPE = 11; private volatile static DispatchQueue fileLoaderQueue = new DispatchQueue("fileUploadQueue"); private final FilePathDatabase filePathDatabase; private final LinkedList<FileUploadOperation> uploadOperationQueue = new LinkedList<>(); private final LinkedList<FileUploadOperation> uploadSmallOperationQueue = new LinkedList<>(); private final ConcurrentHashMap<String, FileUploadOperation> uploadOperationPaths = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, FileUploadOperation> uploadOperationPathsEnc = new ConcurrentHashMap<>(); private int currentUploadOperationsCount = 0; private int currentUploadSmallOperationsCount = 0; private final ConcurrentHashMap<String, FileLoadOperation> loadOperationPaths = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, LoadOperationUIObject> loadOperationPathsUI = new ConcurrentHashMap<>(10, 1, 2); private HashMap<String, Long> uploadSizes = new HashMap<>(); private HashMap<String, Boolean> loadingVideos = new HashMap<>(); private String forceLoadingFile; private static SparseArray<File> mediaDirs = null; private FileLoaderDelegate delegate = null; private int lastReferenceId; private ConcurrentHashMap<Integer, Object> parentObjectReferences = new ConcurrentHashMap<>(); private static final FileLoader[] Instance = new FileLoader[UserConfig.MAX_ACCOUNT_COUNT]; public static FileLoader getInstance(int num) { FileLoader localInstance = Instance[num]; if (localInstance == null) { synchronized (FileLoader.class) { localInstance = Instance[num]; if (localInstance == null) { Instance[num] = localInstance = new FileLoader(num); } } } return localInstance; } public FileLoader(int instance) { super(instance); filePathDatabase = new FilePathDatabase(instance); for (int i = 0; i < smallFilesQueue.length; i++) { smallFilesQueue[i] = new FileLoaderPriorityQueue(instance, "smallFilesQueue dc" + (i + 1), FileLoaderPriorityQueue.TYPE_SMALL, fileLoaderQueue); largeFilesQueue[i] = new FileLoaderPriorityQueue(instance, "largeFilesQueue dc" + (i + 1), FileLoaderPriorityQueue.TYPE_LARGE, fileLoaderQueue); } dumpFilesQueue(); } public static void setMediaDirs(SparseArray<File> dirs) { mediaDirs = dirs; } public static File checkDirectory(int type) { return mediaDirs.get(type); } public static File getDirectory(int type) { File dir = mediaDirs.get(type); if (dir == null && type != FileLoader.MEDIA_DIR_CACHE) { dir = mediaDirs.get(FileLoader.MEDIA_DIR_CACHE); } if (BuildVars.NO_SCOPED_STORAGE) { try { if (dir != null && !dir.isDirectory()) { dir.mkdirs(); } } catch (Exception e) { //don't prompt } } return dir; } public int getFileReference(Object parentObject) { int reference = lastReferenceId++; parentObjectReferences.put(reference, parentObject); return reference; } public Object getParentObject(int reference) { return parentObjectReferences.get(reference); } public void setLoadingVideoInternal(TLRPC.Document document, boolean player) { String key = getAttachFileName(document); String dKey = key + (player ? "p" : ""); loadingVideos.put(dKey, true); getNotificationCenter().postNotificationName(NotificationCenter.videoLoadingStateChanged, key); } public void setLoadingVideo(TLRPC.Document document, boolean player, boolean schedule) { if (document == null) { return; } if (schedule) { AndroidUtilities.runOnUIThread(() -> setLoadingVideoInternal(document, player)); } else { setLoadingVideoInternal(document, player); } } public void setLoadingVideoForPlayer(TLRPC.Document document, boolean player) { if (document == null) { return; } String key = getAttachFileName(document); if (loadingVideos.containsKey(key + (player ? "" : "p"))) { loadingVideos.put(key + (player ? "p" : ""), true); } } private void removeLoadingVideoInternal(TLRPC.Document document, boolean player) { String key = getAttachFileName(document); String dKey = key + (player ? "p" : ""); if (loadingVideos.remove(dKey) != null) { getNotificationCenter().postNotificationName(NotificationCenter.videoLoadingStateChanged, key); } } public void removeLoadingVideo(TLRPC.Document document, boolean player, boolean schedule) { if (document == null) { return; } if (schedule) { AndroidUtilities.runOnUIThread(() -> removeLoadingVideoInternal(document, player)); } else { removeLoadingVideoInternal(document, player); } } public boolean isLoadingVideo(TLRPC.Document document, boolean player) { return document != null && loadingVideos.containsKey(getAttachFileName(document) + (player ? "p" : "")); } public boolean isLoadingVideoAny(TLRPC.Document document) { return isLoadingVideo(document, false) || isLoadingVideo(document, true); } public void cancelFileUpload(final String location, final boolean enc) { if (location == null) { return; } fileLoaderQueue.postRunnable(() -> { FileUploadOperation operation; if (!enc) { operation = uploadOperationPaths.get(location); } else { operation = uploadOperationPathsEnc.get(location); } uploadSizes.remove(location); if (operation != null) { uploadOperationPathsEnc.remove(location); uploadOperationQueue.remove(operation); uploadSmallOperationQueue.remove(operation); operation.cancel(); } }); } public void checkUploadNewDataAvailable(final String location, final boolean encrypted, final long newAvailableSize, final long finalSize) { checkUploadNewDataAvailable(location, encrypted, newAvailableSize, finalSize, null); } public void checkUploadNewDataAvailable(final String location, final boolean encrypted, final long newAvailableSize, final long finalSize, final Float progress) { fileLoaderQueue.postRunnable(() -> { FileUploadOperation operation; if (encrypted) { operation = uploadOperationPathsEnc.get(location); } else { operation = uploadOperationPaths.get(location); } if (operation != null) { operation.checkNewDataAvailable(newAvailableSize, finalSize, progress); } else if (finalSize != 0) { uploadSizes.put(location, finalSize); } }); } public void onNetworkChanged(final boolean slow) { fileLoaderQueue.postRunnable(() -> { for (ConcurrentHashMap.Entry<String, FileUploadOperation> entry : uploadOperationPaths.entrySet()) { entry.getValue().onNetworkChanged(slow); } for (ConcurrentHashMap.Entry<String, FileUploadOperation> entry : uploadOperationPathsEnc.entrySet()) { entry.getValue().onNetworkChanged(slow); } }); } public void uploadFile(final String location, final boolean encrypted, final boolean small, final int type) { uploadFile(location, encrypted, small, 0, type, false); } public void uploadFile(final String location, final boolean encrypted, final boolean small, final long estimatedSize, final int type, boolean forceSmallFile) { if (location == null) { return; } fileLoaderQueue.postRunnable(() -> { if (encrypted) { if (uploadOperationPathsEnc.containsKey(location)) { return; } } else { if (uploadOperationPaths.containsKey(location)) { return; } } long esimated = estimatedSize; if (esimated != 0) { Long finalSize = uploadSizes.get(location); if (finalSize != null) { esimated = 0; uploadSizes.remove(location); } } FileUploadOperation operation = new FileUploadOperation(currentAccount, location, encrypted, esimated, type); if (delegate != null && estimatedSize != 0) { delegate.fileUploadProgressChanged(operation, location, 0, estimatedSize, encrypted); } if (encrypted) { uploadOperationPathsEnc.put(location, operation); } else { uploadOperationPaths.put(location, operation); } if (forceSmallFile) { operation.setForceSmallFile(); } operation.setDelegate(new FileUploadOperation.FileUploadOperationDelegate() { @Override public void didFinishUploadingFile(final FileUploadOperation operation, final TLRPC.InputFile inputFile, final TLRPC.InputEncryptedFile inputEncryptedFile, final byte[] key, final byte[] iv) { fileLoaderQueue.postRunnable(() -> { if (encrypted) { uploadOperationPathsEnc.remove(location); } else { uploadOperationPaths.remove(location); } if (small) { currentUploadSmallOperationsCount--; if (currentUploadSmallOperationsCount < 1) { FileUploadOperation operation12 = uploadSmallOperationQueue.poll(); if (operation12 != null) { currentUploadSmallOperationsCount++; operation12.start(); } } } else { currentUploadOperationsCount--; if (currentUploadOperationsCount < 1) { FileUploadOperation operation12 = uploadOperationQueue.poll(); if (operation12 != null) { currentUploadOperationsCount++; operation12.start(); } } } if (delegate != null) { delegate.fileDidUploaded(location, inputFile, inputEncryptedFile, key, iv, operation.getTotalFileSize()); } }); } @Override public void didFailedUploadingFile(final FileUploadOperation operation) { fileLoaderQueue.postRunnable(() -> { if (encrypted) { uploadOperationPathsEnc.remove(location); } else { uploadOperationPaths.remove(location); } if (delegate != null) { delegate.fileDidFailedUpload(location, encrypted); } if (small) { currentUploadSmallOperationsCount--; if (currentUploadSmallOperationsCount < 1) { FileUploadOperation operation1 = uploadSmallOperationQueue.poll(); if (operation1 != null) { currentUploadSmallOperationsCount++; operation1.start(); } } } else { currentUploadOperationsCount--; if (currentUploadOperationsCount < 1) { FileUploadOperation operation1 = uploadOperationQueue.poll(); if (operation1 != null) { currentUploadOperationsCount++; operation1.start(); } } } }); } @Override public void didChangedUploadProgress(FileUploadOperation operation, long uploadedSize, long totalSize) { if (delegate != null) { delegate.fileUploadProgressChanged(operation, location, uploadedSize, totalSize, encrypted); } } }); if (small) { if (currentUploadSmallOperationsCount < 1) { currentUploadSmallOperationsCount++; operation.start(); } else { uploadSmallOperationQueue.add(operation); } } else { if (currentUploadOperationsCount < 1) { currentUploadOperationsCount++; operation.start(); } else { uploadOperationQueue.add(operation); } } }); } public void setForceStreamLoadingFile(TLRPC.FileLocation location, String ext) { if (location == null) { return; } fileLoaderQueue.postRunnable(() -> { forceLoadingFile = getAttachFileName(location, ext); FileLoadOperation operation = loadOperationPaths.get(forceLoadingFile); if (operation != null) { if (operation.isPreloadVideoOperation()) { operation.setIsPreloadVideoOperation(false); } operation.setForceRequest(true); operation.setPriority(getPriorityValue(PRIORITY_STREAM)); operation.getQueue().remove(operation); operation.getQueue().add(operation); operation.getQueue().checkLoadingOperations(); } }); } public void cancelLoadFile(TLRPC.Document document) { cancelLoadFile(document, false); } public void cancelLoadFile(TLRPC.Document document, boolean deleteFile) { cancelLoadFile(document, null, null, null, null, null, deleteFile); } public void cancelLoadFile(SecureDocument document) { cancelLoadFile(null, document, null, null, null, null, false); } public void cancelLoadFile(WebFile document) { cancelLoadFile(null, null, document, null, null, null, false); } public void cancelLoadFile(TLRPC.PhotoSize photo) { cancelLoadFile(photo, false); } public void cancelLoadFile(TLRPC.PhotoSize photo, boolean deleteFile) { cancelLoadFile(null, null, null, photo.location, null, null, deleteFile); } public void cancelLoadFile(TLRPC.FileLocation location, String ext) { cancelLoadFile(location, ext, false); } public void cancelLoadFile(TLRPC.FileLocation location, String ext, boolean deleteFile) { cancelLoadFile(null, null, null, location, ext, null, deleteFile); } public void cancelLoadFile(String fileName) { cancelLoadFile(null, null, null, null, null, fileName, true); } public void cancelLoadFiles(ArrayList<String> fileNames) { for (int a = 0, N = fileNames.size(); a < N; a++) { cancelLoadFile(null, null, null, null, null, fileNames.get(a), true); } } private void cancelLoadFile(final TLRPC.Document document, final SecureDocument secureDocument, final WebFile webDocument, final TLRPC.FileLocation location, final String locationExt, String name, boolean deleteFile) { if (location == null && document == null && webDocument == null && secureDocument == null && TextUtils.isEmpty(name)) { return; } final String fileName; if (location != null) { fileName = getAttachFileName(location, locationExt); } else if (document != null) { fileName = getAttachFileName(document); } else if (secureDocument != null) { fileName = getAttachFileName(secureDocument); } else if (webDocument != null) { fileName = getAttachFileName(webDocument); } else { fileName = name; } LoadOperationUIObject uiObject = loadOperationPathsUI.remove(fileName); Runnable runnable = uiObject != null ? uiObject.loadInternalRunnable : null; boolean removed = uiObject != null; if (runnable != null) { fileLoaderQueue.cancelRunnable(runnable); } fileLoaderQueue.postRunnable(() -> { FileLoadOperation operation = loadOperationPaths.remove(fileName); if (operation != null) { FileLoaderPriorityQueue queue = operation.getQueue(); queue.cancel(operation); } }); if (removed && document != null) { AndroidUtilities.runOnUIThread(() -> { getNotificationCenter().postNotificationName(NotificationCenter.onDownloadingFilesChanged); }); } } public void changePriority(int priority, final TLRPC.Document document, final SecureDocument secureDocument, final WebFile webDocument, final TLRPC.FileLocation location, final String locationExt, String name) { if (location == null && document == null && webDocument == null && secureDocument == null && TextUtils.isEmpty(name)) { return; } final String fileName; if (location != null) { fileName = getAttachFileName(location, locationExt); } else if (document != null) { fileName = getAttachFileName(document); } else if (secureDocument != null) { fileName = getAttachFileName(secureDocument); } else if (webDocument != null) { fileName = getAttachFileName(webDocument); } else { fileName = name; } fileLoaderQueue.postRunnable(() -> { FileLoadOperation operation = loadOperationPaths.get(fileName); if (operation != null) { int newPriority = getPriorityValue(priority); if (operation.getPriority() == newPriority) { return; } operation.setPriority(newPriority); FileLoaderPriorityQueue queue = operation.getQueue(); queue.remove(operation); queue.add(operation); queue.checkLoadingOperations(); FileLog.d("update priority " + fileName + " position in queue " + operation.getPositionInQueue() + " account=" + currentAccount); } }); } public void cancelLoadAllFiles() { for (String fileName : loadOperationPathsUI.keySet()) { LoadOperationUIObject uiObject = loadOperationPathsUI.get(fileName); Runnable runnable = uiObject != null ? uiObject.loadInternalRunnable : null; boolean removed = uiObject != null; if (runnable != null) { fileLoaderQueue.cancelRunnable(runnable); } fileLoaderQueue.postRunnable(() -> { FileLoadOperation operation = loadOperationPaths.remove(fileName); if (operation != null) { FileLoaderPriorityQueue queue = operation.getQueue(); queue.cancel(operation); } }); // if (removed && document != null) { // AndroidUtilities.runOnUIThread(() -> { // getNotificationCenter().postNotificationName(NotificationCenter.onDownloadingFilesChanged); // }); // } } } public boolean isLoadingFile(final String fileName) { return fileName != null && loadOperationPathsUI.containsKey(fileName); } public float getBufferedProgressFromPosition(final float position, final String fileName) { if (TextUtils.isEmpty(fileName)) { return 0; } FileLoadOperation loadOperation = loadOperationPaths.get(fileName); if (loadOperation != null) { return loadOperation.getDownloadedLengthFromOffset(position); } else { return 0.0f; } } public void loadFile(ImageLocation imageLocation, Object parentObject, String ext, int priority, int cacheType) { if (imageLocation == null) { return; } if (cacheType == 0 && (imageLocation.isEncrypted() || imageLocation.photoSize != null && imageLocation.getSize() == 0)) { cacheType = 1; } loadFile(imageLocation.document, imageLocation.secureDocument, imageLocation.webFile, imageLocation.location, imageLocation, parentObject, ext, imageLocation.getSize(), priority, cacheType); } public void loadFile(SecureDocument secureDocument, int priority) { if (secureDocument == null) { return; } loadFile(null, secureDocument, null, null, null, null, null, 0, priority, 1); } public void loadFile(TLRPC.Document document, Object parentObject, int priority, int cacheType) { if (document == null) { return; } if (cacheType == 0 && document.key != null) { cacheType = 1; } loadFile(document, null, null, null, null, parentObject, null, 0, priority, cacheType); } public void loadFile(WebFile document, int priority, int cacheType) { loadFile(null, null, document, null, null, null, null, 0, priority, cacheType); } private FileLoadOperation loadFileInternal(final TLRPC.Document document, final SecureDocument secureDocument, final WebFile webDocument, TLRPC.TL_fileLocationToBeDeprecated location, final ImageLocation imageLocation, Object parentObject, final String locationExt, final long locationSize, int priority, final FileLoadOperationStream stream, final long streamOffset, boolean streamPriority, final int cacheType) { String fileName; if (location != null) { fileName = getAttachFileName(location, locationExt); } else if (secureDocument != null) { fileName = getAttachFileName(secureDocument); } else if (document != null) { fileName = getAttachFileName(document); } else if (webDocument != null) { fileName = getAttachFileName(webDocument); } else { fileName = null; } if (fileName == null || fileName.contains("" + Integer.MIN_VALUE)) { return null; } if (fileName.startsWith("0_0")) { FileLog.e(new RuntimeException("cant get hash from " + document)); return null; } if (cacheType != 10 && !TextUtils.isEmpty(fileName) && !fileName.contains("" + Integer.MIN_VALUE)) { loadOperationPathsUI.put(fileName, new LoadOperationUIObject()); } if (document != null && parentObject instanceof MessageObject && ((MessageObject) parentObject).putInDownloadsStore && !((MessageObject) parentObject).isAnyKindOfSticker()) { getDownloadController().startDownloadFile(document, (MessageObject) parentObject); } final String finalFileName = fileName; FileLoadOperation operation = loadOperationPaths.get(finalFileName); priority = getPriorityValue(priority); if (operation != null) { if (cacheType != 10 && operation.isPreloadVideoOperation()) { operation.setIsPreloadVideoOperation(false); } operation.setForceRequest(priority > 0); operation.setStream(stream, streamPriority, streamOffset); boolean priorityChanged = false; if (operation.getPriority() != priority) { priorityChanged = true; operation.setPriority(priority); } operation.getQueue().add(operation); operation.updateProgress(); if (priorityChanged) { operation.getQueue().checkLoadingOperations(); } FileLog.d("load operation update position fileName=" + finalFileName + " position in queue " + operation.getPositionInQueue() + " preloadFinish " + operation.isPreloadFinished()); return operation; } File tempDir = getDirectory(MEDIA_DIR_CACHE); File storeDir = tempDir; int type = MEDIA_DIR_CACHE; long documentId = 0; int dcId = 0; if (secureDocument != null) { operation = new FileLoadOperation(secureDocument); type = MEDIA_DIR_DOCUMENT; } else if (location != null) { documentId = location.volume_id; dcId = location.dc_id + (location.local_id << 16); operation = new FileLoadOperation(imageLocation, parentObject, locationExt, locationSize); type = MEDIA_DIR_IMAGE; } else if (document != null) { operation = new FileLoadOperation(document, parentObject); if (MessageObject.isVoiceDocument(document)) { type = MEDIA_DIR_AUDIO; } else if (MessageObject.isVideoDocument(document)) { type = MEDIA_DIR_VIDEO; documentId = document.id; dcId = document.dc_id; } else { type = MEDIA_DIR_DOCUMENT; documentId = document.id; dcId = document.dc_id; } if (MessageObject.isRoundVideoDocument(document)) { documentId = 0; dcId = 0; } } else if (webDocument != null) { operation = new FileLoadOperation(currentAccount, webDocument); if (webDocument.location != null) { type = MEDIA_DIR_CACHE; } else if (MessageObject.isVoiceWebDocument(webDocument)) { type = MEDIA_DIR_AUDIO; } else if (MessageObject.isVideoWebDocument(webDocument)) { type = MEDIA_DIR_VIDEO; } else if (MessageObject.isImageWebDocument(webDocument)) { type = MEDIA_DIR_IMAGE; } else { type = MEDIA_DIR_DOCUMENT; } } FileLoaderPriorityQueue loaderQueue; int index = Utilities.clamp(operation.getDatacenterId() - 1, 4, 0); boolean isStory = parentObject instanceof TL_stories.StoryItem; if (operation.totalBytesCount > 20 * 1024 * 1024 || isStory) { loaderQueue = largeFilesQueue[index]; } else { loaderQueue = smallFilesQueue[index]; } String storeFileName = fileName; if (cacheType == 0 || cacheType == 10 || isStory) { if (documentId != 0) { String path = getFileDatabase().getPath(documentId, dcId, type, true); boolean customPath = false; if (path != null) { File file = new File(path); if (file.exists()) { customPath = true; storeFileName = file.getName(); storeDir = file.getParentFile(); } } if (!customPath) { storeFileName = fileName; storeDir = getDirectory(type); boolean saveCustomPath = false; if (isStory) { File newDir = getDirectory(MEDIA_DIR_STORIES); if (newDir != null) { storeDir = newDir; saveCustomPath = true; } } else if ((type == MEDIA_DIR_IMAGE || type == MEDIA_DIR_VIDEO) && canSaveToPublicStorage(parentObject)) { File newDir; if (type == MEDIA_DIR_IMAGE) { newDir = getDirectory(MEDIA_DIR_IMAGE_PUBLIC); } else { newDir = getDirectory(MEDIA_DIR_VIDEO_PUBLIC); } if (newDir != null) { storeDir = newDir; saveCustomPath = true; } } else if (!TextUtils.isEmpty(getDocumentFileName(document)) && canSaveAsFile(parentObject)) { storeFileName = getDocumentFileName(document); File newDir = getDirectory(MEDIA_DIR_FILES); if (newDir != null) { storeDir = newDir; saveCustomPath = true; } } if (saveCustomPath) { operation.pathSaveData = new FilePathDatabase.PathData(documentId, dcId, type); } } } else { storeDir = getDirectory(type); } } else if (cacheType == ImageLoader.CACHE_TYPE_ENCRYPTED) { operation.setEncryptFile(true); } operation.setPaths(currentAccount, fileName, loaderQueue, storeDir, tempDir, storeFileName); if (cacheType == 10) { operation.setIsPreloadVideoOperation(true); } final int finalType = type; FileLoadOperation.FileLoadOperationDelegate fileLoadOperationDelegate = new FileLoadOperation.FileLoadOperationDelegate() { @Override public void didPreFinishLoading(FileLoadOperation operation, File finalFile) { FileLoaderPriorityQueue queue = operation.getQueue(); fileLoaderQueue.postRunnable(() -> { operation.preFinished = true; queue.checkLoadingOperations(); }); } @Override public void didFinishLoadingFile(FileLoadOperation operation, File finalFile) { if (!operation.isPreloadVideoOperation() && operation.isPreloadFinished()) { checkDownloadQueue(operation, operation.getQueue(), 0); return; } FilePathDatabase.FileMeta fileMeta = getFileMetadataFromParent(currentAccount, parentObject); if (fileMeta != null) { getFileLoader().getFileDatabase().saveFileDialogId(finalFile, fileMeta); } if (parentObject instanceof MessageObject) { MessageObject messageObject = (MessageObject) parentObject; if (document != null && messageObject.putInDownloadsStore) { getDownloadController().onDownloadComplete(messageObject); } } if (!operation.isPreloadVideoOperation()) { loadOperationPathsUI.remove(fileName); if (delegate != null) { delegate.fileDidLoaded(fileName, finalFile, parentObject, finalType); } } checkDownloadQueue(operation, operation.getQueue(), 0); } @Override public void didFailedLoadingFile(FileLoadOperation operation, int reason) { loadOperationPathsUI.remove(fileName); checkDownloadQueue(operation, operation.getQueue()); if (delegate != null) { delegate.fileDidFailedLoad(fileName, reason); } if (document != null && parentObject instanceof MessageObject && reason == 0) { getDownloadController().onDownloadFail((MessageObject) parentObject, reason); } else if (reason == -1) { LaunchActivity.checkFreeDiscSpaceStatic(2); } } @Override public void didChangedLoadProgress(FileLoadOperation operation, long uploadedSize, long totalSize) { if (delegate != null) { delegate.fileLoadProgressChanged(operation, fileName, uploadedSize, totalSize); } } @Override public void saveFilePath(FilePathDatabase.PathData pathSaveData, File cacheFileFinal) { getFileDatabase().putPath(pathSaveData.id, pathSaveData.dc, pathSaveData.type, 0, cacheFileFinal != null ? cacheFileFinal.toString() : null); } @Override public boolean hasAnotherRefOnFile(String path) { return getFileDatabase().hasAnotherRefOnFile(path); } @Override public boolean isLocallyCreatedFile(String path) { return getFileDatabase().isLocallyCreated(path); } }; operation.setDelegate(fileLoadOperationDelegate); loadOperationPaths.put(finalFileName, operation); operation.setPriority(priority); if (stream != null) { operation.setStream(stream, streamPriority, streamOffset); } loaderQueue.add(operation); loaderQueue.checkLoadingOperations(operation.isStory && priority >= PRIORITY_HIGH); if (BuildVars.LOGS_ENABLED) { FileLog.d("create load operation fileName=" + finalFileName + " documentName=" + getDocumentFileName(document) + " size=" + AndroidUtilities.formatFileSize(operation.totalBytesCount) + " position in queue " + operation.getPositionInQueue() + " account=" + currentAccount); } return operation; } public static boolean canSaveAsFile(Object parentObject) { if (parentObject instanceof MessageObject) { MessageObject messageObject = (MessageObject) parentObject; if (!messageObject.isDocument() || messageObject.isRoundVideo() || messageObject.isVoice()) { return false; } return true; } return false; } private boolean canSaveToPublicStorage(Object parentObject) { if (BuildVars.NO_SCOPED_STORAGE) { return false; } FilePathDatabase.FileMeta metadata = getFileMetadataFromParent(currentAccount, parentObject); MessageObject messageObject = null; if (metadata != null) { int flag; long dialogId = metadata.dialogId; if (getMessagesController().isChatNoForwards(getMessagesController().getChat(-dialogId)) || DialogObject.isEncryptedDialog(dialogId)) { return false; } if (parentObject instanceof MessageObject) { messageObject = (MessageObject) parentObject; if (messageObject.isRoundVideo() || messageObject.isVoice() || messageObject.isAnyKindOfSticker() || messageObject.messageOwner.noforwards) { return false; } } else { if (metadata.messageType == MessageObject.TYPE_ROUND_VIDEO || metadata.messageType == MessageObject.TYPE_STICKER || metadata.messageType == MessageObject.TYPE_VOICE) { return false; } } if (dialogId >= 0) { flag = SharedConfig.SAVE_TO_GALLERY_FLAG_PEER; } else { if (ChatObject.isChannelAndNotMegaGroup(getMessagesController().getChat(-dialogId))) { flag = SharedConfig.SAVE_TO_GALLERY_FLAG_CHANNELS; } else { flag = SharedConfig.SAVE_TO_GALLERY_FLAG_GROUP; } } if (SaveToGallerySettingsHelper.needSave(flag, metadata, messageObject, currentAccount)) { return true; } } return false; } private void addOperationToQueue(FileLoadOperation operation, LinkedList<FileLoadOperation> queue) { int priority = operation.getPriority(); if (priority > 0) { int index = queue.size(); for (int a = 0, size = queue.size(); a < size; a++) { FileLoadOperation queuedOperation = queue.get(a); if (queuedOperation.getPriority() < priority) { index = a; break; } } queue.add(index, operation); } else { queue.add(operation); } } private void loadFile(final TLRPC.Document document, final SecureDocument secureDocument, final WebFile webDocument, TLRPC.TL_fileLocationToBeDeprecated location, final ImageLocation imageLocation, final Object parentObject, final String locationExt, final long locationSize, final int priority, final int cacheType) { String fileName; if (location != null) { fileName = getAttachFileName(location, locationExt); } else if (document != null) { fileName = getAttachFileName(document); } else if (webDocument != null) { fileName = getAttachFileName(webDocument); } else { fileName = null; } Runnable runnable = () -> loadFileInternal(document, secureDocument, webDocument, location, imageLocation, parentObject, locationExt, locationSize, priority, null, 0, false, cacheType); if (cacheType != 10 && !TextUtils.isEmpty(fileName) && !fileName.contains("" + Integer.MIN_VALUE)) { LoadOperationUIObject uiObject = new FileLoader.LoadOperationUIObject(); uiObject.loadInternalRunnable = runnable; loadOperationPathsUI.put(fileName, uiObject); } fileLoaderQueue.postRunnable(runnable); } protected FileLoadOperation loadStreamFile(final FileLoadOperationStream stream, final TLRPC.Document document, final ImageLocation location, final Object parentObject, final long offset, final boolean priority, int loadingPriority) { final CountDownLatch semaphore = new CountDownLatch(1); final FileLoadOperation[] result = new FileLoadOperation[1]; fileLoaderQueue.postRunnable(() -> { result[0] = loadFileInternal(document, null, null, document == null && location != null ? location.location : null, location, parentObject, document == null && location != null ? "mp4" : null, document == null && location != null ? location.currentSize : 0, loadingPriority, stream, offset, priority, document == null ? 1 : 0); semaphore.countDown(); }); awaitFileLoadOperation(semaphore, true); return result[0]; } /** * Necessary to wait of the FileLoadOperation object, despite the interruption of the thread. * Thread can be interrupted by {@link ImageLoader.CacheOutTask#cancel}. * For cases when two {@link ImageReceiver} require loading of the same file and the first {@link ImageReceiver} decides to cancel the operation. * For example, to autoplay a video after sending a message. */ private void awaitFileLoadOperation(CountDownLatch latch, boolean ignoreInterruption) { try { latch.await(); } catch (Exception e) { FileLog.e(e, false); if (ignoreInterruption) awaitFileLoadOperation(latch, false); } } private void checkDownloadQueue(FileLoadOperation operation, FileLoaderPriorityQueue queue) { checkDownloadQueue(operation, queue, 0); } private void checkDownloadQueue(FileLoadOperation operation, FileLoaderPriorityQueue queue, long delay) { fileLoaderQueue.postRunnable(() -> { if (queue.remove(operation)) { loadOperationPaths.remove(operation.getFileName()); queue.checkLoadingOperations(); } }, delay); } public void setDelegate(FileLoaderDelegate fileLoaderDelegate) { delegate = fileLoaderDelegate; } public static String getMessageFileName(TLRPC.Message message) { if (message == null) { return ""; } if (message instanceof TLRPC.TL_messageService) { if (message.action.photo != null) { ArrayList<TLRPC.PhotoSize> sizes = message.action.photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize()); if (sizeFull != null) { return getAttachFileName(sizeFull); } } } } else { if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaDocument) { return getAttachFileName(MessageObject.getMedia(message).document); } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaPhoto) { ArrayList<TLRPC.PhotoSize> sizes = MessageObject.getMedia(message).photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize(), false, null, true); if (sizeFull != null) { return getAttachFileName(sizeFull); } } } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaWebPage) { if (MessageObject.getMedia(message).webpage.document != null) { return getAttachFileName(MessageObject.getMedia(message).webpage.document); } else if (MessageObject.getMedia(message).webpage.photo != null) { ArrayList<TLRPC.PhotoSize> sizes = MessageObject.getMedia(message).webpage.photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize()); if (sizeFull != null) { return getAttachFileName(sizeFull); } } } } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaInvoice) { TLRPC.WebDocument document = ((TLRPC.TL_messageMediaInvoice) MessageObject.getMedia(message)).webPhoto; if (document != null) { return Utilities.MD5(document.url) + "." + ImageLoader.getHttpUrlExtension(document.url, getMimeTypePart(document.mime_type)); } } } return ""; } public File getPathToMessage(TLRPC.Message message) { return getPathToMessage(message, true); } public File getPathToMessage(TLRPC.Message message, boolean useFileDatabaseQueue) { if (message == null) { return new File(""); } if (message instanceof TLRPC.TL_messageService) { if (message.action.photo != null) { ArrayList<TLRPC.PhotoSize> sizes = message.action.photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize()); if (sizeFull != null) { return getPathToAttach(sizeFull, null, false, useFileDatabaseQueue); } } } } else { if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaDocument) { return getPathToAttach(MessageObject.getMedia(message).document, null, MessageObject.getMedia(message).ttl_seconds != 0, useFileDatabaseQueue); } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaPhoto) { ArrayList<TLRPC.PhotoSize> sizes = MessageObject.getMedia(message).photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize(), false, null, true); if (sizeFull != null) { return getPathToAttach(sizeFull, null, MessageObject.getMedia(message).ttl_seconds != 0, useFileDatabaseQueue); } } } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaWebPage) { if (MessageObject.getMedia(message).webpage.document != null) { return getPathToAttach(MessageObject.getMedia(message).webpage.document, null, false, useFileDatabaseQueue); } else if (MessageObject.getMedia(message).webpage.photo != null) { ArrayList<TLRPC.PhotoSize> sizes = MessageObject.getMedia(message).webpage.photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize()); if (sizeFull != null) { return getPathToAttach(sizeFull, null, false, useFileDatabaseQueue); } } } } else if (MessageObject.getMedia(message) instanceof TLRPC.TL_messageMediaInvoice) { return getPathToAttach(((TLRPC.TL_messageMediaInvoice) MessageObject.getMedia(message)).photo, null, true, useFileDatabaseQueue); } } return new File(""); } public File getPathToAttach(TLObject attach) { return getPathToAttach(attach, null, false); } public File getPathToAttach(TLObject attach, boolean forceCache) { return getPathToAttach(attach, null, forceCache); } public File getPathToAttach(TLObject attach, String ext, boolean forceCache) { return getPathToAttach(attach, null, ext, forceCache, true); } public File getPathToAttach(TLObject attach, String ext, boolean forceCache, boolean useFileDatabaseQueue) { return getPathToAttach(attach, null, ext, forceCache, useFileDatabaseQueue); } /** * Return real file name. Used before file.exist() */ public File getPathToAttach(TLObject attach, String size, String ext, boolean forceCache, boolean useFileDatabaseQueue) { File dir = null; long documentId = 0; int dcId = 0; int type = 0; if (forceCache) { dir = getDirectory(MEDIA_DIR_CACHE); } else { if (attach instanceof TLRPC.Document) { TLRPC.Document document = (TLRPC.Document) attach; if (!TextUtils.isEmpty(document.localPath)) { return new File(document.localPath); } if (document.key != null) { type = MEDIA_DIR_CACHE; } else { if (MessageObject.isVoiceDocument(document)) { type = MEDIA_DIR_AUDIO; } else if (MessageObject.isVideoDocument(document)) { type = MEDIA_DIR_VIDEO; } else { type = MEDIA_DIR_DOCUMENT; } } documentId = document.id; dcId = document.dc_id; dir = getDirectory(type); } else if (attach instanceof TLRPC.Photo) { TLRPC.PhotoSize photoSize = getClosestPhotoSizeWithSize(((TLRPC.Photo) attach).sizes, AndroidUtilities.getPhotoSize()); return getPathToAttach(photoSize, ext, false, useFileDatabaseQueue); } else if (attach instanceof TLRPC.PhotoSize) { TLRPC.PhotoSize photoSize = (TLRPC.PhotoSize) attach; if (photoSize instanceof TLRPC.TL_photoStrippedSize || photoSize instanceof TLRPC.TL_photoPathSize) { dir = null; } else if (photoSize.location == null || photoSize.location.key != null || photoSize.location.volume_id == Integer.MIN_VALUE && photoSize.location.local_id < 0 || photoSize.size < 0) { dir = getDirectory(type = MEDIA_DIR_CACHE); } else { dir = getDirectory(type = MEDIA_DIR_IMAGE); } documentId = photoSize.location.volume_id; dcId = photoSize.location.dc_id + (photoSize.location.local_id << 16); } else if (attach instanceof TLRPC.TL_videoSize) { TLRPC.TL_videoSize videoSize = (TLRPC.TL_videoSize) attach; if (videoSize.location == null || videoSize.location.key != null || videoSize.location.volume_id == Integer.MIN_VALUE && videoSize.location.local_id < 0 || videoSize.size < 0) { dir = getDirectory(type = MEDIA_DIR_CACHE); } else { dir = getDirectory(type = MEDIA_DIR_IMAGE); } documentId = videoSize.location.volume_id; dcId = videoSize.location.dc_id + (videoSize.location.local_id << 16); } else if (attach instanceof TLRPC.FileLocation) { TLRPC.FileLocation fileLocation = (TLRPC.FileLocation) attach; if (fileLocation.key != null || fileLocation.volume_id == Integer.MIN_VALUE && fileLocation.local_id < 0) { dir = getDirectory(MEDIA_DIR_CACHE); } else { documentId = fileLocation.volume_id; dcId = fileLocation.dc_id + (fileLocation.local_id << 16); dir = getDirectory(type = MEDIA_DIR_IMAGE); } } else if (attach instanceof TLRPC.UserProfilePhoto || attach instanceof TLRPC.ChatPhoto) { if (size == null) { size = "s"; } if ("s".equals(size)) { dir = getDirectory(MEDIA_DIR_CACHE); } else { dir = getDirectory(MEDIA_DIR_IMAGE); } } else if (attach instanceof WebFile) { WebFile document = (WebFile) attach; if (document.mime_type.startsWith("image/")) { dir = getDirectory(MEDIA_DIR_IMAGE); } else if (document.mime_type.startsWith("audio/")) { dir = getDirectory(MEDIA_DIR_AUDIO); } else if (document.mime_type.startsWith("video/")) { dir = getDirectory(MEDIA_DIR_VIDEO); } else { dir = getDirectory(MEDIA_DIR_DOCUMENT); } } else if (attach instanceof TLRPC.TL_secureFile || attach instanceof SecureDocument) { dir = getDirectory(MEDIA_DIR_CACHE); } } if (dir == null) { return new File(""); } if (documentId != 0) { String path = getInstance(UserConfig.selectedAccount).getFileDatabase().getPath(documentId, dcId, type, useFileDatabaseQueue); if (path != null) { return new File(path); } } return new File(dir, getAttachFileName(attach, ext)); } public FilePathDatabase getFileDatabase() { return filePathDatabase; } public static TLRPC.PhotoSize getClosestPhotoSizeWithSize(ArrayList<TLRPC.PhotoSize> sizes, int side) { return getClosestPhotoSizeWithSize(sizes, side, false); } public static TLRPC.PhotoSize getClosestPhotoSizeWithSize(ArrayList<TLRPC.PhotoSize> sizes, int side, boolean byMinSide) { return getClosestPhotoSizeWithSize(sizes, side, byMinSide, null, false); } public static TLRPC.PhotoSize getClosestPhotoSizeWithSize(ArrayList<TLRPC.PhotoSize> sizes, int side, boolean byMinSide, TLRPC.PhotoSize toIgnore, boolean ignoreStripped) { if (sizes == null || sizes.isEmpty()) { return null; } int lastSide = 0; TLRPC.PhotoSize closestObject = null; for (int a = 0; a < sizes.size(); a++) { TLRPC.PhotoSize obj = sizes.get(a); if (obj == null || obj == toIgnore || obj instanceof TLRPC.TL_photoSizeEmpty || obj instanceof TLRPC.TL_photoPathSize || ignoreStripped && obj instanceof TLRPC.TL_photoStrippedSize) { continue; } if (byMinSide) { int currentSide = Math.min(obj.h, obj.w); if ( closestObject == null || side > 100 && closestObject.location != null && closestObject.location.dc_id == Integer.MIN_VALUE || obj instanceof TLRPC.TL_photoCachedSize || side > lastSide && lastSide < currentSide ) { closestObject = obj; lastSide = currentSide; } } else { int currentSide = Math.max(obj.w, obj.h); 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; } } } return closestObject; } public static TLRPC.VideoSize getClosestVideoSizeWithSize(ArrayList<TLRPC.VideoSize> sizes, int side) { return getClosestVideoSizeWithSize(sizes, side, false); } public static TLRPC.VideoSize getClosestVideoSizeWithSize(ArrayList<TLRPC.VideoSize> sizes, int side, boolean byMinSide) { return getClosestVideoSizeWithSize(sizes, side, byMinSide, false); } public static TLRPC.VideoSize getClosestVideoSizeWithSize(ArrayList<TLRPC.VideoSize> sizes, int side, boolean byMinSide, boolean ignoreStripped) { if (sizes == null || sizes.isEmpty()) { return null; } int lastSide = 0; TLRPC.VideoSize closestObject = null; for (int a = 0; a < sizes.size(); a++) { TLRPC.VideoSize obj = sizes.get(a); if (obj == null || obj instanceof TLRPC.TL_videoSizeEmojiMarkup || obj instanceof TLRPC.TL_videoSizeStickerMarkup) { continue; } if (byMinSide) { int currentSide = Math.min(obj.h, obj.w); if (closestObject == null || side > 100 && closestObject.location != null && closestObject.location.dc_id == Integer.MIN_VALUE || side > lastSide && lastSide < currentSide) { closestObject = obj; lastSide = currentSide; } } else { int currentSide = Math.max(obj.w, obj.h); if ( closestObject == null || side > 100 && closestObject.location != null && closestObject.location.dc_id == Integer.MIN_VALUE || currentSide <= side && lastSide < currentSide ) { closestObject = obj; lastSide = currentSide; } } } return closestObject; } public static TLRPC.TL_photoPathSize getPathPhotoSize(ArrayList<TLRPC.PhotoSize> sizes) { if (sizes == null || sizes.isEmpty()) { return null; } for (int a = 0; a < sizes.size(); a++) { TLRPC.PhotoSize obj = sizes.get(a); if (obj instanceof TLRPC.TL_photoPathSize) { continue; } return (TLRPC.TL_photoPathSize) obj; } return null; } public static String getFileExtension(File file) { String name = file.getName(); try { return name.substring(name.lastIndexOf('.') + 1); } catch (Exception e) { return ""; } } public static String fixFileName(String fileName) { if (fileName != null) { fileName = fileName.replaceAll("[\u0001-\u001f<>\u202E:\"/\\\\|?*\u007f]+", "").trim(); } return fileName; } public static String getDocumentFileName(TLRPC.Document document) { if (document == null) { return null; } if (document.file_name_fixed != null) { return document.file_name_fixed; } String fileName = null; if (document != null) { if (document.file_name != null) { fileName = document.file_name; } else { for (int a = 0; a < document.attributes.size(); a++) { TLRPC.DocumentAttribute documentAttribute = document.attributes.get(a); if (documentAttribute instanceof TLRPC.TL_documentAttributeFilename) { fileName = documentAttribute.file_name; } } } } fileName = fixFileName(fileName); return fileName != null ? fileName : ""; } public static String getMimeTypePart(String mime) { int index; if ((index = mime.lastIndexOf('/')) != -1) { return mime.substring(index + 1); } return ""; } public static String getExtensionByMimeType(String mime) { if (mime != null) { switch (mime) { case "video/mp4": return ".mp4"; case "video/x-matroska": return ".mkv"; case "audio/ogg": return ".ogg"; } } return ""; } public static File getInternalCacheDir() { return ApplicationLoader.applicationContext.getCacheDir(); } public static String getDocumentExtension(TLRPC.Document document) { String fileName = getDocumentFileName(document); int idx = fileName.lastIndexOf('.'); String ext = null; if (idx != -1) { ext = fileName.substring(idx + 1); } if (ext == null || ext.length() == 0) { ext = document.mime_type; } if (ext == null) { ext = ""; } ext = ext.toUpperCase(); return ext; } public static String getAttachFileName(TLObject attach) { return getAttachFileName(attach, null); } public static String getAttachFileName(TLObject attach, String ext) { return getAttachFileName(attach, null, ext); } /** * file hash. contains docId, dcId, ext. */ public static String getAttachFileName(TLObject attach, String size, String ext) { if (attach instanceof TLRPC.Document) { TLRPC.Document document = (TLRPC.Document) attach; String docExt; docExt = getDocumentFileName(document); int idx; if ((idx = docExt.lastIndexOf('.')) == -1) { docExt = ""; } else { docExt = docExt.substring(idx); } if (docExt.length() <= 1) { docExt = getExtensionByMimeType(document.mime_type); } if (docExt.length() > 1) { return document.dc_id + "_" + document.id + docExt; } else { return document.dc_id + "_" + document.id; } } else if (attach instanceof SecureDocument) { SecureDocument secureDocument = (SecureDocument) attach; return secureDocument.secureFile.dc_id + "_" + secureDocument.secureFile.id + ".jpg"; } else if (attach instanceof TLRPC.TL_secureFile) { TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) attach; return secureFile.dc_id + "_" + secureFile.id + ".jpg"; } else if (attach instanceof WebFile) { WebFile document = (WebFile) attach; return Utilities.MD5(document.url) + "." + ImageLoader.getHttpUrlExtension(document.url, getMimeTypePart(document.mime_type)); } else if (attach instanceof TLRPC.PhotoSize) { TLRPC.PhotoSize photo = (TLRPC.PhotoSize) attach; if (photo.location == null || photo.location instanceof TLRPC.TL_fileLocationUnavailable) { return ""; } return photo.location.volume_id + "_" + photo.location.local_id + "." + (ext != null ? ext : "jpg"); } else if (attach instanceof TLRPC.TL_videoSize) { TLRPC.TL_videoSize video = (TLRPC.TL_videoSize) attach; if (video.location == null || video.location instanceof TLRPC.TL_fileLocationUnavailable) { return ""; } return video.location.volume_id + "_" + video.location.local_id + "." + (ext != null ? ext : "mp4"); } else if (attach instanceof TLRPC.FileLocation) { if (attach instanceof TLRPC.TL_fileLocationUnavailable) { return ""; } TLRPC.FileLocation location = (TLRPC.FileLocation) attach; return location.volume_id + "_" + location.local_id + "." + (ext != null ? ext : "jpg"); } else if (attach instanceof TLRPC.UserProfilePhoto) { if (size == null) { size = "s"; } TLRPC.UserProfilePhoto location = (TLRPC.UserProfilePhoto) attach; if (location.photo_small != null) { if ("s".equals(size)) { return getAttachFileName(location.photo_small, ext); } else { return getAttachFileName(location.photo_big, ext); } } else { return location.photo_id + "_" + size + "." + (ext != null ? ext : "jpg"); } } else if (attach instanceof TLRPC.ChatPhoto) { TLRPC.ChatPhoto location = (TLRPC.ChatPhoto) attach; if (location.photo_small != null) { if ("s".equals(size)) { return getAttachFileName(location.photo_small, ext); } else { return getAttachFileName(location.photo_big, ext); } } else { return location.photo_id + "_" + size + "." + (ext != null ? ext : "jpg"); } } return ""; } public void deleteFiles(final ArrayList<File> files, final int type) { if (files == null || files.isEmpty()) { return; } fileLoaderQueue.postRunnable(() -> { for (int a = 0; a < files.size(); a++) { File file = files.get(a); File encrypted = new File(file.getAbsolutePath() + ".enc"); if (encrypted.exists()) { try { if (!encrypted.delete()) { encrypted.deleteOnExit(); } } catch (Exception e) { FileLog.e(e); } try { File key = new File(FileLoader.getInternalCacheDir(), file.getName() + ".enc.key"); if (!key.delete()) { key.deleteOnExit(); } } catch (Exception e) { FileLog.e(e); } } else if (file.exists()) { try { if (!file.delete()) { file.deleteOnExit(); } } catch (Exception e) { FileLog.e(e); } } try { File qFile = new File(file.getParentFile(), "q_" + file.getName()); if (qFile.exists()) { if (!qFile.delete()) { qFile.deleteOnExit(); } } } catch (Exception e) { FileLog.e(e); } } if (type == 2) { ImageLoader.getInstance().clearMemory(); } }); } public static boolean isVideoMimeType(String mime) { return "video/mp4".equals(mime) || SharedConfig.streamMkv && "video/x-matroska".equals(mime); } public static boolean copyFile(InputStream sourceFile, File destFile) throws IOException { return copyFile(sourceFile, destFile, -1); } public static boolean copyFile(InputStream sourceFile, File destFile, int maxSize) throws IOException { FileOutputStream out = new FileOutputStream(destFile); byte[] buf = new byte[4096]; int len; int totalLen = 0; while ((len = sourceFile.read(buf)) > 0) { Thread.yield(); out.write(buf, 0, len); totalLen += len; if (maxSize > 0 && totalLen >= maxSize) { break; } } out.getFD().sync(); out.close(); return true; } public static boolean isSamePhoto(TLObject photo1, TLObject photo2) { if (photo1 == null && photo2 != null || photo1 != null && photo2 == null) { return false; } if (photo1 == null && photo2 == null) { return true; } if (photo1.getClass() != photo2.getClass()) { return false; } if (photo1 instanceof TLRPC.UserProfilePhoto) { TLRPC.UserProfilePhoto p1 = (TLRPC.UserProfilePhoto) photo1; TLRPC.UserProfilePhoto p2 = (TLRPC.UserProfilePhoto) photo2; return p1.photo_id == p2.photo_id; } else if (photo1 instanceof TLRPC.ChatPhoto) { TLRPC.ChatPhoto p1 = (TLRPC.ChatPhoto) photo1; TLRPC.ChatPhoto p2 = (TLRPC.ChatPhoto) photo2; return p1.photo_id == p2.photo_id; } return false; } public static boolean isSamePhoto(TLRPC.FileLocation location, TLRPC.Photo photo) { if (location == null || !(photo instanceof TLRPC.TL_photo)) { return false; } for (int b = 0, N = photo.sizes.size(); b < N; b++) { TLRPC.PhotoSize size = photo.sizes.get(b); if (size.location != null && size.location.local_id == location.local_id && size.location.volume_id == location.volume_id) { return true; } } if (-location.volume_id == photo.id) { return true; } return false; } public static long getPhotoId(TLObject object) { if (object instanceof TLRPC.Photo) { return ((TLRPC.Photo) object).id; } else if (object instanceof TLRPC.ChatPhoto) { return ((TLRPC.ChatPhoto) object).photo_id; } else if (object instanceof TLRPC.UserProfilePhoto) { return ((TLRPC.UserProfilePhoto) object).photo_id; } return 0; } public void getCurrentLoadingFiles(ArrayList<MessageObject> currentLoadingFiles) { currentLoadingFiles.clear(); currentLoadingFiles.addAll(getDownloadController().downloadingFiles); for (int i = 0; i < currentLoadingFiles.size(); i++) { currentLoadingFiles.get(i).isDownloadingFile = true; } } public void getRecentLoadingFiles(ArrayList<MessageObject> recentLoadingFiles) { recentLoadingFiles.clear(); recentLoadingFiles.addAll(getDownloadController().recentDownloadingFiles); for (int i = 0; i < recentLoadingFiles.size(); i++) { recentLoadingFiles.get(i).isDownloadingFile = true; } } public void checkCurrentDownloadsFiles() { ArrayList<MessageObject> messagesToRemove = new ArrayList<>(); ArrayList<MessageObject> messageObjects = new ArrayList<>(getDownloadController().recentDownloadingFiles); for (int i = 0; i < messageObjects.size(); i++) { messageObjects.get(i).checkMediaExistance(); if (messageObjects.get(i).mediaExists) { messagesToRemove.add(messageObjects.get(i)); } } if (!messagesToRemove.isEmpty()) { AndroidUtilities.runOnUIThread(() -> { getDownloadController().recentDownloadingFiles.removeAll(messagesToRemove); getNotificationCenter().postNotificationName(NotificationCenter.onDownloadingFilesChanged); }); } } /** * optimezed for bulk messages */ public void checkMediaExistance(ArrayList<MessageObject> messageObjects) { getFileDatabase().checkMediaExistance(messageObjects); } public interface FileResolver { File getFile(); } public void clearRecentDownloadedFiles() { getDownloadController().clearRecentDownloadedFiles(); } public void clearFilePaths() { filePathDatabase.clear(); } public static boolean checkUploadFileSize(int currentAccount, long length) { boolean premium = AccountInstance.getInstance(currentAccount).getUserConfig().isPremium(); if (length < DEFAULT_MAX_FILE_SIZE || (length < DEFAULT_MAX_FILE_SIZE_PREMIUM && premium)) { return true; } return false; } private static class LoadOperationUIObject { Runnable loadInternalRunnable; } public static byte[] longToBytes(long x) { ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); buffer.putLong(x); return buffer.array(); } public static long bytesToLong(byte[] bytes) { long l = 0; for (int i = 0; i < 8; i++) { l <<= 8; l ^= bytes[i] & 0xFF; } return l; } Runnable dumpFilesQueueRunnable = () -> { for (int i = 0; i < smallFilesQueue.length; i++) { if (smallFilesQueue[i].getCount() > 0 || largeFilesQueue[i].getCount() > 0) { FileLog.d("download queue: dc" + (i + 1) + " account=" + currentAccount + " small_operations=" + smallFilesQueue[i].getCount() + " large_operations=" + largeFilesQueue[i].getCount()); // if (!largeFilesQueue[i].allOperations.isEmpty()) { // largeFilesQueue[i].allOperations.get(0).dump(); // } } } dumpFilesQueue(); }; public void dumpFilesQueue() { if (!BuildVars.LOGS_ENABLED) { return; } fileLoaderQueue.cancelRunnable(dumpFilesQueueRunnable); fileLoaderQueue.postRunnable(dumpFilesQueueRunnable, 10000); } }
TharukRenuja/Telegram
TMessagesProj/src/main/java/org/telegram/messenger/FileLoader.java
41,714
package org.telegram.messenger; import android.os.Looper; import android.util.LongSparseArray; import org.telegram.SQLite.SQLiteCursor; import org.telegram.SQLite.SQLiteDatabase; import org.telegram.SQLite.SQLiteException; import org.telegram.SQLite.SQLitePreparedStatement; import org.telegram.ui.Storage.CacheModel; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; public class FilePathDatabase { private final DispatchQueue dispatchQueue; private final int currentAccount; private SQLiteDatabase database; private File cacheFile; private File shmCacheFile; private final static int LAST_DB_VERSION = 4; private final static String DATABASE_NAME = "file_to_path"; private final static String DATABASE_BACKUP_NAME = "file_to_path_backup"; public final static int MESSAGE_TYPE_VIDEO_MESSAGE = 0; private final FileMeta metaTmp = new FileMeta(); public FilePathDatabase(int currentAccount) { this.currentAccount = currentAccount; dispatchQueue = new DispatchQueue("files_database_queue_" + currentAccount); dispatchQueue.postRunnable(() -> { createDatabase(0, false); }); } public void createDatabase(int tryCount, boolean fromBackup) { File filesDir = ApplicationLoader.getFilesDirFixed(); if (currentAccount != 0) { filesDir = new File(filesDir, "account" + currentAccount + "/"); filesDir.mkdirs(); } cacheFile = new File(filesDir, DATABASE_NAME + ".db"); shmCacheFile = new File(filesDir, DATABASE_NAME + ".db-shm"); boolean createTable = false; if (!cacheFile.exists()) { createTable = true; } try { database = new SQLiteDatabase(cacheFile.getPath()); database.executeFast("PRAGMA secure_delete = ON").stepThis().dispose(); database.executeFast("PRAGMA temp_store = MEMORY").stepThis().dispose(); if (createTable) { database.executeFast("CREATE TABLE paths(document_id INTEGER, dc_id INTEGER, type INTEGER, path TEXT, PRIMARY KEY(document_id, dc_id, type));").stepThis().dispose(); database.executeFast("CREATE INDEX IF NOT EXISTS path_in_paths ON paths(path);").stepThis().dispose(); database.executeFast("CREATE TABLE paths_by_dialog_id(path TEXT PRIMARY KEY, dialog_id INTEGER, message_id INTEGER, message_type INTEGER);").stepThis().dispose(); database.executeFast("PRAGMA user_version = " + LAST_DB_VERSION).stepThis().dispose(); } else { int version = database.executeInt("PRAGMA user_version"); if (BuildVars.LOGS_ENABLED) { FileLog.d("current files db version = " + version); } if (version == 0) { throw new Exception("malformed"); } migrateDatabase(version); //migration } if (!fromBackup) { createBackup(); } FileLog.d("files db created from_backup= " + fromBackup); } catch (Exception e) { if (tryCount < 4) { if (!fromBackup && restoreBackup()) { createDatabase(tryCount + 1, true); return; } else { cacheFile.delete(); shmCacheFile.delete(); createDatabase(tryCount + 1, false); } } if (BuildVars.DEBUG_VERSION) { FileLog.e(e); } } } private void migrateDatabase(int version) throws SQLiteException { if (version == 1) { database.executeFast("CREATE INDEX IF NOT EXISTS path_in_paths ON paths(path);").stepThis().dispose(); database.executeFast("PRAGMA user_version = " + 2).stepThis().dispose(); version = 2; } if (version == 2) { database.executeFast("CREATE TABLE paths_by_dialog_id(path TEXT PRIMARY KEY, dialog_id INTEGER);").stepThis().dispose(); database.executeFast("PRAGMA user_version = " + 3).stepThis().dispose(); version = 3; } if (version == 3) { database.executeFast("ALTER TABLE paths_by_dialog_id ADD COLUMN message_id INTEGER default 0").stepThis().dispose(); database.executeFast("ALTER TABLE paths_by_dialog_id ADD COLUMN message_type INTEGER default 0").stepThis().dispose(); database.executeFast("PRAGMA user_version = " + 4).stepThis().dispose(); } } private void createBackup() { File filesDir = ApplicationLoader.getFilesDirFixed(); if (currentAccount != 0) { filesDir = new File(filesDir, "account" + currentAccount + "/"); filesDir.mkdirs(); } File backupCacheFile = new File(filesDir, DATABASE_BACKUP_NAME + ".db"); try { AndroidUtilities.copyFile(cacheFile, backupCacheFile); FileLog.d("file db backup created " + backupCacheFile.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } } private boolean restoreBackup() { File filesDir = ApplicationLoader.getFilesDirFixed(); if (currentAccount != 0) { filesDir = new File(filesDir, "account" + currentAccount + "/"); filesDir.mkdirs(); } File backupCacheFile = new File(filesDir, DATABASE_BACKUP_NAME + ".db"); if (!backupCacheFile.exists()) { return false; } try { return AndroidUtilities.copyFile(backupCacheFile, cacheFile); } catch (IOException e) { FileLog.e(e); } return false; } public String getPath(long documentId, int dc, int type, boolean useQueue) { if (useQueue) { if (BuildVars.DEBUG_VERSION) { if (dispatchQueue.getHandler() != null && Thread.currentThread() == dispatchQueue.getHandler().getLooper().getThread()) { throw new RuntimeException("Error, lead to infinity loop"); } } CountDownLatch syncLatch = new CountDownLatch(1); String[] res = new String[1]; dispatchQueue.postRunnable(() -> { if (database != null) { SQLiteCursor cursor = null; try { cursor = database.queryFinalized("SELECT path FROM paths WHERE document_id = " + documentId + " AND dc_id = " + dc + " AND type = " + type); if (cursor.next()) { res[0] = cursor.stringValue(0); if (BuildVars.DEBUG_VERSION) { FileLog.d("get file path id=" + documentId + " dc=" + dc + " type=" + type + " path=" + res[0]); } } } catch (SQLiteException e) { FileLog.e(e); } finally { if (cursor != null) { cursor.dispose(); } } } syncLatch.countDown(); }); try { syncLatch.await(); } catch (Exception ignore) { } return res[0]; } else { if (database == null) { return null; } SQLiteCursor cursor = null; String res = null; try { cursor = database.queryFinalized("SELECT path FROM paths WHERE document_id = " + documentId + " AND dc_id = " + dc + " AND type = " + type); if (cursor.next()) { res = cursor.stringValue(0); if (BuildVars.DEBUG_VERSION) { FileLog.d("get file path id=" + documentId + " dc=" + dc + " type=" + type + " path=" + res); } } } catch (SQLiteException e) { FileLog.e(e); } finally { if (cursor != null) { cursor.dispose(); } } return res; } } public void putPath(long id, int dc, int type, String path) { dispatchQueue.postRunnable(() -> { if (BuildVars.DEBUG_VERSION) { FileLog.d("put file path id=" + id + " dc=" + dc + " type=" + type + " path=" + path); } if (database == null) { return; } SQLitePreparedStatement state = null; SQLitePreparedStatement deleteState = null; try { if (path != null) { deleteState = database.executeFast("DELETE FROM paths WHERE path = ?"); deleteState.bindString(1, path); deleteState.step(); state = database.executeFast("REPLACE INTO paths VALUES(?, ?, ?, ?)"); state.requery(); state.bindLong(1, id); state.bindInteger(2, dc); state.bindInteger(3, type); state.bindString(4, path); state.step(); state.dispose(); } else { database.executeFast("DELETE FROM paths WHERE document_id = " + id + " AND dc_id = " + dc + " AND type = " + type).stepThis().dispose(); } } catch (SQLiteException e) { FileLog.e(e); } finally { if (deleteState != null) { deleteState.dispose(); } if (state != null) { state.dispose(); } } }); } public void checkMediaExistance(ArrayList<MessageObject> messageObjects) { if (messageObjects.isEmpty()) { return; } ArrayList<MessageObject> arrayListFinal = new ArrayList<>(messageObjects); CountDownLatch syncLatch = new CountDownLatch(1); long time = System.currentTimeMillis(); dispatchQueue.postRunnable(() -> { try { for (int i = 0; i < arrayListFinal.size(); i++) { MessageObject messageObject = arrayListFinal.get(i); messageObject.checkMediaExistance(false); } } catch (Exception e) { e.printStackTrace(); } syncLatch.countDown(); }); try { syncLatch.await(); } catch (InterruptedException e) { FileLog.e(e); } FileLog.d("checkMediaExistance size=" + messageObjects.size() + " time=" + (System.currentTimeMillis() - time)); if (BuildVars.DEBUG_VERSION) { if (Thread.currentThread() == Looper.getMainLooper().getThread()) { FileLog.e(new Exception("warning, not allowed in main thread")); } } } public void clear() { dispatchQueue.postRunnable(() -> { try { database.executeFast("DELETE FROM paths WHERE 1").stepThis().dispose(); database.executeFast("DELETE FROM paths_by_dialog_id WHERE 1").stepThis().dispose(); } catch (Exception e) { FileLog.e(e); } }); } public boolean hasAnotherRefOnFile(String path) { CountDownLatch syncLatch = new CountDownLatch(1); boolean[] res = new boolean[]{false}; dispatchQueue.postRunnable(() -> { try { SQLiteCursor cursor = database.queryFinalized("SELECT document_id FROM paths WHERE path = '" + path + "'"); if (cursor.next()) { res[0] = true; } } catch (Exception e) { FileLog.e(e); } syncLatch.countDown(); }); try { syncLatch.await(); } catch (InterruptedException e) { FileLog.e(e); } return res[0]; } public void saveFileDialogId(File file,FileMeta fileMeta) { if (file == null || fileMeta == null) { return; } dispatchQueue.postRunnable(() -> { SQLitePreparedStatement state = null; try { state = database.executeFast("REPLACE INTO paths_by_dialog_id VALUES(?, ?, ?, ?)"); state.requery(); state.bindString(1, shield(file.getPath())); state.bindLong(2, fileMeta.dialogId); state.bindInteger(3, fileMeta.messageId); state.bindInteger(4, fileMeta.messageType); state.step(); } catch (Exception e) { FileLog.e(e); } finally { if (state != null) { state.dispose(); } } }); } public FileMeta getFileDialogId(File file, FileMeta metaTmp) { if (file == null) { return null; } if (metaTmp == null) { metaTmp = this.metaTmp; } long dialogId = 0; int messageId = 0; int messageType = 0; SQLiteCursor cursor = null; try { cursor = database.queryFinalized("SELECT dialog_id, message_id, message_type FROM paths_by_dialog_id WHERE path = '" + shield(file.getPath()) + "'"); if (cursor.next()) { dialogId = cursor.longValue(0); messageId = cursor.intValue(1); messageType = cursor.intValue(2); } } catch (Exception e) { FileLog.e(e); } finally { if (cursor != null) { cursor.dispose(); } } metaTmp.dialogId = dialogId; metaTmp.messageId = messageId; metaTmp.messageType = messageType; return metaTmp; } private String shield(String path) { return path.replace("'","").replace("\"",""); } public DispatchQueue getQueue() { return dispatchQueue; } public void removeFiles(List<CacheModel.FileInfo> filesToRemove) { dispatchQueue.postRunnable(() -> { try { database.beginTransaction(); for (int i = 0; i < filesToRemove.size(); i++) { database.executeFast("DELETE FROM paths_by_dialog_id WHERE path = '" + shield(filesToRemove.get(i).file.getPath()) + "'").stepThis().dispose(); } } catch (Exception e) { FileLog.e(e); } finally { database.commitTransaction(); } }); } public LongSparseArray<ArrayList<CacheByChatsController.KeepMediaFile>> lookupFiles(ArrayList<? extends CacheByChatsController.KeepMediaFile> keepMediaFiles) { CountDownLatch syncLatch = new CountDownLatch(1); LongSparseArray<ArrayList<CacheByChatsController.KeepMediaFile>> filesByDialogId = new LongSparseArray<>(); dispatchQueue.postRunnable(() -> { try { FileMeta fileMetaTmp = new FileMeta(); for (int i = 0; i < keepMediaFiles.size(); i++) { FileMeta fileMeta = getFileDialogId(keepMediaFiles.get(i).file, fileMetaTmp); if (fileMeta != null && fileMeta.dialogId != 0) { ArrayList<CacheByChatsController.KeepMediaFile> list = filesByDialogId.get(fileMeta.dialogId); if (list == null) { list = new ArrayList<>(); filesByDialogId.put(fileMeta.dialogId, list); } list.add(keepMediaFiles.get(i)); } } } catch (Exception e) { FileLog.e(e); } syncLatch.countDown(); }); try { syncLatch.await(); } catch (InterruptedException e) { FileLog.e(e); } return filesByDialogId; } public static class PathData { public final long id; public final int dc; public final int type; public PathData(long documentId, int dcId, int type) { this.id = documentId; this.dc = dcId; this.type = type; } } public static class FileMeta { public long dialogId; public int messageId; public int messageType; public long messageSize; } }
dawitys/Telegram
TMessagesProj/src/main/java/org/telegram/messenger/FilePathDatabase.java
41,715
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.ui.Cells; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.text.Layout; import android.text.StaticLayout; import android.text.TextUtils; import android.util.Property; import android.view.Gravity; import android.view.MotionEvent; import android.view.SoundEffectConstants; import android.view.accessibility.AccessibilityNodeInfo; import android.view.animation.AccelerateInterpolator; import android.widget.FrameLayout; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.DocumentObject; import org.telegram.messenger.DownloadController; import org.telegram.messenger.Emoji; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.ImageLoader; import org.telegram.messenger.ImageLocation; import org.telegram.messenger.ImageReceiver; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MediaController; import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessagesController; import org.telegram.messenger.R; import org.telegram.messenger.SharedConfig; import org.telegram.messenger.SvgHelper; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; import org.telegram.messenger.WebFile; import org.telegram.tgnet.TLRPC; import org.telegram.ui.Components.AnimatedFloat; import org.telegram.ui.Components.AnimationProperties; import org.telegram.ui.Components.ButtonBounce; import org.telegram.ui.Components.CheckBox2; import org.telegram.ui.Components.CubicBezierInterpolator; import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.LetterDrawable; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.Components.MediaActionDrawable; import org.telegram.ui.Components.RadialProgress2; import org.telegram.ui.PhotoViewer; import java.io.File; import java.util.ArrayList; import java.util.Locale; public class ContextLinkCell extends FrameLayout implements DownloadController.FileDownloadProgressListener { private final static int DOCUMENT_ATTACH_TYPE_NONE = 0; private final static int DOCUMENT_ATTACH_TYPE_DOCUMENT = 1; private final static int DOCUMENT_ATTACH_TYPE_GIF = 2; private final static int DOCUMENT_ATTACH_TYPE_AUDIO = 3; private final static int DOCUMENT_ATTACH_TYPE_VIDEO = 4; private final static int DOCUMENT_ATTACH_TYPE_MUSIC = 5; private final static int DOCUMENT_ATTACH_TYPE_STICKER = 6; private final static int DOCUMENT_ATTACH_TYPE_PHOTO = 7; private final static int DOCUMENT_ATTACH_TYPE_GEO = 8; public interface ContextLinkCellDelegate { void didPressedImage(ContextLinkCell cell); } private ImageReceiver linkImageView; private boolean drawLinkImageView; private LetterDrawable letterDrawable; private int currentAccount = UserConfig.selectedAccount; private Object parentObject; private Theme.ResourcesProvider resourcesProvider; private boolean needDivider; private boolean buttonPressed; private boolean needShadow; private boolean canPreviewGif; private boolean isKeyboard; private boolean isForceGif; private int linkY; private StaticLayout linkLayout; private int titleY = AndroidUtilities.dp(7); private StaticLayout titleLayout; private int descriptionY = AndroidUtilities.dp(27); private StaticLayout descriptionLayout; private TLRPC.BotInlineResult inlineResult; private TLRPC.User inlineBot; private TLRPC.Document documentAttach; private int currentDate; private TLRPC.Photo photoAttach; private TLRPC.PhotoSize currentPhotoObject; private int documentAttachType; private boolean mediaWebpage; private MessageObject currentMessageObject; private AnimatorSet animator; private Paint backgroundPaint; private int TAG; private int buttonState; private RadialProgress2 radialProgress; private boolean scaled; private static AccelerateInterpolator interpolator = new AccelerateInterpolator(0.5f); private boolean hideLoadProgress; private CheckBox2 checkBox; private ContextLinkCellDelegate delegate; private ButtonBounce buttonBounce; public ContextLinkCell(Context context) { this(context, false, null); } public ContextLinkCell(Context context, boolean needsCheckBox) { this(context, needsCheckBox, null); } public ContextLinkCell(Context context, boolean needsCheckBox, Theme.ResourcesProvider resourcesProvider) { super(context); this.resourcesProvider = resourcesProvider; linkImageView = new ImageReceiver(this); linkImageView.setAllowLoadingOnAttachedOnly(true); linkImageView.setLayerNum(1); linkImageView.setUseSharedAnimationQueue(true); letterDrawable = new LetterDrawable(resourcesProvider, LetterDrawable.STYLE_DEFAULT); radialProgress = new RadialProgress2(this); TAG = DownloadController.getInstance(currentAccount).generateObserverTag(); setFocusable(true); if (needsCheckBox) { backgroundPaint = new Paint(); backgroundPaint.setColor(Theme.getColor(Theme.key_sharedMedia_photoPlaceholder, resourcesProvider)); checkBox = new CheckBox2(context, 21, resourcesProvider); checkBox.setVisibility(INVISIBLE); checkBox.setColor(-1, Theme.key_sharedMedia_photoPlaceholder, Theme.key_checkboxCheck); checkBox.setDrawUnchecked(false); checkBox.setDrawBackgroundAsArc(1); addView(checkBox, LayoutHelper.createFrame(24, 24, Gravity.RIGHT | Gravity.TOP, 0, 1, 1, 0)); } setWillNotDraw(false); } public void allowButtonBounce(boolean allow) { if (allow != (buttonBounce != null)) { buttonBounce = allow ? new ButtonBounce(this, 1f, 3f).setReleaseDelay(120L) : null; } } @SuppressLint("DrawAllocation") @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { drawLinkImageView = false; descriptionLayout = null; titleLayout = null; linkLayout = null; currentPhotoObject = null; linkY = AndroidUtilities.dp(27); if (inlineResult == null && documentAttach == null) { setMeasuredDimension(AndroidUtilities.dp(100), AndroidUtilities.dp(100)); return; } int viewWidth = MeasureSpec.getSize(widthMeasureSpec); int maxWidth = viewWidth - AndroidUtilities.dp(AndroidUtilities.leftBaseline) - AndroidUtilities.dp(8); TLRPC.PhotoSize currentPhotoObjectThumb = null; ArrayList<TLRPC.PhotoSize> photoThumbs = null; WebFile webFile = null; TLRPC.TL_webDocument webDocument = null; String urlLocation = null; if (documentAttach != null) { photoThumbs = new ArrayList<>(documentAttach.thumbs); } else if (inlineResult != null && inlineResult.photo != null) { photoThumbs = new ArrayList<>(inlineResult.photo.sizes); } if (!mediaWebpage && inlineResult != null) { if (inlineResult.title != null) { try { int width = (int) Math.ceil(Theme.chat_contextResult_titleTextPaint.measureText(inlineResult.title)); CharSequence titleFinal = TextUtils.ellipsize(Emoji.replaceEmoji(inlineResult.title.replace('\n', ' '), Theme.chat_contextResult_titleTextPaint.getFontMetricsInt(), AndroidUtilities.dp(15), false), Theme.chat_contextResult_titleTextPaint, Math.min(width, maxWidth), TextUtils.TruncateAt.END); titleLayout = new StaticLayout(titleFinal, Theme.chat_contextResult_titleTextPaint, maxWidth + AndroidUtilities.dp(4), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); } catch (Exception e) { FileLog.e(e); } letterDrawable.setTitle(inlineResult.title); } if (inlineResult.description != null) { try { descriptionLayout = ChatMessageCell.generateStaticLayout(Emoji.replaceEmoji(inlineResult.description, Theme.chat_contextResult_descriptionTextPaint.getFontMetricsInt(), AndroidUtilities.dp(13), false), Theme.chat_contextResult_descriptionTextPaint, maxWidth, maxWidth, 0, 3); if (descriptionLayout.getLineCount() > 0) { linkY = descriptionY + descriptionLayout.getLineBottom(descriptionLayout.getLineCount() - 1) + AndroidUtilities.dp(1); } } catch (Exception e) { FileLog.e(e); } } if (inlineResult.url != null) { try { int width = (int) Math.ceil(Theme.chat_contextResult_descriptionTextPaint.measureText(inlineResult.url)); CharSequence linkFinal = TextUtils.ellipsize(inlineResult.url.replace('\n', ' '), Theme.chat_contextResult_descriptionTextPaint, Math.min(width, maxWidth), TextUtils.TruncateAt.MIDDLE); linkLayout = new StaticLayout(linkFinal, Theme.chat_contextResult_descriptionTextPaint, maxWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); } catch (Exception e) { FileLog.e(e); } } } String ext = null; if (documentAttach != null) { if (isForceGif || MessageObject.isGifDocument(documentAttach)) { currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(documentAttach.thumbs, 90); } else if (MessageObject.isStickerDocument(documentAttach) || MessageObject.isAnimatedStickerDocument(documentAttach, true)) { currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(documentAttach.thumbs, 90); ext = "webp"; } else { if (documentAttachType != DOCUMENT_ATTACH_TYPE_MUSIC && documentAttachType != DOCUMENT_ATTACH_TYPE_AUDIO) { currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(documentAttach.thumbs, 90); } } } else if (inlineResult != null && inlineResult.photo != null) { currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(photoThumbs, AndroidUtilities.getPhotoSize(), true); currentPhotoObjectThumb = FileLoader.getClosestPhotoSizeWithSize(photoThumbs, 80); if (currentPhotoObjectThumb == currentPhotoObject) { currentPhotoObjectThumb = null; } } if (inlineResult != null) { if (inlineResult.content instanceof TLRPC.TL_webDocument) { if (inlineResult.type != null) { if (inlineResult.type.startsWith("gif")) { if (inlineResult.thumb instanceof TLRPC.TL_webDocument && "video/mp4".equals(inlineResult.thumb.mime_type)) { webDocument = (TLRPC.TL_webDocument) inlineResult.thumb; } else { webDocument = (TLRPC.TL_webDocument) inlineResult.content; } documentAttachType = DOCUMENT_ATTACH_TYPE_GIF; } else if (inlineResult.type.equals("photo")) { if (inlineResult.thumb instanceof TLRPC.TL_webDocument) { webDocument = (TLRPC.TL_webDocument) inlineResult.thumb; } else { webDocument = (TLRPC.TL_webDocument) inlineResult.content; } } } } if (webDocument == null && (inlineResult.thumb instanceof TLRPC.TL_webDocument)) { webDocument = (TLRPC.TL_webDocument) inlineResult.thumb; } if (webDocument == null && currentPhotoObject == null && currentPhotoObjectThumb == null) { if (inlineResult.send_message instanceof TLRPC.TL_botInlineMessageMediaVenue || inlineResult.send_message instanceof TLRPC.TL_botInlineMessageMediaGeo) { double lat = inlineResult.send_message.geo.lat; double lon = inlineResult.send_message.geo._long; if (MessagesController.getInstance(currentAccount).mapProvider == 2) { webFile = WebFile.createWithGeoPoint(inlineResult.send_message.geo, 72, 72, 15, Math.min(2, (int) Math.ceil(AndroidUtilities.density))); } else { urlLocation = AndroidUtilities.formapMapUrl(currentAccount, lat, lon, 72, 72, true, 15, -1); } } } if (webDocument != null) { webFile = WebFile.createWithWebDocument(webDocument); } } int width; int w = 0; int h = 0; if (documentAttach != null) { for (int b = 0; b < documentAttach.attributes.size(); b++) { TLRPC.DocumentAttribute attribute = documentAttach.attributes.get(b); if (attribute instanceof TLRPC.TL_documentAttributeImageSize || attribute instanceof TLRPC.TL_documentAttributeVideo) { w = attribute.w; h = attribute.h; break; } } } if (w == 0 || h == 0) { if (currentPhotoObject != null) { if (currentPhotoObjectThumb != null) { currentPhotoObjectThumb.size = -1; } w = currentPhotoObject.w; h = currentPhotoObject.h; } else if (inlineResult != null) { int[] result = MessageObject.getInlineResultWidthAndHeight(inlineResult); w = result[0]; h = result[1]; } } if (w == 0 || h == 0) { w = h = AndroidUtilities.dp(80); } if (documentAttach != null || currentPhotoObject != null || webFile != null || urlLocation != null) { String currentPhotoFilter; String currentPhotoFilterThumb = "52_52_b"; if (mediaWebpage) { width = (int) (w / (h / (float) AndroidUtilities.dp(80))); if (documentAttachType == DOCUMENT_ATTACH_TYPE_GIF) { currentPhotoFilterThumb = currentPhotoFilter = String.format(Locale.US, "%d_%d_b", (int) (width / AndroidUtilities.density), 80); if (!SharedConfig.isAutoplayGifs() && !isKeyboard) { currentPhotoFilterThumb += "_firstframe"; currentPhotoFilter += "_firstframe"; } } else { currentPhotoFilter = String.format(Locale.US, "%d_%d", (int) (width / AndroidUtilities.density), 80); currentPhotoFilterThumb = currentPhotoFilter + "_b"; } } else { currentPhotoFilter = "52_52"; } linkImageView.setAspectFit(documentAttachType == DOCUMENT_ATTACH_TYPE_STICKER); if (documentAttachType == DOCUMENT_ATTACH_TYPE_GIF) { if (documentAttach != null) { TLRPC.VideoSize thumb = MessageObject.getDocumentVideoThumb(documentAttach); if (thumb != null) { linkImageView.setImage(ImageLocation.getForDocument(thumb, documentAttach), "100_100" + (!SharedConfig.isAutoplayGifs() && !isKeyboard ? "_firstframe" : ""), ImageLocation.getForDocument(currentPhotoObject, documentAttach), currentPhotoFilter, -1, ext, parentObject, 1); } else { ImageLocation location = ImageLocation.getForDocument(documentAttach); if (isForceGif) { location.imageType = FileLoader.IMAGE_TYPE_ANIMATION; } linkImageView.setImage(location, "100_100" + (!SharedConfig.isAutoplayGifs() && !isKeyboard ? "_firstframe" : ""), ImageLocation.getForDocument(currentPhotoObject, documentAttach), currentPhotoFilter, documentAttach.size, ext, parentObject, 0); } } else if (webFile != null) { linkImageView.setImage(ImageLocation.getForWebFile(webFile), "100_100", ImageLocation.getForPhoto(currentPhotoObject, photoAttach), currentPhotoFilter, -1, ext, parentObject, 1); } else { linkImageView.setImage(ImageLocation.getForPath(urlLocation), "100_100", ImageLocation.getForPhoto(currentPhotoObject, photoAttach), currentPhotoFilter, -1, ext, parentObject, 1); } } else { if (currentPhotoObject != null) { SvgHelper.SvgDrawable svgThumb = DocumentObject.getSvgThumb(documentAttach, Theme.key_windowBackgroundGray, 1.0f); if (MessageObject.canAutoplayAnimatedSticker(documentAttach)) { if (svgThumb != null) { linkImageView.setImage(ImageLocation.getForDocument(documentAttach), "80_80", svgThumb, currentPhotoObject.size, ext, parentObject, 0); } else { linkImageView.setImage(ImageLocation.getForDocument(documentAttach), "80_80", ImageLocation.getForDocument(currentPhotoObject, documentAttach), currentPhotoFilterThumb, currentPhotoObject.size, ext, parentObject, 0); } } else { if (documentAttach != null) { if (svgThumb != null) { linkImageView.setImage(ImageLocation.getForDocument(currentPhotoObject, documentAttach), currentPhotoFilter, svgThumb, currentPhotoObject.size, ext, parentObject, 0); } else { linkImageView.setImage(ImageLocation.getForDocument(currentPhotoObject, documentAttach), currentPhotoFilter, ImageLocation.getForPhoto(currentPhotoObjectThumb, photoAttach), currentPhotoFilterThumb, currentPhotoObject.size, ext, parentObject, 0); } } else { linkImageView.setImage(ImageLocation.getForPhoto(currentPhotoObject, photoAttach), currentPhotoFilter, ImageLocation.getForPhoto(currentPhotoObjectThumb, photoAttach), currentPhotoFilterThumb, currentPhotoObject.size, ext, parentObject, 0); } } } else if (webFile != null) { linkImageView.setImage(ImageLocation.getForWebFile(webFile), currentPhotoFilter, ImageLocation.getForPhoto(currentPhotoObjectThumb, photoAttach), currentPhotoFilterThumb, -1, ext, parentObject, 1); } else { linkImageView.setImage(ImageLocation.getForPath(urlLocation), currentPhotoFilter, ImageLocation.getForPhoto(currentPhotoObjectThumb, photoAttach), currentPhotoFilterThumb, -1, ext, parentObject, 1); } } if (SharedConfig.isAutoplayGifs() || isKeyboard) { linkImageView.setAllowStartAnimation(true); linkImageView.startAnimation(); } else { linkImageView.setAllowStartAnimation(false); linkImageView.stopAnimation(); } drawLinkImageView = true; } if (mediaWebpage) { width = viewWidth; int height = MeasureSpec.getSize(heightMeasureSpec); if (height == 0) { height = AndroidUtilities.dp(100); } setMeasuredDimension(width, height); int x = (width - AndroidUtilities.dp(24)) / 2; int y = (height - AndroidUtilities.dp(24)) / 2; radialProgress.setProgressRect(x, y, x + AndroidUtilities.dp(24), y + AndroidUtilities.dp(24)); radialProgress.setCircleRadius(AndroidUtilities.dp(12)); linkImageView.setImageCoords(0, 0, width, height); } else { int height = 0; if (titleLayout != null && titleLayout.getLineCount() != 0) { height += titleLayout.getLineBottom(titleLayout.getLineCount() - 1); } if (descriptionLayout != null && descriptionLayout.getLineCount() != 0) { height += descriptionLayout.getLineBottom(descriptionLayout.getLineCount() - 1); } if (linkLayout != null && linkLayout.getLineCount() > 0) { height += linkLayout.getLineBottom(linkLayout.getLineCount() - 1); } height = Math.max(AndroidUtilities.dp(52), height); setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), Math.max(AndroidUtilities.dp(68), height + AndroidUtilities.dp(16)) + (needDivider ? 1 : 0)); int maxPhotoWidth = AndroidUtilities.dp(52); int x = LocaleController.isRTL ? MeasureSpec.getSize(widthMeasureSpec) - AndroidUtilities.dp(8) - maxPhotoWidth : AndroidUtilities.dp(8); letterDrawable.setBounds(x, AndroidUtilities.dp(8), x + maxPhotoWidth, AndroidUtilities.dp(60)); linkImageView.setImageCoords(x, AndroidUtilities.dp(8), maxPhotoWidth, maxPhotoWidth); if (documentAttachType == DOCUMENT_ATTACH_TYPE_AUDIO || documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC) { radialProgress.setCircleRadius(AndroidUtilities.dp(24)); radialProgress.setProgressRect(x + AndroidUtilities.dp(4), AndroidUtilities.dp(12), x + AndroidUtilities.dp(48), AndroidUtilities.dp(56)); } } if (checkBox != null) { measureChildWithMargins(checkBox, widthMeasureSpec, 0, heightMeasureSpec, 0); } } private void setAttachType() { currentMessageObject = null; documentAttachType = DOCUMENT_ATTACH_TYPE_NONE; if (documentAttach != null) { if (MessageObject.isGifDocument(documentAttach)) { documentAttachType = DOCUMENT_ATTACH_TYPE_GIF; } else if (MessageObject.isStickerDocument(documentAttach) || MessageObject.isAnimatedStickerDocument(documentAttach, true)) { documentAttachType = DOCUMENT_ATTACH_TYPE_STICKER; } else if (MessageObject.isMusicDocument(documentAttach)) { documentAttachType = DOCUMENT_ATTACH_TYPE_MUSIC; } else if (MessageObject.isVoiceDocument(documentAttach)) { documentAttachType = DOCUMENT_ATTACH_TYPE_AUDIO; } } else if (inlineResult != null) { if (inlineResult.photo != null) { documentAttachType = DOCUMENT_ATTACH_TYPE_PHOTO; } else if (inlineResult.type.equals("audio")) { documentAttachType = DOCUMENT_ATTACH_TYPE_MUSIC; } else if (inlineResult.type.equals("voice")) { documentAttachType = DOCUMENT_ATTACH_TYPE_AUDIO; } } if (documentAttachType == DOCUMENT_ATTACH_TYPE_AUDIO || documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC) { TLRPC.TL_message message = new TLRPC.TL_message(); message.out = true; message.id = -Utilities.random.nextInt(); message.peer_id = new TLRPC.TL_peerUser(); message.from_id = new TLRPC.TL_peerUser(); message.peer_id.user_id = message.from_id.user_id = UserConfig.getInstance(currentAccount).getClientUserId(); message.date = (int) (System.currentTimeMillis() / 1000); message.message = ""; message.media = new TLRPC.TL_messageMediaDocument(); message.media.flags |= 3; message.media.document = new TLRPC.TL_document(); message.media.document.file_reference = new byte[0]; message.flags |= TLRPC.MESSAGE_FLAG_HAS_MEDIA | TLRPC.MESSAGE_FLAG_HAS_FROM_ID; if (documentAttach != null) { message.media.document = documentAttach; message.attachPath = ""; } else { String ext = ImageLoader.getHttpUrlExtension(inlineResult.content.url, documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC ? "mp3" : "ogg"); message.media.document.id = 0; message.media.document.access_hash = 0; message.media.document.date = message.date; message.media.document.mime_type = "audio/" + ext; message.media.document.size = 0; message.media.document.dc_id = 0; TLRPC.TL_documentAttributeAudio attributeAudio = new TLRPC.TL_documentAttributeAudio(); attributeAudio.duration = MessageObject.getInlineResultDuration(inlineResult); attributeAudio.title = inlineResult.title != null ? inlineResult.title : ""; attributeAudio.performer = inlineResult.description != null ? inlineResult.description : ""; attributeAudio.flags |= 3; if (documentAttachType == DOCUMENT_ATTACH_TYPE_AUDIO) { attributeAudio.voice = true; } message.media.document.attributes.add(attributeAudio); TLRPC.TL_documentAttributeFilename fileName = new TLRPC.TL_documentAttributeFilename(); fileName.file_name = Utilities.MD5(inlineResult.content.url) + "." + ImageLoader.getHttpUrlExtension(inlineResult.content.url, documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC ? "mp3" : "ogg"); message.media.document.attributes.add(fileName); message.attachPath = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE), Utilities.MD5(inlineResult.content.url) + "." + ImageLoader.getHttpUrlExtension(inlineResult.content.url, documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC ? "mp3" : "ogg")).getAbsolutePath(); } currentMessageObject = new MessageObject(currentAccount, message, false, true); } } public void setLink(TLRPC.BotInlineResult contextResult, TLRPC.User bot, boolean media, boolean divider, boolean shadow) { setLink(contextResult, bot, media, divider, shadow, false); } public void setLink(TLRPC.BotInlineResult contextResult, TLRPC.User bot, boolean media, boolean divider, boolean shadow, boolean forceGif) { needDivider = divider; needShadow = shadow; inlineBot = bot; parentObject = inlineResult = contextResult; if (inlineResult != null) { documentAttach = inlineResult.document; photoAttach = inlineResult.photo; } else { documentAttach = null; photoAttach = null; } mediaWebpage = media; isForceGif = forceGif; setAttachType(); if (forceGif) { documentAttachType = DOCUMENT_ATTACH_TYPE_GIF; } requestLayout(); fileName = null; cacheFile = null; fileExist = false; resolvingFileName = false; updateButtonState(false, false); } public TLRPC.User getInlineBot() { return inlineBot; } public Object getParentObject() { return parentObject; } public void setGif(TLRPC.Document document, boolean divider) { setGif(document, "gif" + document, 0, divider); } public void setGif(TLRPC.Document document, Object parent, int date, boolean divider) { needDivider = divider; needShadow = false; currentDate = date; inlineResult = null; parentObject = parent; documentAttach = document; photoAttach = null; mediaWebpage = true; isForceGif = true; setAttachType(); documentAttachType = DOCUMENT_ATTACH_TYPE_GIF; requestLayout(); fileName = null; cacheFile = null; fileExist = false; resolvingFileName = false; updateButtonState(false, false); } public boolean isSticker() { return documentAttachType == DOCUMENT_ATTACH_TYPE_STICKER; } public boolean isGif() { return documentAttachType == DOCUMENT_ATTACH_TYPE_GIF && canPreviewGif; } public boolean showingBitmap() { return linkImageView.getBitmap() != null; } public int getDate() { return currentDate; } public TLRPC.Document getDocument() { return documentAttach; } public TLRPC.BotInlineResult getBotInlineResult() { return inlineResult; } public ImageReceiver getPhotoImage() { return linkImageView; } public void setScaled(boolean value) { scaled = value; if (buttonBounce != null) { buttonBounce.setPressed(isPressed() || scaled); } } public void setCanPreviewGif(boolean value) { canPreviewGif = value; } public void setIsKeyboard(boolean value) { isKeyboard = value; } public boolean isCanPreviewGif() { return canPreviewGif; } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); linkImageView.onDetachedFromWindow(); radialProgress.onDetachedFromWindow(); DownloadController.getInstance(currentAccount).removeLoadingFileObserver(this); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (linkImageView.onAttachedToWindow()) { updateButtonState(false, false); } radialProgress.onAttachedToWindow(); } public MessageObject getMessageObject() { return currentMessageObject; } @Override public boolean onTouchEvent(MotionEvent event) { if (mediaWebpage || delegate == null || inlineResult == null) { return super.onTouchEvent(event); } int x = (int) event.getX(); int y = (int) event.getY(); boolean result = false; int side = AndroidUtilities.dp(48); if (documentAttachType == DOCUMENT_ATTACH_TYPE_AUDIO || documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC) { boolean area = letterDrawable.getBounds().contains(x, y); if (event.getAction() == MotionEvent.ACTION_DOWN) { if (area) { buttonPressed = true; radialProgress.setPressed(buttonPressed, false); invalidate(); result = true; } } else if (buttonPressed) { if (event.getAction() == MotionEvent.ACTION_UP) { buttonPressed = false; playSoundEffect(SoundEffectConstants.CLICK); didPressedButton(); invalidate(); } else if (event.getAction() == MotionEvent.ACTION_CANCEL) { buttonPressed = false; invalidate(); } else if (event.getAction() == MotionEvent.ACTION_MOVE) { if (!area) { buttonPressed = false; invalidate(); } } radialProgress.setPressed(buttonPressed, false); } } else { if (inlineResult != null && inlineResult.content != null && !TextUtils.isEmpty(inlineResult.content.url)) { if (event.getAction() == MotionEvent.ACTION_DOWN) { if (letterDrawable.getBounds().contains(x, y)) { buttonPressed = true; result = true; } } else { if (buttonPressed) { if (event.getAction() == MotionEvent.ACTION_UP) { buttonPressed = false; playSoundEffect(SoundEffectConstants.CLICK); delegate.didPressedImage(this); } else if (event.getAction() == MotionEvent.ACTION_CANCEL) { buttonPressed = false; } else if (event.getAction() == MotionEvent.ACTION_MOVE) { if (!letterDrawable.getBounds().contains(x, y)) { buttonPressed = false; } } } } } } if (!result) { result = super.onTouchEvent(event); } return result; } private void didPressedButton() { if (documentAttachType == DOCUMENT_ATTACH_TYPE_AUDIO || documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC) { if (buttonState == 0) { if (MediaController.getInstance().playMessage(currentMessageObject)) { buttonState = 1; radialProgress.setIcon(getIconForCurrentState(), false, true); invalidate(); } } else if (buttonState == 1) { boolean result = MediaController.getInstance().pauseMessage(currentMessageObject); if (result) { buttonState = 0; radialProgress.setIcon(getIconForCurrentState(), false, true); invalidate(); } } else if (buttonState == 2) { radialProgress.setProgress(0, false); if (documentAttach != null) { FileLoader.getInstance(currentAccount).loadFile(documentAttach, inlineResult, FileLoader.PRIORITY_NORMAL, 0); } else if (inlineResult.content instanceof TLRPC.TL_webDocument) { FileLoader.getInstance(currentAccount).loadFile(WebFile.createWithWebDocument(inlineResult.content), FileLoader.PRIORITY_HIGH, 1); } buttonState = 4; radialProgress.setIcon(getIconForCurrentState(), false, true); invalidate(); } else if (buttonState == 4) { if (documentAttach != null) { FileLoader.getInstance(currentAccount).cancelLoadFile(documentAttach); } else if (inlineResult.content instanceof TLRPC.TL_webDocument) { FileLoader.getInstance(currentAccount).cancelLoadFile(WebFile.createWithWebDocument(inlineResult.content)); } buttonState = 2; radialProgress.setIcon(getIconForCurrentState(), false, true); invalidate(); } } } @Override protected void onDraw(Canvas canvas) { if (checkBox != null) { if (checkBox.isChecked() || !linkImageView.hasBitmapImage() || linkImageView.getCurrentAlpha() != 1.0f || PhotoViewer.isShowingImage((MessageObject) parentObject)) { canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), backgroundPaint); } } if (titleLayout != null) { canvas.save(); canvas.translate(AndroidUtilities.dp(LocaleController.isRTL ? 8 : AndroidUtilities.leftBaseline), titleY); titleLayout.draw(canvas); canvas.restore(); } if (descriptionLayout != null) { Theme.chat_contextResult_descriptionTextPaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText2, resourcesProvider)); canvas.save(); canvas.translate(AndroidUtilities.dp(LocaleController.isRTL ? 8 : AndroidUtilities.leftBaseline), descriptionY); descriptionLayout.draw(canvas); canvas.restore(); } if (linkLayout != null) { Theme.chat_contextResult_descriptionTextPaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhiteLinkText, resourcesProvider)); canvas.save(); canvas.translate(AndroidUtilities.dp(LocaleController.isRTL ? 8 : AndroidUtilities.leftBaseline), linkY); linkLayout.draw(canvas); canvas.restore(); } if (!mediaWebpage) { if (drawLinkImageView && !PhotoViewer.isShowingImage(inlineResult)) { letterDrawable.setAlpha((int) (255 * (1.0f - linkImageView.getCurrentAlpha()))); } else { letterDrawable.setAlpha(255); } if (documentAttachType == DOCUMENT_ATTACH_TYPE_AUDIO || documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC) { radialProgress.setProgressColor(Theme.getColor(buttonPressed ? Theme.key_chat_inAudioSelectedProgress : Theme.key_chat_inAudioProgress, resourcesProvider)); radialProgress.draw(canvas); } else if (inlineResult != null && inlineResult.type.equals("file")) { int w = Theme.chat_inlineResultFile.getIntrinsicWidth(); int h = Theme.chat_inlineResultFile.getIntrinsicHeight(); int x = (int) (linkImageView.getImageX() + (AndroidUtilities.dp(52) - w) / 2); int y = (int) (linkImageView.getImageY() + (AndroidUtilities.dp(52) - h) / 2); canvas.drawRect(linkImageView.getImageX(), linkImageView.getImageY(), linkImageView.getImageX() + AndroidUtilities.dp(52), linkImageView.getImageY() + AndroidUtilities.dp(52), LetterDrawable.paint); Theme.chat_inlineResultFile.setBounds(x, y, x + w, y + h); Theme.chat_inlineResultFile.draw(canvas); } else if (inlineResult != null && (inlineResult.type.equals("audio") || inlineResult.type.equals("voice"))) { int w = Theme.chat_inlineResultAudio.getIntrinsicWidth(); int h = Theme.chat_inlineResultAudio.getIntrinsicHeight(); int x = (int) (linkImageView.getImageX() + (AndroidUtilities.dp(52) - w) / 2); int y = (int) (linkImageView.getImageY() + (AndroidUtilities.dp(52) - h) / 2); canvas.drawRect(linkImageView.getImageX(), linkImageView.getImageY(), linkImageView.getImageX() + AndroidUtilities.dp(52), linkImageView.getImageY() + AndroidUtilities.dp(52), LetterDrawable.paint); Theme.chat_inlineResultAudio.setBounds(x, y, x + w, y + h); Theme.chat_inlineResultAudio.draw(canvas); } else if (inlineResult != null && (inlineResult.type.equals("venue") || inlineResult.type.equals("geo"))) { int w = Theme.chat_inlineResultLocation.getIntrinsicWidth(); int h = Theme.chat_inlineResultLocation.getIntrinsicHeight(); int x = (int) (linkImageView.getImageX() + (AndroidUtilities.dp(52) - w) / 2); int y = (int) (linkImageView.getImageY() + (AndroidUtilities.dp(52) - h) / 2); canvas.drawRect(linkImageView.getImageX(), linkImageView.getImageY(), linkImageView.getImageX() + AndroidUtilities.dp(52), linkImageView.getImageY() + AndroidUtilities.dp(52), LetterDrawable.paint); Theme.chat_inlineResultLocation.setBounds(x, y, x + w, y + h); Theme.chat_inlineResultLocation.draw(canvas); } else { letterDrawable.draw(canvas); } } else { if (inlineResult != null && (inlineResult.send_message instanceof TLRPC.TL_botInlineMessageMediaGeo || inlineResult.send_message instanceof TLRPC.TL_botInlineMessageMediaVenue)) { int w = Theme.chat_inlineResultLocation.getIntrinsicWidth(); int h = Theme.chat_inlineResultLocation.getIntrinsicHeight(); int x = (int) (linkImageView.getImageX() + (linkImageView.getImageWidth() - w) / 2); int y = (int) (linkImageView.getImageY() + (linkImageView.getImageHeight() - h) / 2); canvas.drawRect(linkImageView.getImageX(), linkImageView.getImageY(), linkImageView.getImageX() + linkImageView.getImageWidth(), linkImageView.getImageY() + linkImageView.getImageHeight(), LetterDrawable.paint); Theme.chat_inlineResultLocation.setBounds(x, y, x + w, y + h); Theme.chat_inlineResultLocation.draw(canvas); } } if (drawLinkImageView) { if (inlineResult != null) { linkImageView.setVisible(!PhotoViewer.isShowingImage(inlineResult), false); } canvas.save(); float s = imageScale; if (buttonBounce != null) { s *= buttonBounce.getScale(.1f); } canvas.scale(s, s, getMeasuredWidth() / 2, getMeasuredHeight() / 2); linkImageView.draw(canvas); canvas.restore(); } if (mediaWebpage && (documentAttachType == DOCUMENT_ATTACH_TYPE_PHOTO || documentAttachType == DOCUMENT_ATTACH_TYPE_GIF)) { radialProgress.draw(canvas); } if (needDivider && !mediaWebpage) { if (LocaleController.isRTL) { canvas.drawLine(0, getMeasuredHeight() - 1, getMeasuredWidth() - AndroidUtilities.dp(AndroidUtilities.leftBaseline), getMeasuredHeight() - 1, Theme.dividerPaint); } else { canvas.drawLine(AndroidUtilities.dp(AndroidUtilities.leftBaseline), getMeasuredHeight() - 1, getMeasuredWidth(), getMeasuredHeight() - 1, Theme.dividerPaint); } } if (needShadow) { Theme.chat_contextResult_shadowUnderSwitchDrawable.setBounds(0, 0, getMeasuredWidth(), AndroidUtilities.dp(3)); Theme.chat_contextResult_shadowUnderSwitchDrawable.draw(canvas); } } private int getIconForCurrentState() { if (documentAttachType == DOCUMENT_ATTACH_TYPE_AUDIO || documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC) { radialProgress.setColorKeys(Theme.key_chat_inLoader, Theme.key_chat_inLoaderSelected, Theme.key_chat_inMediaIcon, Theme.key_chat_inMediaIconSelected); if (buttonState == 1) { return MediaActionDrawable.ICON_PAUSE; } else if (buttonState == 2) { return MediaActionDrawable.ICON_DOWNLOAD; } else if (buttonState == 4) { return MediaActionDrawable.ICON_CANCEL; } return MediaActionDrawable.ICON_PLAY; } radialProgress.setColorKeys(Theme.key_chat_mediaLoaderPhoto, Theme.key_chat_mediaLoaderPhotoSelected, Theme.key_chat_mediaLoaderPhotoIcon, Theme.key_chat_mediaLoaderPhotoIconSelected); return buttonState == 1 ? MediaActionDrawable.ICON_EMPTY : MediaActionDrawable.ICON_NONE; } boolean resolvingFileName; String fileName; File cacheFile = null; int resolveFileNameId; boolean fileExist; private static int resolveFileIdPointer; public void updateButtonState(boolean ifSame, boolean animated) { if (fileName == null && !resolvingFileName) { resolvingFileName = true; int localId = resolveFileNameId = resolveFileNameId++; Utilities.searchQueue.postRunnable(new Runnable() { @Override public void run() { String fileName = null; File cacheFile = null; if (documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC || documentAttachType == DOCUMENT_ATTACH_TYPE_AUDIO) { if (documentAttach != null) { fileName = FileLoader.getAttachFileName(documentAttach); cacheFile = FileLoader.getInstance(currentAccount).getPathToAttach(documentAttach); } else if (inlineResult.content instanceof TLRPC.TL_webDocument) { fileName = Utilities.MD5(inlineResult.content.url) + "." + ImageLoader.getHttpUrlExtension(inlineResult.content.url, documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC ? "mp3" : "ogg"); cacheFile = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE), fileName); } } else if (mediaWebpage) { if (inlineResult != null) { if (inlineResult.document instanceof TLRPC.TL_document) { fileName = FileLoader.getAttachFileName(inlineResult.document); cacheFile = FileLoader.getInstance(currentAccount).getPathToAttach(inlineResult.document); } else if (inlineResult.photo instanceof TLRPC.TL_photo) { currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(inlineResult.photo.sizes, AndroidUtilities.getPhotoSize(), true); fileName = FileLoader.getAttachFileName(currentPhotoObject); cacheFile = FileLoader.getInstance(currentAccount).getPathToAttach(currentPhotoObject); } else if (inlineResult.content instanceof TLRPC.TL_webDocument) { fileName = Utilities.MD5(inlineResult.content.url) + "." + ImageLoader.getHttpUrlExtension(inlineResult.content.url, FileLoader.getMimeTypePart(inlineResult.content.mime_type)); cacheFile = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE), fileName); if (documentAttachType == DOCUMENT_ATTACH_TYPE_GIF && inlineResult.thumb instanceof TLRPC.TL_webDocument && "video/mp4".equals(inlineResult.thumb.mime_type)) { fileName = null; } } else if (inlineResult.thumb instanceof TLRPC.TL_webDocument) { fileName = Utilities.MD5(inlineResult.thumb.url) + "." + ImageLoader.getHttpUrlExtension(inlineResult.thumb.url, FileLoader.getMimeTypePart(inlineResult.thumb.mime_type)); cacheFile = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE), fileName); } } else if (documentAttach != null) { fileName = FileLoader.getAttachFileName(documentAttach); cacheFile = FileLoader.getInstance(currentAccount).getPathToAttach(documentAttach); } if (documentAttach != null && documentAttachType == DOCUMENT_ATTACH_TYPE_GIF && MessageObject.getDocumentVideoThumb(documentAttach) != null) { fileName = null; } } String fileNameFinal = fileName; File cacheFileFinal = cacheFile; boolean fileExist = !TextUtils.isEmpty(fileName) && cacheFile.exists(); AndroidUtilities.runOnUIThread(() -> { resolvingFileName = false; if (resolveFileNameId == localId) { ContextLinkCell.this.fileName = fileNameFinal; if (ContextLinkCell.this.fileName == null) { ContextLinkCell.this.fileName = ""; } ContextLinkCell.this.cacheFile = cacheFileFinal; ContextLinkCell.this.fileExist = fileExist; } updateButtonState(ifSame, true); }); } }); radialProgress.setIcon(MediaActionDrawable.ICON_NONE, ifSame, false); } else { if (TextUtils.isEmpty(fileName)) { buttonState = -1; radialProgress.setIcon(MediaActionDrawable.ICON_NONE, ifSame, false); return; } boolean isLoading; if (documentAttach != null) { isLoading = FileLoader.getInstance(currentAccount).isLoadingFile(fileName); } else { isLoading = ImageLoader.getInstance().isLoadingHttpFile(fileName); } if (isLoading || !fileExist) { DownloadController.getInstance(currentAccount).addLoadingFileObserver(fileName, this); if (documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC || documentAttachType == DOCUMENT_ATTACH_TYPE_AUDIO) { if (!isLoading) { buttonState = 2; } else { buttonState = 4; Float progress = ImageLoader.getInstance().getFileProgress(fileName); if (progress != null) { radialProgress.setProgress(progress, animated); } else { radialProgress.setProgress(0, animated); } } } else { buttonState = 1; Float progress = ImageLoader.getInstance().getFileProgress(fileName); float setProgress = progress != null ? progress : 0; radialProgress.setProgress(setProgress, false); } } else { DownloadController.getInstance(currentAccount).removeLoadingFileObserver(this); if (documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC || documentAttachType == DOCUMENT_ATTACH_TYPE_AUDIO) { boolean playing = MediaController.getInstance().isPlayingMessage(currentMessageObject); if (!playing || playing && MediaController.getInstance().isMessagePaused()) { buttonState = 0; } else { buttonState = 1; } radialProgress.setProgress(1, animated); } else { buttonState = -1; } } radialProgress.setIcon(getIconForCurrentState(), ifSame, animated); invalidate(); } } public void setDelegate(ContextLinkCellDelegate contextLinkCellDelegate) { delegate = contextLinkCellDelegate; } public TLRPC.BotInlineResult getResult() { return inlineResult; } @Override public void onFailedDownload(String fileName, boolean canceled) { updateButtonState(true, canceled); } @Override public void onSuccessDownload(String fileName) { fileExist = true; radialProgress.setProgress(1, true); updateButtonState(false, true); } @Override public void onProgressDownload(String fileName, long downloadedSize, long totalSize) { radialProgress.setProgress(Math.min(1f, downloadedSize / (float) totalSize), true); if (documentAttachType == DOCUMENT_ATTACH_TYPE_AUDIO || documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC) { if (buttonState != 4) { updateButtonState(false, true); } } else { if (buttonState != 1) { updateButtonState(false, true); } } } @Override public void onProgressUpload(String fileName, long uploadedSize, long totalSize, boolean isEncrypted) { } @Override public int getObserverTag() { return TAG; } @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); StringBuilder sbuf = new StringBuilder(); switch (documentAttachType) { case DOCUMENT_ATTACH_TYPE_DOCUMENT: sbuf.append(LocaleController.getString("AttachDocument", R.string.AttachDocument)); break; case DOCUMENT_ATTACH_TYPE_GIF: sbuf.append(LocaleController.getString("AttachGif", R.string.AttachGif)); break; case DOCUMENT_ATTACH_TYPE_AUDIO: sbuf.append(LocaleController.getString("AttachAudio", R.string.AttachAudio)); break; case DOCUMENT_ATTACH_TYPE_VIDEO: sbuf.append(LocaleController.getString("AttachVideo", R.string.AttachVideo)); break; case DOCUMENT_ATTACH_TYPE_MUSIC: sbuf.append(LocaleController.getString("AttachMusic", R.string.AttachMusic)); break; case DOCUMENT_ATTACH_TYPE_STICKER: sbuf.append(LocaleController.getString("AttachSticker", R.string.AttachSticker)); break; case DOCUMENT_ATTACH_TYPE_PHOTO: sbuf.append(LocaleController.getString("AttachPhoto", R.string.AttachPhoto)); break; case DOCUMENT_ATTACH_TYPE_GEO: sbuf.append(LocaleController.getString("AttachLocation", R.string.AttachLocation)); break; } final boolean hasTitle = titleLayout != null && !TextUtils.isEmpty(titleLayout.getText()); final boolean hasDescription = descriptionLayout != null && !TextUtils.isEmpty(descriptionLayout.getText()); if (documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC && hasTitle && hasDescription) { sbuf.append(", "); sbuf.append(LocaleController.formatString("AccDescrMusicInfo", R.string.AccDescrMusicInfo, descriptionLayout.getText(), titleLayout.getText())); } else { if (hasTitle) { if (sbuf.length() > 0) { sbuf.append(", "); } sbuf.append(titleLayout.getText()); } if (hasDescription) { if (sbuf.length() > 0) { sbuf.append(", "); } sbuf.append(descriptionLayout.getText()); } } info.setText(sbuf); if (checkBox != null && checkBox.isChecked()) { info.setCheckable(true); info.setChecked(true); } } private float imageScale = 1.0f; public final Property<ContextLinkCell, Float> IMAGE_SCALE = new AnimationProperties.FloatProperty<ContextLinkCell>("animationValue") { @Override public void setValue(ContextLinkCell object, float value) { imageScale = value; invalidate(); } @Override public Float get(ContextLinkCell object) { return imageScale; } }; public void setChecked(boolean checked, boolean animated) { if (checkBox == null) { return; } if (checkBox.getVisibility() != VISIBLE) { checkBox.setVisibility(VISIBLE); } checkBox.setChecked(checked, animated); if (animator != null) { animator.cancel(); animator = null; } if (animated) { animator = new AnimatorSet(); animator.playTogether( ObjectAnimator.ofFloat(this, IMAGE_SCALE, checked ? 0.81f : 1.0f)); animator.setDuration(200); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (animator != null && animator.equals(animation)) { animator = null; if (!checked) { setBackgroundColor(0); } } } @Override public void onAnimationCancel(Animator animation) { if (animator != null && animator.equals(animation)) { animator = null; } } }); animator.start(); } else { imageScale = checked ? 0.85f : 1.0f; invalidate(); } } @Override public void setPressed(boolean pressed) { super.setPressed(pressed); if (buttonBounce != null) { buttonBounce.setPressed(pressed || scaled); } } }
Telegram-FOSS-Team/Telegram-FOSS
TMessagesProj/src/main/java/org/telegram/ui/Cells/ContextLinkCell.java
41,716
package org.telegram.messenger; import android.content.Context; import android.content.SharedPreferences; import android.os.BatteryManager; import android.os.Build; import android.os.PowerManager; import android.util.SparseArray; import android.util.SparseIntArray; import androidx.annotation.RequiresApi; import androidx.core.math.MathUtils; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.Components.AnimatedEmojiDrawable; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.Components.AnimatedEmojiDrawable; public class LiteMode { public static final int FLAG_ANIMATED_STICKERS_KEYBOARD = 1; public static final int FLAG_ANIMATED_STICKERS_CHAT = 2; public static final int FLAGS_ANIMATED_STICKERS = FLAG_ANIMATED_STICKERS_KEYBOARD | FLAG_ANIMATED_STICKERS_CHAT; public static final int FLAG_ANIMATED_EMOJI_KEYBOARD_PREMIUM = 4; public static final int FLAG_ANIMATED_EMOJI_KEYBOARD_NOT_PREMIUM = 16384; public static final int FLAG_ANIMATED_EMOJI_KEYBOARD = FLAG_ANIMATED_EMOJI_KEYBOARD_PREMIUM | FLAG_ANIMATED_EMOJI_KEYBOARD_NOT_PREMIUM; public static final int FLAG_ANIMATED_EMOJI_REACTIONS_PREMIUM = 8; public static final int FLAG_ANIMATED_EMOJI_REACTIONS_NOT_PREMIUM = 8192; public static final int FLAG_ANIMATED_EMOJI_REACTIONS = FLAG_ANIMATED_EMOJI_REACTIONS_PREMIUM | FLAG_ANIMATED_EMOJI_REACTIONS_NOT_PREMIUM; public static final int FLAG_ANIMATED_EMOJI_CHAT_PREMIUM = 16; public static final int FLAG_ANIMATED_EMOJI_CHAT_NOT_PREMIUM = 4096; public static final int FLAG_ANIMATED_EMOJI_CHAT = FLAG_ANIMATED_EMOJI_CHAT_PREMIUM | FLAG_ANIMATED_EMOJI_CHAT_NOT_PREMIUM; public static final int FLAGS_ANIMATED_EMOJI = FLAG_ANIMATED_EMOJI_KEYBOARD | FLAG_ANIMATED_EMOJI_REACTIONS | FLAG_ANIMATED_EMOJI_CHAT; public static final int FLAG_CHAT_BACKGROUND = 32; public static final int FLAG_CHAT_FORUM_TWOCOLUMN = 64; public static final int FLAG_CHAT_SPOILER = 128; public static final int FLAG_CHAT_BLUR = 256; public static final int FLAG_CHAT_SCALE = 32768; public static final int FLAGS_CHAT = FLAG_CHAT_BACKGROUND | FLAG_CHAT_FORUM_TWOCOLUMN | FLAG_CHAT_SPOILER | FLAG_CHAT_BLUR | FLAG_CHAT_SCALE; public static final int FLAG_CALLS_ANIMATIONS = 512; public static final int FLAG_AUTOPLAY_VIDEOS = 1024; public static final int FLAG_AUTOPLAY_GIFS = 2048; public static int PRESET_LOW = ( FLAG_ANIMATED_EMOJI_CHAT_PREMIUM | FLAG_AUTOPLAY_GIFS ); // 2064 public static int PRESET_MEDIUM = ( FLAGS_ANIMATED_STICKERS | FLAG_ANIMATED_EMOJI_KEYBOARD_PREMIUM | FLAG_ANIMATED_EMOJI_REACTIONS_PREMIUM | FLAG_ANIMATED_EMOJI_CHAT | FLAG_CHAT_FORUM_TWOCOLUMN | FLAG_CALLS_ANIMATIONS | FLAG_AUTOPLAY_VIDEOS | FLAG_AUTOPLAY_GIFS ); // 7775 public static int PRESET_HIGH = ( FLAGS_ANIMATED_STICKERS | FLAGS_ANIMATED_EMOJI | FLAGS_CHAT | FLAG_CALLS_ANIMATIONS | FLAG_AUTOPLAY_VIDEOS | FLAG_AUTOPLAY_GIFS ); // 65535 public static int PRESET_POWER_SAVER = 0; private static int BATTERY_LOW = 10; private static int BATTERY_MEDIUM = 10; private static int BATTERY_HIGH = 10; private static int powerSaverLevel; private static boolean lastPowerSaverApplied; private static int value; private static boolean loaded; public static int getValue() { return getValue(false); } public static int getValue(boolean ignorePowerSaving) { if (!loaded) { loadPreference(); } if (!ignorePowerSaving && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (getBatteryLevel() <= powerSaverLevel && powerSaverLevel > 0) { if (!lastPowerSaverApplied) { onPowerSaverApplied(lastPowerSaverApplied = true); } return PRESET_POWER_SAVER; } if (lastPowerSaverApplied) { onPowerSaverApplied(lastPowerSaverApplied = false); } } return value; } private static int lastBatteryLevelCached = -1; private static long lastBatteryLevelChecked; @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public static int getBatteryLevel() { if (lastBatteryLevelCached < 0 || System.currentTimeMillis() - lastBatteryLevelChecked > 1000 * 12) { BatteryManager batteryManager = (BatteryManager) ApplicationLoader.applicationContext.getSystemService(Context.BATTERY_SERVICE); if (batteryManager != null) { lastBatteryLevelCached = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY); lastBatteryLevelChecked = System.currentTimeMillis(); } } return lastBatteryLevelCached; } private static int preprocessFlag(int flag) { if (flag == FLAG_ANIMATED_EMOJI_KEYBOARD) { return UserConfig.hasPremiumOnAccounts() ? FLAG_ANIMATED_EMOJI_KEYBOARD_PREMIUM : FLAG_ANIMATED_EMOJI_KEYBOARD_NOT_PREMIUM; } else if (flag == FLAG_ANIMATED_EMOJI_REACTIONS) { return UserConfig.hasPremiumOnAccounts() ? FLAG_ANIMATED_EMOJI_REACTIONS_PREMIUM : FLAG_ANIMATED_EMOJI_REACTIONS_NOT_PREMIUM; } else if (flag == FLAG_ANIMATED_EMOJI_CHAT) { return UserConfig.hasPremiumOnAccounts() ? FLAG_ANIMATED_EMOJI_CHAT_PREMIUM : FLAG_ANIMATED_EMOJI_CHAT_NOT_PREMIUM; } return flag; } public static boolean isEnabled(int flag) { return (getValue() & preprocessFlag(flag)) > 0; } public static boolean isEnabledSetting(int flag) { return (getValue(true) & flag) > 0; } public static void toggleFlag(int flag) { toggleFlag(flag, !isEnabled(flag)); } public static void toggleFlag(int flag, boolean enabled) { setAllFlags(enabled ? getValue(true) | flag : getValue(true) & ~flag); } public static void setAllFlags(int flags) { // in settings it is already handled. would you handle it? 🫵 // onFlagsUpdate(value, flags); value = flags; savePreference(); } public static void updatePresets(TLRPC.TL_jsonObject json) { for (int i = 0; i < json.value.size(); ++i) { TLRPC.TL_jsonObjectValue kv = json.value.get(i); if ("settings_mask".equals(kv.key) && kv.value instanceof TLRPC.TL_jsonArray) { ArrayList<TLRPC.JSONValue> array = ((TLRPC.TL_jsonArray) kv.value).value; try { PRESET_LOW = (int) ((TLRPC.TL_jsonNumber) array.get(0)).value; PRESET_MEDIUM = (int) ((TLRPC.TL_jsonNumber) array.get(1)).value; PRESET_HIGH = (int) ((TLRPC.TL_jsonNumber) array.get(2)).value; } catch (Exception e) { FileLog.e(e); } } else if ("battery_low".equals(kv.key) && kv.value instanceof TLRPC.TL_jsonArray) { ArrayList<TLRPC.JSONValue> array = ((TLRPC.TL_jsonArray) kv.value).value; try { BATTERY_LOW = (int) ((TLRPC.TL_jsonNumber) array.get(0)).value; BATTERY_MEDIUM = (int) ((TLRPC.TL_jsonNumber) array.get(1)).value; BATTERY_HIGH = (int) ((TLRPC.TL_jsonNumber) array.get(2)).value; } catch (Exception e) { FileLog.e(e); } } } loadPreference(); } public static void loadPreference() { int defaultValue = PRESET_HIGH, batteryDefaultValue = BATTERY_HIGH; if (SharedConfig.getDevicePerformanceClass() == SharedConfig.PERFORMANCE_CLASS_LOW) { defaultValue = PRESET_LOW; batteryDefaultValue = BATTERY_LOW; } else if (SharedConfig.getDevicePerformanceClass() == SharedConfig.PERFORMANCE_CLASS_AVERAGE) { defaultValue = PRESET_MEDIUM; batteryDefaultValue = BATTERY_MEDIUM; } final SharedPreferences preferences = MessagesController.getGlobalMainSettings(); if (!preferences.contains("lite_mode2")) { if (preferences.contains("lite_mode")) { defaultValue = preferences.getInt("lite_mode", defaultValue); if (defaultValue == 4095) { defaultValue = PRESET_HIGH; } } else { if (preferences.contains("light_mode")) { boolean prevLiteModeEnabled = (preferences.getInt("light_mode", SharedConfig.getDevicePerformanceClass() == SharedConfig.PERFORMANCE_CLASS_LOW ? 1 : 0) & 1) > 0; if (prevLiteModeEnabled) { defaultValue = PRESET_LOW; } else { defaultValue = PRESET_HIGH; } } // migrate settings if (preferences.contains("loopStickers")) { boolean loopStickers = preferences.getBoolean("loopStickers", true); if (loopStickers) { defaultValue |= FLAG_ANIMATED_STICKERS_CHAT; } else { defaultValue &= ~FLAG_ANIMATED_STICKERS_CHAT; } } if (preferences.contains("autoplay_video")) { boolean autoplayVideo = preferences.getBoolean("autoplay_video", true) || preferences.getBoolean("autoplay_video_liteforce", false); if (autoplayVideo) { defaultValue |= FLAG_AUTOPLAY_VIDEOS; } else { defaultValue &= ~FLAG_AUTOPLAY_VIDEOS; } } if (preferences.contains("autoplay_gif")) { boolean autoplayGif = preferences.getBoolean("autoplay_gif", true); if (autoplayGif) { defaultValue |= FLAG_AUTOPLAY_GIFS; } else { defaultValue &= ~FLAG_AUTOPLAY_GIFS; } } if (preferences.contains("chatBlur")) { boolean chatBlur = preferences.getBoolean("chatBlur", true); if (chatBlur) { defaultValue |= FLAG_CHAT_BLUR; } else { defaultValue &= ~FLAG_CHAT_BLUR; } } } } int prevValue = value; value = preferences.getInt("lite_mode2", defaultValue); if (loaded) { onFlagsUpdate(prevValue, value); } powerSaverLevel = preferences.getInt("lite_mode_battery_level", batteryDefaultValue); loaded = true; } public static void savePreference() { MessagesController.getGlobalMainSettings().edit().putInt("lite_mode2", value).putInt("lite_mode_battery_level", powerSaverLevel).apply(); } public static int getPowerSaverLevel() { if (!loaded) { loadPreference(); } return powerSaverLevel; } public static void setPowerSaverLevel(int value) { powerSaverLevel = MathUtils.clamp(value, 0, 100); savePreference(); // check power saver applied getValue(false); } public static boolean isPowerSaverApplied() { getValue(false); return lastPowerSaverApplied; } private static void onPowerSaverApplied(boolean powerSaverApplied) { if (powerSaverApplied) { onFlagsUpdate(getValue(true), PRESET_POWER_SAVER); } else { onFlagsUpdate(PRESET_POWER_SAVER, getValue(true)); } if (onPowerSaverAppliedListeners != null) { AndroidUtilities.runOnUIThread(() -> { Iterator<Utilities.Callback<Boolean>> i = onPowerSaverAppliedListeners.iterator(); while (i.hasNext()) { Utilities.Callback<Boolean> callback = i.next(); if (callback != null) { callback.run(powerSaverApplied); } } }); } } private static void onFlagsUpdate(int oldValue, int newValue) { int changedFlags = ~oldValue & newValue; if ((changedFlags & FLAGS_ANIMATED_EMOJI) > 0) { AnimatedEmojiDrawable.updateAll(); } if ((changedFlags & FLAG_CHAT_BACKGROUND) > 0) { Theme.reloadWallpaper(); } } private static HashSet<Utilities.Callback<Boolean>> onPowerSaverAppliedListeners; public static void addOnPowerSaverAppliedListener(Utilities.Callback<Boolean> listener) { if (onPowerSaverAppliedListeners == null) { onPowerSaverAppliedListeners = new HashSet<>(); } onPowerSaverAppliedListeners.add(listener); } public static void removeOnPowerSaverAppliedListener(Utilities.Callback<Boolean> listener) { if (onPowerSaverAppliedListeners != null) { onPowerSaverAppliedListeners.remove(listener); } } }
vivabelarus/Telegram
TMessagesProj/src/main/java/org/telegram/messenger/LiteMode.java
41,717
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.ui; import static org.telegram.messenger.AndroidUtilities.dp; import static org.telegram.messenger.LocaleController.getString; import static org.telegram.messenger.MessageObject.replaceWithLink; import android.Manifest; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.annotation.TargetApi; import android.app.DatePickerDialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Outline; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.text.Spannable; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.StaticLayout; import android.text.TextPaint; import android.text.TextUtils; import android.text.style.CharacterStyle; import android.text.style.ClickableSpan; import android.text.style.DynamicDrawableSpan; import android.text.style.ImageSpan; import android.text.style.LineHeightSpan; import android.text.style.URLSpan; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.TextureView; import android.view.View; import android.view.ViewGroup; import android.view.ViewOutlineProvider; import android.view.ViewTreeObserver; import android.view.WindowManager; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.collection.LongSparseArray; import androidx.core.content.FileProvider; import androidx.recyclerview.widget.ChatListItemAnimator; import androidx.recyclerview.widget.DiffUtil; import androidx.recyclerview.widget.GridLayoutManagerFixed; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.LinearSmoothScrollerCustom; import androidx.recyclerview.widget.RecyclerView; import com.google.android.exoplayer2.ui.AspectRatioFrameLayout; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AnimationNotificationsLocker; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.BuildVars; import org.telegram.messenger.ChatObject; import org.telegram.messenger.ContactsController; import org.telegram.messenger.DialogObject; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.ImageLocation; import org.telegram.messenger.ImageReceiver; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MediaController; import org.telegram.messenger.MediaDataController; import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesStorage; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.UserConfig; import org.telegram.messenger.UserObject; import org.telegram.messenger.Utilities; import org.telegram.messenger.browser.Browser; import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.ActionBar; import org.telegram.ui.ActionBar.ActionBarMenu; import org.telegram.ui.ActionBar.ActionBarMenuItem; import org.telegram.ui.ActionBar.ActionBarMenuSubItem; import org.telegram.ui.ActionBar.ActionBarPopupWindow; import org.telegram.ui.ActionBar.AdjustPanLayoutHelper; import org.telegram.ui.ActionBar.AlertDialog; import org.telegram.ui.ActionBar.BackDrawable; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.BottomSheet; import org.telegram.ui.ActionBar.INavigationLayout; import org.telegram.ui.ActionBar.SimpleTextView; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.ThemeDescription; import org.telegram.ui.Cells.ChatActionCell; import org.telegram.ui.Cells.ChatLoadingCell; import org.telegram.ui.Cells.ChatMessageCell; import org.telegram.ui.Cells.ChatUnreadCell; import org.telegram.ui.Components.AdminLogFilterAlert; import org.telegram.ui.Components.AdminLogFilterAlert2; import org.telegram.ui.Components.AlertsCreator; import org.telegram.ui.Components.Bulletin; import org.telegram.ui.Components.BulletinFactory; import org.telegram.ui.Components.ChatAvatarContainer; import org.telegram.ui.Components.ChatScrimPopupContainerLayout; import org.telegram.ui.Components.ClearHistoryAlert; import org.telegram.ui.Components.ColoredImageSpan; import org.telegram.ui.Components.EmbedBottomSheet; import org.telegram.ui.Components.Forum.ForumUtilities; import org.telegram.ui.Components.InviteLinkBottomSheet; import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.PhonebookShareAlert; import org.telegram.ui.Components.PipRoundVideoView; import org.telegram.ui.Components.RadialProgressView; import org.telegram.ui.Components.Reactions.ReactionsEffectOverlay; import org.telegram.ui.Components.RecyclerAnimationScrollHelper; import org.telegram.ui.Components.RecyclerListView; import org.telegram.ui.Components.ShareAlert; import org.telegram.ui.Components.SizeNotifierFrameLayout; import org.telegram.ui.Components.StickersAlert; import org.telegram.ui.Components.URLSpanMono; import org.telegram.ui.Components.URLSpanNoUnderline; import org.telegram.ui.Components.URLSpanReplacement; import org.telegram.ui.Components.URLSpanUserMention; import org.telegram.ui.Components.UndoView; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; public class ChannelAdminLogActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate { protected TLRPC.Chat currentChat; private ArrayList<ChatMessageCell> chatMessageCellsCache = new ArrayList<>(); private FrameLayout progressView; private View progressView2; private RadialProgressView progressBar; private RecyclerListView chatListView; private UndoView undoView; private LinearLayoutManager chatLayoutManager; private RecyclerAnimationScrollHelper chatScrollHelper; private ChatActivityAdapter chatAdapter; private TextView bottomOverlayChatText; private ImageView bottomOverlayImage; private FrameLayout bottomOverlayChat; private FrameLayout emptyViewContainer; private ChatAvatarContainer avatarContainer; private LinearLayout emptyLayoutView; private ImageView emptyImageView; private TextView emptyView; private ChatActionCell floatingDateView; private ActionBarMenuItem searchItem; private long minEventId; private boolean currentFloatingDateOnScreen; private boolean currentFloatingTopIsNotMessage; private AnimatorSet floatingDateAnimation; private boolean scrollingFloatingDate; private int[] mid = new int[]{2}; private boolean searchWas; private boolean scrollByTouch; private float contentPanTranslation; private float contentPanTranslationT; private long activityResumeTime; public static int lastStableId = 10; private boolean checkTextureViewPosition; private SizeNotifierFrameLayout contentView; private MessageObject selectedObject; private TLRPC.ChannelParticipant selectedParticipant; private FrameLayout searchContainer; private ImageView searchCalendarButton; private ImageView searchUpButton; private ImageView searchDownButton; private SimpleTextView searchCountText; private FrameLayout roundVideoContainer; private AspectRatioFrameLayout aspectRatioFrameLayout; private TextureView videoTextureView; private Path aspectPath; private Paint aspectPaint; private int scrollToPositionOnRecreate = -1; private int scrollToOffsetOnRecreate = 0; private boolean paused = true; private boolean wasPaused = false; private boolean openAnimationEnded; private final LongSparseArray<MessageObject> messagesDict = new LongSparseArray<>(); private final LongSparseArray<MessageObject> realMessagesDict = new LongSparseArray<>(); private final HashMap<String, ArrayList<MessageObject>> messagesByDays = new HashMap<>(); protected ArrayList<MessageObject> messages = new ArrayList<>(); private final ArrayList<MessageObject> filteredMessages = new ArrayList<>(); private final HashSet<Long> expandedEvents = new HashSet<>(); private int minDate; private boolean endReached; private boolean loading; private boolean reloadingLastMessages; private int loadsCount; private ArrayList<TLRPC.ChannelParticipant> admins; private TLRPC.TL_channelAdminLogEventsFilter currentFilter = null; private String searchQuery = ""; private LongSparseArray<TLRPC.User> selectedAdmins; private final static int[] allowedNotificationsDuringChatListAnimations = new int[]{ NotificationCenter.chatInfoDidLoad, NotificationCenter.dialogsNeedReload, NotificationCenter.closeChats, NotificationCenter.messagesDidLoad, NotificationCenter.botKeyboardDidLoad }; private AnimationNotificationsLocker notificationsLocker = new AnimationNotificationsLocker(allowedNotificationsDuringChatListAnimations); private HashMap<String, Object> invitesCache = new HashMap<>(); private HashMap<Long, TLRPC.User> usersMap; private boolean linviteLoading; private PhotoViewer.PhotoViewerProvider provider = new PhotoViewer.EmptyPhotoViewerProvider() { @Override public PhotoViewer.PlaceProviderObject getPlaceForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index, boolean needPreview) { int count = chatListView.getChildCount(); for (int a = 0; a < count; a++) { ImageReceiver imageReceiver = null; View view = chatListView.getChildAt(a); if (view instanceof ChatMessageCell) { if (messageObject != null) { ChatMessageCell cell = (ChatMessageCell) view; MessageObject message = cell.getMessageObject(); if (message != null && message.getId() == messageObject.getId()) { imageReceiver = cell.getPhotoImage(); } } } else if (view instanceof ChatActionCell) { ChatActionCell cell = (ChatActionCell) view; MessageObject message = cell.getMessageObject(); if (message != null) { if (messageObject != null) { if (message.getId() == messageObject.getId()) { imageReceiver = cell.getPhotoImage(); } } else if (fileLocation != null && message.photoThumbs != null) { for (int b = 0; b < message.photoThumbs.size(); b++) { TLRPC.PhotoSize photoSize = message.photoThumbs.get(b); if (photoSize.location.volume_id == fileLocation.volume_id && photoSize.location.local_id == fileLocation.local_id) { imageReceiver = cell.getPhotoImage(); break; } } } } } if (imageReceiver != null) { int[] coords = new int[2]; view.getLocationInWindow(coords); PhotoViewer.PlaceProviderObject object = new PhotoViewer.PlaceProviderObject(); object.viewX = coords[0]; object.viewY = coords[1] - (Build.VERSION.SDK_INT >= 21 ? 0 : AndroidUtilities.statusBarHeight); object.parentView = chatListView; object.imageReceiver = imageReceiver; object.thumb = imageReceiver.getBitmapSafe(); object.radius = imageReceiver.getRoundRadius(); object.isEvent = true; return object; } } return null; } }; private ChatListItemAnimator chatListItemAnimator; public ChannelAdminLogActivity(TLRPC.Chat chat) { currentChat = chat; } @Override public boolean onFragmentCreate() { super.onFragmentCreate(); NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.emojiLoaded); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingDidStart); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingPlayStateChanged); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingDidReset); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingProgressDidChanged); NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.didSetNewWallpapper); loadMessages(true); loadAdmins(); Bulletin.addDelegate(this, new Bulletin.Delegate() { @Override public int getBottomOffset(int tag) { return dp(51); } }); return true; } @Override public void onFragmentDestroy() { super.onFragmentDestroy(); NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.emojiLoaded); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.messagePlayingDidStart); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.messagePlayingPlayStateChanged); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.messagePlayingDidReset); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.messagePlayingProgressDidChanged); NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.didSetNewWallpapper); notificationsLocker.unlock(); } private void updateEmptyPlaceholder() { if (emptyView == null) { return; } if (!TextUtils.isEmpty(searchQuery)) { emptyImageView.setVisibility(View.GONE); emptyView.setPadding(dp(8), dp(3), dp(8), dp(3)); emptyView.setText(AndroidUtilities.replaceTags(LocaleController.getString(R.string.NoLogFound))); } else if (selectedAdmins != null || currentFilter != null) { emptyImageView.setVisibility(View.GONE); emptyView.setPadding(dp(8), dp(3), dp(8), dp(3)); emptyView.setText(AndroidUtilities.replaceTags(LocaleController.getString(R.string.NoLogFoundFiltered))); } else { emptyImageView.setVisibility(View.VISIBLE); emptyView.setPadding(dp(16), dp(16), dp(16), dp(16)); if (currentChat.megagroup) { emptyView.setText(smallerNewNewLine(AndroidUtilities.replaceTags(getString(R.string.EventLogEmpty2)))); } else { emptyView.setText(smallerNewNewLine(AndroidUtilities.replaceTags(getString(R.string.EventLogEmptyChannel2)))); } } } private CharSequence smallerNewNewLine(CharSequence cs) { int index = AndroidUtilities.charSequenceIndexOf(cs, "\n\n"); if (index >= 0 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { if (!(cs instanceof Spannable)) cs = new SpannableStringBuilder(cs); ((SpannableStringBuilder) cs).setSpan(new LineHeightSpan.Standard(dp(8)), index + 1, index + 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } return cs; } public void reloadLastMessages() { if (reloadingLastMessages) { return; } reloadingLastMessages = true; TLRPC.TL_channels_getAdminLog req = new TLRPC.TL_channels_getAdminLog(); req.channel = MessagesController.getInputChannel(currentChat); req.q = searchQuery; req.limit = 10; req.max_id = 0; req.min_id = 0; if (currentFilter != null) { req.flags |= 1; req.events_filter = currentFilter; } if (selectedAdmins != null) { req.flags |= 2; for (int a = 0; a < selectedAdmins.size(); a++) { req.admins.add(MessagesController.getInstance(currentAccount).getInputUser(selectedAdmins.valueAt(a))); } } ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> { if (response != null) { final TLRPC.TL_channels_adminLogResults res = (TLRPC.TL_channels_adminLogResults) response; AndroidUtilities.runOnUIThread(() -> { reloadingLastMessages = false; chatListItemAnimator.setShouldAnimateEnterFromBottom(false); saveScrollPosition(false); MessagesController.getInstance(currentAccount).putUsers(res.users, false); MessagesController.getInstance(currentAccount).putChats(res.chats, false); ArrayList<MessageObject> messages = new ArrayList<>(); HashMap<String, ArrayList<MessageObject>> messagesByDays = new HashMap<>(); boolean added = false; for (int a = 0; a < res.events.size(); a++) { TLRPC.TL_channelAdminLogEvent event = res.events.get(a); if (messagesDict.indexOfKey(event.id) >= 0) { continue; } if (event.action instanceof TLRPC.TL_channelAdminLogEventActionParticipantToggleAdmin) { TLRPC.TL_channelAdminLogEventActionParticipantToggleAdmin action = (TLRPC.TL_channelAdminLogEventActionParticipantToggleAdmin) event.action; if (action.prev_participant instanceof TLRPC.TL_channelParticipantCreator && !(action.new_participant instanceof TLRPC.TL_channelParticipantCreator)) { continue; } } minEventId = Math.min(minEventId, event.id); MessageObject messageObject = new MessageObject(currentAccount, event, messages, messagesByDays, currentChat, mid, false); if (messageObject.contentType < 0 || messageObject.currentEvent != null && messageObject.currentEvent.action instanceof TLRPC.TL_channelAdminLogEventActionDeleteMessage) { continue; } if (!messagesDict.containsKey(event.id)) { added = true; this.messages.add(0, messageObject); messagesDict.put(event.id, messageObject); } } if (chatAdapter != null && added) { filterDeletedMessages(); chatAdapter.notifyDataSetChanged(); } }); } }); } private void loadMessages(boolean reset) { if (loading) { return; } if (reset) { minEventId = Long.MAX_VALUE; if (progressView != null) { AndroidUtilities.updateViewVisibilityAnimated(progressView, true, 0.3f, true); emptyViewContainer.setVisibility(View.INVISIBLE); chatListView.setEmptyView(null); } messagesDict.clear(); messages.clear(); messagesByDays.clear(); filterDeletedMessages(); loadsCount = 0; } loading = true; TLRPC.TL_channels_getAdminLog req = new TLRPC.TL_channels_getAdminLog(); req.channel = MessagesController.getInputChannel(currentChat); req.q = searchQuery; req.limit = 50; if (!reset && !messages.isEmpty()) { req.max_id = minEventId; } else { req.max_id = 0; } req.min_id = 0; if (currentFilter != null) { req.flags |= 1; req.events_filter = currentFilter; } if (selectedAdmins != null) { req.flags |= 2; for (int a = 0; a < selectedAdmins.size(); a++) { req.admins.add(MessagesController.getInstance(currentAccount).getInputUser(selectedAdmins.valueAt(a))); } } loadsCount++; updateEmptyPlaceholder(); ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> { if (response != null) { final TLRPC.TL_channels_adminLogResults res = (TLRPC.TL_channels_adminLogResults) response; AndroidUtilities.runOnUIThread(() -> { loadsCount--; chatListItemAnimator.setShouldAnimateEnterFromBottom(false); saveScrollPosition(false); MessagesController.getInstance(currentAccount).putUsers(res.users, false); MessagesController.getInstance(currentAccount).putChats(res.chats, false); boolean added = false; int oldRowsCount = messages.size(); for (int a = 0; a < res.events.size(); a++) { TLRPC.TL_channelAdminLogEvent event = res.events.get(a); if (messagesDict.indexOfKey(event.id) >= 0) { continue; } if (event.action instanceof TLRPC.TL_channelAdminLogEventActionParticipantToggleAdmin) { TLRPC.TL_channelAdminLogEventActionParticipantToggleAdmin action = (TLRPC.TL_channelAdminLogEventActionParticipantToggleAdmin) event.action; if (action.prev_participant instanceof TLRPC.TL_channelParticipantCreator && !(action.new_participant instanceof TLRPC.TL_channelParticipantCreator)) { continue; } } minEventId = Math.min(minEventId, event.id); added = true; MessageObject messageObject = new MessageObject(currentAccount, event, messages, messagesByDays, currentChat, mid, false); if (messageObject.contentType < 0) { continue; } messagesDict.put(event.id, messageObject); } int newRowsCount = messages.size() - oldRowsCount; ArrayList<MessageObject> missingReplies = new ArrayList<>(); for (int i = oldRowsCount; i < messages.size(); ++i) { MessageObject msg = messages.get(i); if (msg != null && msg.contentType != 0 && msg.getRealId() >= 0) { realMessagesDict.put(msg.getRealId(), msg); } if (msg == null || msg.messageOwner == null || msg.messageOwner.reply_to == null) { continue; } TLRPC.MessageReplyHeader replyTo = msg.messageOwner.reply_to; if (replyTo.reply_to_peer_id == null) { MessageObject replyMessage = null; for (int j = 0; j < messages.size(); ++j) { if (i == j) continue; MessageObject msg2 = messages.get(j); if (msg2.contentType != 1 && msg2.getRealId() == replyTo.reply_to_msg_id) { replyMessage = msg2; break; } } if (replyMessage != null) { msg.replyMessageObject = replyMessage; } } missingReplies.add(msg); } if (!missingReplies.isEmpty()) { MediaDataController.getInstance(currentAccount).loadReplyMessagesForMessages(missingReplies, -currentChat.id, ChatActivity.MODE_DEFAULT, 0, () -> { saveScrollPosition(false); chatAdapter.notifyDataSetChanged(); }, getClassGuid()); } filterDeletedMessages(); loading = false; if (!added) { endReached = true; } AndroidUtilities.updateViewVisibilityAnimated(progressView, false, 0.3f, true); chatListView.setEmptyView(emptyViewContainer); if (chatAdapter != null) { chatAdapter.notifyDataSetChanged(); } if (searchItem != null) { searchItem.setVisibility(filteredMessages.isEmpty() && TextUtils.isEmpty(searchQuery) ? View.GONE : View.VISIBLE); } }); } }); if (reset && chatAdapter != null) { chatAdapter.notifyDataSetChanged(); } } private final ArrayList<Integer> filteredMessagesUpdatedPosition = new ArrayList<>(); private void filterDeletedMessages() { ArrayList<MessageObject> newFilteredMessages = new ArrayList<>(); ArrayList<MessageObject> currentDeleteGroup = new ArrayList<>(); filteredMessagesUpdatedPosition.clear(); for (int i = 0; i < messages.size(); ++i) { MessageObject message = messages.get(i); long thisMessageDeletedBy = messageDeletedBy(message); if (message.stableId <= 0) { message.stableId = lastStableId++; } MessageObject nextMessage = i + 1 < messages.size() ? messages.get(i + 1) : null; long nextMessageDeletedBy = messageDeletedBy(nextMessage); if (thisMessageDeletedBy != 0) { currentDeleteGroup.add(message); } else { newFilteredMessages.add(message); } if (thisMessageDeletedBy != nextMessageDeletedBy && !currentDeleteGroup.isEmpty()) { boolean wasKeyboard = message.messageOwner.reply_markup != null && !(message.messageOwner.reply_markup.rows.isEmpty()); int index = newFilteredMessages.size(); ArrayList<MessageObject> separatedFirstActions = new ArrayList<>(); for (int j = currentDeleteGroup.size() - 1; j >= 0; j--) { if (currentDeleteGroup.get(j).contentType == 1) { separatedFirstActions.add(currentDeleteGroup.remove(j)); } else { break; } } if (!currentDeleteGroup.isEmpty()) { MessageObject lastMessage = currentDeleteGroup.get(currentDeleteGroup.size() - 1); boolean expandable = TextUtils.isEmpty(searchQuery) && currentDeleteGroup.size() > 3; if (expandedEvents.contains(lastMessage.eventId) || !expandable) { for (int k = 0; k < currentDeleteGroup.size(); ++k) { setupExpandButton(currentDeleteGroup.get(k), 0); } newFilteredMessages.addAll(currentDeleteGroup); } else { setupExpandButton(lastMessage, currentDeleteGroup.size() - 1); newFilteredMessages.add(lastMessage); } if (wasKeyboard != (lastMessage.messageOwner.reply_markup != null && !(lastMessage.messageOwner.reply_markup.rows.isEmpty()))) { lastMessage.forceUpdate = true; chatAdapter.notifyItemChanged(index + (wasKeyboard ? currentDeleteGroup.size() - 1 : 0)); chatAdapter.notifyItemChanged(index + (wasKeyboard ? currentDeleteGroup.size() - 1 : 0) + 1); } newFilteredMessages.add(actionMessagesDeletedBy(message.eventId, message.currentEvent.user_id, currentDeleteGroup, expandedEvents.contains(message.eventId), expandable)); } if (!separatedFirstActions.isEmpty()) { MessageObject lastMessage = separatedFirstActions.get(separatedFirstActions.size() - 1); newFilteredMessages.addAll(separatedFirstActions); newFilteredMessages.add(actionMessagesDeletedBy(lastMessage.eventId, lastMessage.currentEvent.user_id, separatedFirstActions, true, false)); } currentDeleteGroup.clear(); } } filteredMessages.clear(); filteredMessages.addAll(newFilteredMessages); } private final LongSparseArray<Integer> stableIdByEventExpand = new LongSparseArray<>(); private MessageObject actionMessagesDeletedBy(long eventId, long user_id, ArrayList<MessageObject> messages, boolean expanded, boolean expandable) { MessageObject messageObject = null; for (int i = 0; i < filteredMessages.size(); ++i) { MessageObject messageObject1 = filteredMessages.get(i); if (messageObject1 != null && messageObject1.contentType == 1 && messageObject1.actionDeleteGroupEventId == eventId) { messageObject = messageObject1; break; } } if (messageObject == null) { TLRPC.TL_message msg = new TLRPC.TL_message(); msg.dialog_id = -currentChat.id; msg.id = -1; try { msg.date = messages.get(0).messageOwner.date; } catch (Exception e) { FileLog.e(e); } messageObject = new MessageObject(currentAccount, msg, false, false); } TLRPC.User user = getMessagesController().getUser(user_id); messageObject.contentType = 1; if (expandable && messages.size() > 1) { messageObject.actionDeleteGroupEventId = eventId; } else { messageObject.actionDeleteGroupEventId = -1; } String names = TextUtils.join(", ", messages.stream().map(MessageObject::getFromChatId).distinct().map(dialogId -> { if (dialogId < 0) { TLRPC.Chat chat = getMessagesController().getChat(-dialogId); if (chat == null) return null; return chat.title; } else { return UserObject.getForcedFirstName(getMessagesController().getUser(dialogId)); } }).filter(s -> s != null).limit(4).toArray()); SpannableStringBuilder ssb = new SpannableStringBuilder(replaceWithLink(LocaleController.formatPluralString(expandable ? "EventLogDeletedMultipleMessagesToExpand" : "EventLogDeletedMultipleMessages", messages.size(), names), "un1", user)); if (expandable && messages.size() > 1) { ProfileActivity.ShowDrawable drawable = findDrawable(messageObject.messageText); if (drawable == null) { drawable = new ProfileActivity.ShowDrawable(getString(expanded ? R.string.EventLogDeletedMultipleMessagesHide : R.string.EventLogDeletedMultipleMessagesShow)); drawable.textDrawable.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM)); drawable.textDrawable.setTextSize(dp(10)); drawable.setTextColor(Color.WHITE); drawable.setBackgroundColor(0x1e000000); } else { drawable.textDrawable.setText(getString(expanded ? R.string.EventLogDeletedMultipleMessagesHide : R.string.EventLogDeletedMultipleMessagesShow), false); } drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); ssb.append(" S"); ssb.setSpan(new ColoredImageSpan(drawable), ssb.length() - 1, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } messageObject.messageText = ssb; MessageObject lastMessage = messages.size() <= 0 ? null : messages.get(messages.size() - 1); if (lastMessage != null) { if (!stableIdByEventExpand.containsKey(lastMessage.eventId)) stableIdByEventExpand.put(lastMessage.eventId, lastStableId++); messageObject.stableId = stableIdByEventExpand.get(lastMessage.eventId); } return messageObject; } public static ProfileActivity.ShowDrawable findDrawable(CharSequence messageText) { if (messageText instanceof Spannable) { ColoredImageSpan[] spans = ((Spannable) messageText).getSpans(0, messageText.length(), ColoredImageSpan.class); for (int i = 0; i < spans.length; ++i) { if (spans[i] != null && spans[i].drawable instanceof ProfileActivity.ShowDrawable) { return (ProfileActivity.ShowDrawable) spans[i].drawable; } } } return null; } private void setupExpandButton(MessageObject msg, int count) { if (msg == null) { return; } if (count <= 0) { if (msg.messageOwner.reply_markup != null) { msg.messageOwner.reply_markup.rows.clear(); } } else { TLRPC.TL_replyInlineMarkup markup = new TLRPC.TL_replyInlineMarkup(); msg.messageOwner.reply_markup = markup; TLRPC.TL_keyboardButtonRow row = new TLRPC.TL_keyboardButtonRow(); markup.rows.add(row); TLRPC.TL_keyboardButton button = new TLRPC.TL_keyboardButton(); button.text = LocaleController.formatPluralString("EventLogExpandMore", count); row.buttons.add(button); } msg.measureInlineBotButtons(); } private long messageDeletedBy(MessageObject msg) { if (msg == null || msg.currentEvent == null || !(msg.currentEvent.action instanceof TLRPC.TL_channelAdminLogEventActionDeleteMessage)) { return 0; } return msg.currentEvent.user_id; } @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.emojiLoaded) { if (chatListView != null) { chatListView.invalidateViews(); } } else if (id == NotificationCenter.messagePlayingDidStart) { MessageObject messageObject = (MessageObject) args[0]; if (messageObject.isRoundVideo()) { MediaController.getInstance().setTextureView(createTextureView(true), aspectRatioFrameLayout, roundVideoContainer, true); updateTextureViewPosition(); } if (chatListView != null) { int count = chatListView.getChildCount(); for (int a = 0; a < count; a++) { View view = chatListView.getChildAt(a); if (view instanceof ChatMessageCell) { ChatMessageCell cell = (ChatMessageCell) view; MessageObject messageObject1 = cell.getMessageObject(); if (messageObject1 != null) { if (messageObject1.isVoice() || messageObject1.isMusic()) { cell.updateButtonState(false, true, false); } else if (messageObject1.isRoundVideo()) { cell.checkVideoPlayback(false, null); if (!MediaController.getInstance().isPlayingMessage(messageObject1)) { if (messageObject1.audioProgress != 0) { messageObject1.resetPlayingProgress(); cell.invalidate(); } } } } } } } } else if (id == NotificationCenter.messagePlayingDidReset || id == NotificationCenter.messagePlayingPlayStateChanged) { if (chatListView != null) { int count = chatListView.getChildCount(); for (int a = 0; a < count; a++) { View view = chatListView.getChildAt(a); if (view instanceof ChatMessageCell) { ChatMessageCell cell = (ChatMessageCell) view; MessageObject messageObject = cell.getMessageObject(); if (messageObject != null) { if (messageObject.isVoice() || messageObject.isMusic()) { cell.updateButtonState(false, true, false); } else if (messageObject.isRoundVideo()) { if (!MediaController.getInstance().isPlayingMessage(messageObject)) { cell.checkVideoPlayback(true, null); } } } } } } } else if (id == NotificationCenter.messagePlayingProgressDidChanged) { Integer mid = (Integer) args[0]; if (chatListView != null) { int count = chatListView.getChildCount(); for (int a = 0; a < count; a++) { View view = chatListView.getChildAt(a); if (view instanceof ChatMessageCell) { ChatMessageCell cell = (ChatMessageCell) view; MessageObject playing = cell.getMessageObject(); if (playing != null && playing.getId() == mid) { MessageObject player = MediaController.getInstance().getPlayingMessageObject(); if (player != null) { playing.audioProgress = player.audioProgress; playing.audioProgressSec = player.audioProgressSec; playing.audioPlayerDuration = player.audioPlayerDuration; cell.updatePlayingMessageProgress(); } break; } } } } } else if (id == NotificationCenter.didSetNewWallpapper) { if (fragmentView != null) { contentView.setBackgroundImage(Theme.getCachedWallpaper(), Theme.isWallpaperMotion()); progressView2.invalidate(); if (emptyView != null) { emptyView.invalidate(); } chatListView.invalidateViews(); } } } private void updateBottomOverlay() { /*if (searchItem != null && searchItem.getVisibility() == View.VISIBLE) { searchContainer.setVisibility(View.VISIBLE); bottomOverlayChat.setVisibility(View.INVISIBLE); } else { searchContainer.setVisibility(View.INVISIBLE); bottomOverlayChat.setVisibility(View.VISIBLE); }*/ } @Override public View createView(Context context) { if (chatMessageCellsCache.isEmpty()) { for (int a = 0; a < 8; a++) { chatMessageCellsCache.add(new ChatMessageCell(context)); } } searchWas = false; hasOwnBackground = true; Theme.createChatResources(context, false); actionBar.setAddToContainer(false); actionBar.setOccupyStatusBar(Build.VERSION.SDK_INT >= 21 && !AndroidUtilities.isTablet()); actionBar.setBackButtonDrawable(new BackDrawable(false)); actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override public void onItemClick(final int id) { if (id == -1) { finishFragment(); } } }); avatarContainer = new ChatAvatarContainer(context, null, false); avatarContainer.setOccupyStatusBar(!AndroidUtilities.isTablet()); actionBar.addView(avatarContainer, 0, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 56, 0, 40, 0)); ActionBarMenu menu = actionBar.createMenu(); searchItem = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() { @Override public void onSearchCollapse() { searchQuery = ""; avatarContainer.setVisibility(View.VISIBLE); if (searchWas) { searchWas = false; loadMessages(true); } /*highlightMessageId = Integer.MAX_VALUE; updateVisibleRows(); scrollToLastMessage(false); */ updateBottomOverlay(); } @Override public void onSearchExpand() { avatarContainer.setVisibility(View.GONE); updateBottomOverlay(); } @Override public void onSearchPressed(EditText editText) { searchWas = true; searchQuery = editText.getText().toString(); loadMessages(true); //updateSearchButtons(0, 0, 0); } }); searchItem.setSearchFieldHint(getString("Search", R.string.Search)); avatarContainer.setEnabled(false); avatarContainer.setTitle(currentChat.title); avatarContainer.setSubtitle(getString("EventLogAllEvents", R.string.EventLogAllEvents)); avatarContainer.setChatAvatar(currentChat); fragmentView = new SizeNotifierFrameLayout(context) { final AdjustPanLayoutHelper adjustPanLayoutHelper = new AdjustPanLayoutHelper(this) { @Override protected void onTransitionStart(boolean keyboardVisible, int contentHeight) { wasManualScroll = true; } @Override protected void onTransitionEnd() { } @Override protected void onPanTranslationUpdate(float y, float progress, boolean keyboardVisible) { if (getParentLayout() != null && getParentLayout().isPreviewOpenAnimationInProgress()) { return; } contentPanTranslation = y; contentPanTranslationT = progress; actionBar.setTranslationY(y); if (emptyViewContainer != null) { emptyViewContainer.setTranslationY(y / 2); } progressView.setTranslationY(y / 2); contentView.setBackgroundTranslation((int) y); setFragmentPanTranslationOffset((int) y); // invalidateChatListViewTopPadding(); // invalidateMessagesVisiblePart(); chatListView.invalidate(); // updateBulletinLayout(); if (AndroidUtilities.isTablet() && getParentActivity() instanceof LaunchActivity) { BaseFragment mainFragment = ((LaunchActivity)getParentActivity()).getActionBarLayout().getLastFragment(); if (mainFragment instanceof DialogsActivity) { ((DialogsActivity)mainFragment).setPanTranslationOffset(y); } } } @Override protected boolean heightAnimationEnabled() { INavigationLayout actionBarLayout = getParentLayout(); if (inPreviewMode || inBubbleMode || AndroidUtilities.isInMultiwindow || actionBarLayout == null) { return false; } if (System.currentTimeMillis() - activityResumeTime < 250) { return false; } if ((ChannelAdminLogActivity.this == actionBarLayout.getLastFragment() && actionBarLayout.isTransitionAnimationInProgress()) || actionBarLayout.isPreviewOpenAnimationInProgress() || isPaused || !openAnimationEnded) { return false; } return true; } }; @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject(); if (messageObject != null && messageObject.isRoundVideo() && messageObject.eventId != 0 && messageObject.getDialogId() == -currentChat.id) { MediaController.getInstance().setTextureView(createTextureView(false), aspectRatioFrameLayout, roundVideoContainer, true); } } @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { boolean result = super.drawChild(canvas, child, drawingTime); if (child == actionBar && parentLayout != null) { parentLayout.drawHeaderShadow(canvas, actionBar.getVisibility() == VISIBLE ? actionBar.getMeasuredHeight() : 0); } return result; } @Override protected boolean isActionBarVisible() { return actionBar.getVisibility() == VISIBLE; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int allHeight; int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); setMeasuredDimension(widthSize, heightSize); heightSize -= getPaddingTop(); measureChildWithMargins(actionBar, widthMeasureSpec, 0, heightMeasureSpec, 0); int actionBarHeight = actionBar.getMeasuredHeight(); if (actionBar.getVisibility() == VISIBLE) { heightSize -= actionBarHeight; } int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); if (child == null || child.getVisibility() == GONE || child == actionBar) { continue; } if (child == chatListView || child == progressView) { int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY); int contentHeightSpec = MeasureSpec.makeMeasureSpec(Math.max(dp(10), heightSize - dp(48 + 2)), MeasureSpec.EXACTLY); child.measure(contentWidthSpec, contentHeightSpec); } else if (child == emptyViewContainer) { int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY); int contentHeightSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY); child.measure(contentWidthSpec, contentHeightSpec); } else { measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0); } } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int width = child.getMeasuredWidth(); final int height = child.getMeasuredHeight(); int childLeft; int childTop; int gravity = lp.gravity; if (gravity == -1) { gravity = Gravity.TOP | Gravity.LEFT; } final int absoluteGravity = gravity & Gravity.HORIZONTAL_GRAVITY_MASK; final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK; switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { case Gravity.CENTER_HORIZONTAL: childLeft = (r - l - width) / 2 + lp.leftMargin - lp.rightMargin; break; case Gravity.RIGHT: childLeft = r - width - lp.rightMargin; break; case Gravity.LEFT: default: childLeft = lp.leftMargin; } switch (verticalGravity) { case Gravity.TOP: childTop = lp.topMargin + getPaddingTop(); if (child != actionBar && actionBar.getVisibility() == VISIBLE) { childTop += actionBar.getMeasuredHeight(); } break; case Gravity.CENTER_VERTICAL: childTop = (b - t - height) / 2 + lp.topMargin - lp.bottomMargin; break; case Gravity.BOTTOM: childTop = (b - t) - height - lp.bottomMargin; break; default: childTop = lp.topMargin; } if (child == emptyViewContainer) { childTop -= dp(24) - (actionBar.getVisibility() == VISIBLE ? actionBar.getMeasuredHeight() / 2 : 0); } else if (child == actionBar) { childTop -= getPaddingTop(); } else if (child == backgroundView) { childTop = 0; } child.layout(childLeft, childTop, childLeft + width, childTop + height); } updateMessagesVisiblePart(); notifyHeightChanged(); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (AvatarPreviewer.hasVisibleInstance()) { AvatarPreviewer.getInstance().onTouchEvent(ev); return true; } return super.dispatchTouchEvent(ev); } }; contentView = (SizeNotifierFrameLayout) fragmentView; contentView.setOccupyStatusBar(!AndroidUtilities.isTablet()); contentView.setBackgroundImage(Theme.getCachedWallpaper(), Theme.isWallpaperMotion()); emptyViewContainer = new FrameLayout(context); emptyViewContainer.setVisibility(View.INVISIBLE); contentView.addView(emptyViewContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER)); emptyViewContainer.setOnTouchListener((v, event) -> true); emptyLayoutView = new LinearLayout(context); emptyLayoutView.setBackground(Theme.createServiceDrawable(dp(12), emptyView, contentView)); emptyLayoutView.setOrientation(LinearLayout.VERTICAL); emptyImageView = new ImageView(context); emptyImageView.setScaleType(ImageView.ScaleType.CENTER); emptyImageView.setImageResource(R.drawable.large_log_actions); emptyImageView.setColorFilter(new PorterDuffColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN)); emptyImageView.setVisibility(View.GONE); emptyLayoutView.addView(emptyImageView, LayoutHelper.createLinear(54, 54, Gravity.CENTER, 16, 20, 16, -4)); emptyView = new TextView(context) { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(MeasureSpec.makeMeasureSpec(Math.min(MeasureSpec.getSize(widthMeasureSpec), dp(220)), MeasureSpec.getMode(widthMeasureSpec)), heightMeasureSpec); } }; emptyView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); emptyView.setGravity(Gravity.CENTER); emptyView.setTextColor(Theme.getColor(Theme.key_chat_serviceText)); emptyView.setPadding(dp(8), dp(5), dp(8), dp(5)); emptyLayoutView.addView(emptyView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 0, 0, 0)); emptyViewContainer.addView(emptyLayoutView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 20, 0, 20, 0)); chatListView = new RecyclerListView(context) { @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { applyScrolledPosition(); super.onLayout(changed, l, t, r, b); } @Override public boolean drawChild(Canvas canvas, View child, long drawingTime) { boolean result = super.drawChild(canvas, child, drawingTime); if (child instanceof ChatMessageCell) { ChatMessageCell chatMessageCell = (ChatMessageCell) child; ImageReceiver imageReceiver = chatMessageCell.getAvatarImage(); if (imageReceiver != null) { boolean updateVisibility = !chatMessageCell.getMessageObject().deleted && chatListView.getChildAdapterPosition(chatMessageCell) != RecyclerView.NO_POSITION; if (chatMessageCell.getMessageObject().deleted) { imageReceiver.setVisible(false, false); return result; } int top = (int) child.getY(); if (chatMessageCell.drawPinnedBottom()) { int p; ViewHolder holder = chatListView.getChildViewHolder(child); p = holder.getAdapterPosition(); if (p >= 0) { int nextPosition; nextPosition = p + 1; holder = chatListView.findViewHolderForAdapterPosition(nextPosition); if (holder != null) { imageReceiver.setVisible(false, false); return result; } } } float tx = chatMessageCell.getSlidingOffsetX() + chatMessageCell.getCheckBoxTranslation(); int y = (int) child.getY() + chatMessageCell.getLayoutHeight(); int maxY = chatListView.getMeasuredHeight() - chatListView.getPaddingBottom(); if (y > maxY) { y = maxY; } if (chatMessageCell.drawPinnedTop()) { int p; ViewHolder holder = chatListView.getChildViewHolder(child); p = holder.getAdapterPosition(); if (p >= 0) { int tries = 0; while (true) { if (tries >= 20) { break; } tries++; int prevPosition; prevPosition = p - 1; holder = chatListView.findViewHolderForAdapterPosition(prevPosition); if (holder != null) { top = holder.itemView.getTop(); if (holder.itemView instanceof ChatMessageCell) { chatMessageCell = (ChatMessageCell) holder.itemView; if (!chatMessageCell.drawPinnedTop()) { break; } else { p = prevPosition; } } else { break; } } else { break; } } } } if (y - dp(48) < top) { y = top + dp(48); } if (!chatMessageCell.drawPinnedBottom()) { int cellBottom = (int) (chatMessageCell.getY() + chatMessageCell.getMeasuredHeight()); if (y > cellBottom) { y = cellBottom; } } canvas.save(); if (tx != 0) { canvas.translate(tx, 0); } if (chatMessageCell.getCurrentMessagesGroup() != null) { if (chatMessageCell.getCurrentMessagesGroup().transitionParams.backgroundChangeBounds) { y -= chatMessageCell.getTranslationY(); } } if (updateVisibility) { imageReceiver.setImageY(y - dp(44)); } if (chatMessageCell.shouldDrawAlphaLayer()) { imageReceiver.setAlpha(chatMessageCell.getAlpha()); canvas.scale( chatMessageCell.getScaleX(), chatMessageCell.getScaleY(), chatMessageCell.getX() + chatMessageCell.getPivotX(), chatMessageCell.getY() + (chatMessageCell.getHeight() >> 1) ); } else { imageReceiver.setAlpha(1f); } if (updateVisibility) { imageReceiver.setVisible(true, false); } imageReceiver.draw(canvas); canvas.restore(); } } return result; } }; chatListView.setOnItemClickListener(new RecyclerListView.OnItemClickListenerExtended() { @Override public void onItemClick(View view, int position, float x, float y) { if (view instanceof ChatActionCell) { MessageObject messageObject = ((ChatActionCell) view).getMessageObject(); if (messageObject != null && messageObject.actionDeleteGroupEventId != -1) { if (expandedEvents.contains(messageObject.actionDeleteGroupEventId)) { expandedEvents.remove(messageObject.actionDeleteGroupEventId); } else { expandedEvents.add(messageObject.actionDeleteGroupEventId); } saveScrollPosition(true); filterDeletedMessages(); chatAdapter.notifyDataSetChanged(); return; } } createMenu(view, x, y); } }); chatListView.setTag(1); chatListView.setVerticalScrollBarEnabled(true); chatListView.setAdapter(chatAdapter = new ChatActivityAdapter(context)); chatListView.setClipToPadding(false); chatListView.setPadding(0, dp(4), 0, dp(3)); chatListView.setItemAnimator(chatListItemAnimator = new ChatListItemAnimator(null, chatListView, resourceProvider) { int scrollAnimationIndex = -1; Runnable finishRunnable; public void onAnimationStart() { if (scrollAnimationIndex == -1) { scrollAnimationIndex = getNotificationCenter().setAnimationInProgress(scrollAnimationIndex, allowedNotificationsDuringChatListAnimations, false); } if (finishRunnable != null) { AndroidUtilities.cancelRunOnUIThread(finishRunnable); finishRunnable = null; } if (BuildVars.LOGS_ENABLED) { FileLog.d("admin logs chatItemAnimator disable notifications"); } } @Override protected void onAllAnimationsDone() { super.onAllAnimationsDone(); if (finishRunnable != null) { AndroidUtilities.cancelRunOnUIThread(finishRunnable); } AndroidUtilities.runOnUIThread(finishRunnable = () -> { if (scrollAnimationIndex != -1) { getNotificationCenter().onAnimationFinish(scrollAnimationIndex); scrollAnimationIndex = -1; } if (BuildVars.LOGS_ENABLED) { FileLog.d("admin logs chatItemAnimator enable notifications"); } }); } }); chatListItemAnimator.setReversePositions(true); chatListView.setLayoutAnimation(null); chatLayoutManager = new LinearLayoutManager(context) { @Override public boolean supportsPredictiveItemAnimations() { return true; } @Override public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) { scrollByTouch = false; LinearSmoothScrollerCustom linearSmoothScroller = new LinearSmoothScrollerCustom(recyclerView.getContext(), LinearSmoothScrollerCustom.POSITION_MIDDLE); linearSmoothScroller.setTargetPosition(position); startSmoothScroll(linearSmoothScroller); } @Override public void scrollToPositionWithOffset(int position, int offset) { super.scrollToPositionWithOffset(position, offset); } }; chatLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); chatLayoutManager.setStackFromEnd(true); chatListView.setLayoutManager(chatLayoutManager); chatScrollHelper = new RecyclerAnimationScrollHelper(chatListView, chatLayoutManager); chatScrollHelper.setScrollListener(this::updateMessagesVisiblePart); chatScrollHelper.setAnimationCallback(chatScrollHelperCallback); contentView.addView(chatListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); chatListView.setOnScrollListener(new RecyclerView.OnScrollListener() { private float totalDy = 0; private final int scrollValue = dp(100); @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { if (newState == RecyclerView.SCROLL_STATE_DRAGGING) { scrollingFloatingDate = true; checkTextureViewPosition = true; } else if (newState == RecyclerView.SCROLL_STATE_IDLE) { scrollingFloatingDate = false; checkTextureViewPosition = false; hideFloatingDateView(true); } } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { chatListView.invalidate(); if (dy != 0 && scrollingFloatingDate && !currentFloatingTopIsNotMessage) { if (floatingDateView.getTag() == null) { if (floatingDateAnimation != null) { floatingDateAnimation.cancel(); } floatingDateView.setTag(1); floatingDateAnimation = new AnimatorSet(); floatingDateAnimation.setDuration(150); floatingDateAnimation.playTogether(ObjectAnimator.ofFloat(floatingDateView, "alpha", 1.0f)); floatingDateAnimation.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (animation.equals(floatingDateAnimation)) { floatingDateAnimation = null; } } }); floatingDateAnimation.start(); } } checkScrollForLoad(true); updateMessagesVisiblePart(); } }); if (scrollToPositionOnRecreate != -1) { chatLayoutManager.scrollToPositionWithOffset(scrollToPositionOnRecreate, scrollToOffsetOnRecreate); scrollToPositionOnRecreate = -1; } progressView = new FrameLayout(context); progressView.setVisibility(View.INVISIBLE); contentView.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT)); progressView2 = new View(context); progressView2.setBackground(Theme.createServiceDrawable(dp(18), progressView2, contentView)); progressView.addView(progressView2, LayoutHelper.createFrame(36, 36, Gravity.CENTER)); progressBar = new RadialProgressView(context); progressBar.setSize(dp(28)); progressBar.setProgressColor(Theme.getColor(Theme.key_chat_serviceText)); progressView.addView(progressBar, LayoutHelper.createFrame(32, 32, Gravity.CENTER)); floatingDateView = new ChatActionCell(context); floatingDateView.setAlpha(0.0f); floatingDateView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); contentView.addView(floatingDateView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 4, 0, 0)); contentView.addView(actionBar); bottomOverlayChat = new FrameLayout(context) { @Override public void onDraw(Canvas canvas) { int bottom = Theme.chat_composeShadowDrawable.getIntrinsicHeight(); Theme.chat_composeShadowDrawable.setBounds(0, 0, getMeasuredWidth(), bottom); Theme.chat_composeShadowDrawable.draw(canvas); canvas.drawRect(0, bottom, getMeasuredWidth(), getMeasuredHeight(), Theme.chat_composeBackgroundPaint); } }; bottomOverlayChat.setWillNotDraw(false); bottomOverlayChat.setPadding(0, dp(3), 0, 0); contentView.addView(bottomOverlayChat, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM)); bottomOverlayChat.setOnClickListener(view -> { if (getParentActivity() == null) { return; } AdminLogFilterAlert2 adminLogFilterAlert = new AdminLogFilterAlert2(this, currentFilter, selectedAdmins, currentChat.megagroup); adminLogFilterAlert.setCurrentAdmins(admins); adminLogFilterAlert.setAdminLogFilterAlertDelegate((filter, admins) -> { currentFilter = filter; selectedAdmins = admins; if (currentFilter != null || selectedAdmins != null) { avatarContainer.setSubtitle(getString("EventLogSelectedEvents", R.string.EventLogSelectedEvents)); } else { avatarContainer.setSubtitle(getString("EventLogAllEvents", R.string.EventLogAllEvents)); } loadMessages(true); }); showDialog(adminLogFilterAlert); }); bottomOverlayChatText = new TextView(context); bottomOverlayChatText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); bottomOverlayChatText.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); bottomOverlayChatText.setTextColor(Theme.getColor(Theme.key_chat_fieldOverlayText)); bottomOverlayChatText.setText(getString("SETTINGS", R.string.SETTINGS).toUpperCase()); bottomOverlayChat.addView(bottomOverlayChatText, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER)); bottomOverlayImage = new ImageView(context); bottomOverlayImage.setImageResource(R.drawable.msg_help); bottomOverlayImage.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_fieldOverlayText), PorterDuff.Mode.MULTIPLY)); bottomOverlayImage.setScaleType(ImageView.ScaleType.CENTER); bottomOverlayChat.addView(bottomOverlayImage, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP, 3, 0, 0, 0)); bottomOverlayImage.setContentDescription(getString("BotHelp", R.string.BotHelp)); bottomOverlayImage.setOnClickListener(v -> { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); if (currentChat.megagroup) { builder.setMessage(AndroidUtilities.replaceTags(getString("EventLogInfoDetail", R.string.EventLogInfoDetail))); } else { builder.setMessage(AndroidUtilities.replaceTags(getString("EventLogInfoDetailChannel", R.string.EventLogInfoDetailChannel))); } builder.setPositiveButton(getString("OK", R.string.OK), null); builder.setTitle(getString("EventLogInfoTitle", R.string.EventLogInfoTitle)); showDialog(builder.create()); }); searchContainer = new FrameLayout(context) { @Override public void onDraw(Canvas canvas) { int bottom = Theme.chat_composeShadowDrawable.getIntrinsicHeight(); Theme.chat_composeShadowDrawable.setBounds(0, 0, getMeasuredWidth(), bottom); Theme.chat_composeShadowDrawable.draw(canvas); canvas.drawRect(0, bottom, getMeasuredWidth(), getMeasuredHeight(), Theme.chat_composeBackgroundPaint); } }; searchContainer.setWillNotDraw(false); searchContainer.setVisibility(View.INVISIBLE); searchContainer.setFocusable(true); searchContainer.setFocusableInTouchMode(true); searchContainer.setClickable(true); searchContainer.setPadding(0, dp(3), 0, 0); contentView.addView(searchContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM)); /*searchUpButton = new ImageView(context); searchUpButton.setScaleType(ImageView.ScaleType.CENTER); searchUpButton.setImageResource(R.drawable.msg_go_up); searchUpButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_searchPanelIcons), PorterDuff.Mode.MULTIPLY)); searchContainer.addView(searchUpButton, LayoutHelper.createFrame(48, 48)); searchUpButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MessagesSearchQuery.searchMessagesInChat(null, dialog_id, mergeDialogId, classGuid, 1); } }); searchDownButton = new ImageView(context); searchDownButton.setScaleType(ImageView.ScaleType.CENTER); searchDownButton.setImageResource(R.drawable.msg_go_down); searchDownButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_searchPanelIcons), PorterDuff.Mode.MULTIPLY)); searchContainer.addView(searchDownButton, LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP, 48, 0, 0, 0)); searchDownButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MessagesSearchQuery.searchMessagesInChat(null, dialog_id, mergeDialogId, classGuid, 2); } });*/ searchCalendarButton = new ImageView(context); searchCalendarButton.setScaleType(ImageView.ScaleType.CENTER); searchCalendarButton.setImageResource(R.drawable.msg_calendar); searchCalendarButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_searchPanelIcons), PorterDuff.Mode.MULTIPLY)); searchContainer.addView(searchCalendarButton, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP)); searchCalendarButton.setOnClickListener(view -> { if (getParentActivity() == null) { return; } AndroidUtilities.hideKeyboard(searchItem.getSearchField()); showDialog(AlertsCreator.createCalendarPickerDialog(getParentActivity(), 1375315200000L, param -> loadMessages(true), null).create()); }); searchCountText = new SimpleTextView(context); searchCountText.setTextColor(Theme.getColor(Theme.key_chat_searchPanelText)); searchCountText.setTextSize(15); searchCountText.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); searchContainer.addView(searchCountText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 108, 0, 0, 0)); chatAdapter.updateRows(); if (loading && messages.isEmpty()) { AndroidUtilities.updateViewVisibilityAnimated(progressView, true, 0.3f, true); chatListView.setEmptyView(null); } else { AndroidUtilities.updateViewVisibilityAnimated(progressView, false, 0.3f, true); chatListView.setEmptyView(emptyViewContainer); } chatListView.setAnimateEmptyView(true, RecyclerListView.EMPTY_VIEW_ANIMATION_TYPE_ALPHA_SCALE); undoView = new UndoView(context); undoView.setAdditionalTranslationY(dp(51)); contentView.addView(undoView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 8, 0, 8, 8)); updateEmptyPlaceholder(); return fragmentView; } private ActionBarPopupWindow scrimPopupWindow; private int scrimPopupX, scrimPopupY; private void closeMenu() { if (scrimPopupWindow != null) { scrimPopupWindow.dismiss(); } } private final static int OPTION_COPY = 3; private final static int OPTION_SAVE_TO_GALLERY = 4; private final static int OPTION_APPLY_FILE = 5; private final static int OPTION_SHARE = 6; private final static int OPTION_SAVE_TO_GALLERY2 = 7; private final static int OPTION_SAVE_STICKER = 9; private final static int OPTION_SAVE_TO_DOWNLOADS_OR_MUSIC = 10; private final static int OPTION_SAVE_TO_GIFS = 11; private final static int OPTION_ADD_CONTACT = 15; private final static int OPTION_COPY_PHONE = 16; private final static int OPTION_CALL = 17; private final static int OPTION_RESTRICT = 33; private final static int OPTION_REPORT_FALSE_POSITIVE = 34; private final static int OPTION_BAN = 35; private boolean createMenu(View v) { return createMenu(v, 0, 0); } private boolean createMenu(View v, float x, float y) { MessageObject message = null; if (v instanceof ChatMessageCell) { message = ((ChatMessageCell) v).getMessageObject(); } else if (v instanceof ChatActionCell) { message = ((ChatActionCell) v).getMessageObject(); } if (message == null) { return false; } final int type = getMessageType(message); selectedObject = message; if (getParentActivity() == null) { return false; } ArrayList<CharSequence> items = new ArrayList<>(); final ArrayList<Integer> options = new ArrayList<>(); final ArrayList<Integer> icons = new ArrayList<>(); if (message.currentEvent != null && (message.currentEvent.action instanceof TLRPC.TL_channelAdminLogEventActionDeleteMessage && message.currentEvent.user_id == getMessagesController().telegramAntispamUserId || message.currentEvent.action instanceof TLRPC.TL_channelAdminLogEventActionToggleAntiSpam)) { if (v instanceof ChatActionCell) { SpannableString arrow = new SpannableString(">"); Drawable arrowDrawable = getContext().getResources().getDrawable(R.drawable.attach_arrow_right).mutate(); arrowDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_undo_cancelColor), PorterDuff.Mode.MULTIPLY)); arrowDrawable.setBounds(0, 0, dp(10), dp(10)); arrow.setSpan(new ImageSpan(arrowDrawable, DynamicDrawableSpan.ALIGN_CENTER), 0, arrow.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); SpannableStringBuilder link = new SpannableStringBuilder(); link .append(getString("EventLogFilterGroupInfo", R.string.EventLogFilterGroupInfo)) .append(" ") .append(arrow) .append(" ") .append(getString("ChannelAdministrators", R.string.ChannelAdministrators)); link.setSpan(new ClickableSpan() { @Override public void onClick(@NonNull View view) { finishFragment(); } @Override public void updateDrawState(@NonNull TextPaint ds) { super.updateDrawState(ds); ds.setUnderlineText(false); } }, 0, link.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); CharSequence text = getString("ChannelAntiSpamInfo2", R.string.ChannelAntiSpamInfo2); text = AndroidUtilities.replaceCharSequence("%s", text, link); Bulletin bulletin = BulletinFactory.of(this).createSimpleBulletin(R.raw.msg_antispam, getString("ChannelAntiSpamUser", R.string.ChannelAntiSpamUser), text); bulletin.setDuration(Bulletin.DURATION_PROLONG); bulletin.show(); return true; } items.add(getString("ReportFalsePositive", R.string.ReportFalsePositive)); icons.add(R.drawable.msg_notspam); options.add(OPTION_REPORT_FALSE_POSITIVE); items.add(null); icons.add(null); options.add(null); } if (selectedObject.type == MessageObject.TYPE_TEXT || selectedObject.caption != null) { items.add(getString("Copy", R.string.Copy)); icons.add(R.drawable.msg_copy); options.add(OPTION_COPY); } if (type == 1) { if (selectedObject.currentEvent != null && selectedObject.currentEvent.action instanceof TLRPC.TL_channelAdminLogEventActionChangeStickerSet) { TLRPC.TL_channelAdminLogEventActionChangeStickerSet action = (TLRPC.TL_channelAdminLogEventActionChangeStickerSet) selectedObject.currentEvent.action; TLRPC.InputStickerSet stickerSet = action.new_stickerset; if (stickerSet == null || stickerSet instanceof TLRPC.TL_inputStickerSetEmpty) { stickerSet = action.prev_stickerset; } if (stickerSet != null) { showDialog(new StickersAlert(getParentActivity(), ChannelAdminLogActivity.this, stickerSet, null, null)); return true; } } else if (selectedObject.currentEvent != null && selectedObject.currentEvent.action instanceof TLRPC.TL_channelAdminLogEventActionChangeEmojiStickerSet) { GroupStickersActivity fragment = new GroupStickersActivity(currentChat.id, true); TLRPC.ChatFull chatInfo = getMessagesController().getChatFull(currentChat.id); if (chatInfo != null) { fragment.setInfo(chatInfo); presentFragment(fragment); } } else if (selectedObject.currentEvent != null && selectedObject.currentEvent.action instanceof TLRPC.TL_channelAdminLogEventActionChangeHistoryTTL) { if (ChatObject.canUserDoAdminAction(currentChat, ChatObject.ACTION_DELETE_MESSAGES)) { ClearHistoryAlert alert = new ClearHistoryAlert(getParentActivity(), null, currentChat, false, null); alert.setDelegate(new ClearHistoryAlert.ClearHistoryAlertDelegate() { @Override public void onAutoDeleteHistory(int ttl, int action) { getMessagesController().setDialogHistoryTTL(-currentChat.id, ttl); TLRPC.ChatFull chatInfo = getMessagesController().getChatFull(currentChat.id); if (chatInfo != null) { undoView.showWithAction(-currentChat.id, action, null, chatInfo.ttl_period, null, null); } } }); showDialog(alert); } } } else if (type == 3) { if (selectedObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage && MessageObject.isNewGifDocument(selectedObject.messageOwner.media.webpage.document)) { items.add(getString("SaveToGIFs", R.string.SaveToGIFs)); icons.add(R.drawable.msg_gif); options.add(OPTION_SAVE_TO_GIFS); } } else if (type == 4) { if (selectedObject.isVideo()) { items.add(getString("SaveToGallery", R.string.SaveToGallery)); icons.add(R.drawable.msg_gallery); options.add(OPTION_SAVE_TO_GALLERY); items.add(getString("ShareFile", R.string.ShareFile)); icons.add(R.drawable.msg_share); options.add(OPTION_SHARE); } else if (selectedObject.isMusic()) { items.add(getString("SaveToMusic", R.string.SaveToMusic)); icons.add(R.drawable.msg_download); options.add(OPTION_SAVE_TO_DOWNLOADS_OR_MUSIC); items.add(getString("ShareFile", R.string.ShareFile)); icons.add(R.drawable.msg_share); options.add(OPTION_SHARE); } else if (selectedObject.getDocument() != null) { if (MessageObject.isNewGifDocument(selectedObject.getDocument())) { items.add(getString("SaveToGIFs", R.string.SaveToGIFs)); icons.add(R.drawable.msg_gif); options.add(OPTION_SAVE_TO_GIFS); } items.add(getString("SaveToDownloads", R.string.SaveToDownloads)); icons.add(R.drawable.msg_download); options.add(OPTION_SAVE_TO_DOWNLOADS_OR_MUSIC); items.add(getString("ShareFile", R.string.ShareFile)); icons.add(R.drawable.msg_share); options.add(OPTION_SHARE); } else { items.add(getString("SaveToGallery", R.string.SaveToGallery)); icons.add(R.drawable.msg_gallery); options.add(OPTION_SAVE_TO_GALLERY); } } else if (type == 5) { items.add(getString("ApplyLocalizationFile", R.string.ApplyLocalizationFile)); icons.add(R.drawable.msg_language); options.add(OPTION_APPLY_FILE); items.add(getString("SaveToDownloads", R.string.SaveToDownloads)); icons.add(R.drawable.msg_download); options.add(OPTION_SAVE_TO_DOWNLOADS_OR_MUSIC); items.add(getString("ShareFile", R.string.ShareFile)); icons.add(R.drawable.msg_share); options.add(OPTION_SHARE); } else if (type == 10) { items.add(getString("ApplyThemeFile", R.string.ApplyThemeFile)); icons.add(R.drawable.msg_theme); options.add(OPTION_APPLY_FILE); items.add(getString("SaveToDownloads", R.string.SaveToDownloads)); icons.add(R.drawable.msg_download); options.add(OPTION_SAVE_TO_DOWNLOADS_OR_MUSIC); items.add(getString("ShareFile", R.string.ShareFile)); icons.add(R.drawable.msg_share); options.add(OPTION_SHARE); } else if (type == 6) { items.add(getString("SaveToGallery", R.string.SaveToGallery)); icons.add(R.drawable.msg_gallery); options.add(OPTION_SAVE_TO_GALLERY2); items.add(getString("SaveToDownloads", R.string.SaveToDownloads)); icons.add(R.drawable.msg_download); options.add(OPTION_SAVE_TO_DOWNLOADS_OR_MUSIC); items.add(getString("ShareFile", R.string.ShareFile)); icons.add(R.drawable.msg_share); options.add(OPTION_SHARE); } else if (type == 7) { if (selectedObject.isMask()) { items.add(getString("AddToMasks", R.string.AddToMasks)); } else { items.add(getString("AddToStickers", R.string.AddToStickers)); } icons.add(R.drawable.msg_sticker); options.add(OPTION_SAVE_STICKER); } else if (type == 8) { long uid = selectedObject.messageOwner.media.user_id; TLRPC.User user = null; if (uid != 0) { user = MessagesController.getInstance(currentAccount).getUser(uid); } if (user != null && user.id != UserConfig.getInstance(currentAccount).getClientUserId() && ContactsController.getInstance(currentAccount).contactsDict.get(user.id) == null) { items.add(getString("AddContactTitle", R.string.AddContactTitle)); icons.add(R.drawable.msg_addcontact); options.add(OPTION_ADD_CONTACT); } if (!TextUtils.isEmpty(selectedObject.messageOwner.media.phone_number)) { items.add(getString("Copy", R.string.Copy)); icons.add(R.drawable.msg_copy); options.add(OPTION_COPY_PHONE); items.add(getString("Call", R.string.Call)); icons.add(R.drawable.msg_calls); options.add(OPTION_CALL); } } boolean callbackSent = false; Runnable proceed = () -> { if (options.isEmpty() || getParentActivity() == null) { return; } ActionBarPopupWindow.ActionBarPopupWindowLayout popupLayout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(getParentActivity(), R.drawable.popup_fixed_alert, getResourceProvider(), 0); popupLayout.setMinimumWidth(dp(200)); Rect backgroundPaddings = new Rect(); Drawable shadowDrawable = getParentActivity().getResources().getDrawable(R.drawable.popup_fixed_alert).mutate(); shadowDrawable.getPadding(backgroundPaddings); popupLayout.setBackgroundColor(getThemedColor(Theme.key_actionBarDefaultSubmenuBackground)); for (int a = 0, N = items.size(); a < N; ++a) { if (options.get(a) == null) { popupLayout.addView(new ActionBarPopupWindow.GapView(getContext(), getResourceProvider()), LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 8)); } else { ActionBarMenuSubItem cell = new ActionBarMenuSubItem(getParentActivity(), a == 0, a == N - 1, getResourceProvider()); cell.setMinimumWidth(dp(200)); cell.setTextAndIcon(items.get(a), icons.get(a)); if (options.get(a) == OPTION_BAN) { cell.setColors(getThemedColor(Theme.key_text_RedBold), getThemedColor(Theme.key_text_RedRegular)); } final Integer option = options.get(a); popupLayout.addView(cell); final int i = a; cell.setOnClickListener(v1 -> { if (selectedObject == null || i >= options.size()) { return; } processSelectedOption(option); }); } } ChatScrimPopupContainerLayout scrimPopupContainerLayout = new ChatScrimPopupContainerLayout(contentView.getContext()) { @Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { closeMenu(); } return super.dispatchKeyEvent(event); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { boolean b = super.dispatchTouchEvent(ev); if (ev.getAction() == MotionEvent.ACTION_DOWN && !b) { closeMenu(); } return b; } }; scrimPopupContainerLayout.addView(popupLayout, LayoutHelper.createLinearRelatively(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT, 0, 0, 0, 0)); scrimPopupContainerLayout.setPopupWindowLayout(popupLayout); scrimPopupWindow = new ActionBarPopupWindow(scrimPopupContainerLayout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT) { @Override public void dismiss() { super.dismiss(); if (scrimPopupWindow != this) { return; } Bulletin.hideVisible(); scrimPopupWindow = null; } }; scrimPopupWindow.setPauseNotifications(true); scrimPopupWindow.setDismissAnimationDuration(220); scrimPopupWindow.setOutsideTouchable(true); scrimPopupWindow.setClippingEnabled(true); scrimPopupWindow.setAnimationStyle(R.style.PopupContextAnimation); scrimPopupWindow.setFocusable(true); scrimPopupContainerLayout.measure(View.MeasureSpec.makeMeasureSpec(dp(1000), View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(dp(1000), View.MeasureSpec.AT_MOST)); scrimPopupWindow.setInputMethodMode(ActionBarPopupWindow.INPUT_METHOD_NOT_NEEDED); scrimPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING); scrimPopupWindow.getContentView().setFocusableInTouchMode(true); popupLayout.setFitItems(true); int popupX = v.getLeft() + (int) x - scrimPopupContainerLayout.getMeasuredWidth() + backgroundPaddings.left - dp(28); if (popupX < dp(6)) { popupX = dp(6); } else if (popupX > chatListView.getMeasuredWidth() - dp(6) - scrimPopupContainerLayout.getMeasuredWidth()) { popupX = chatListView.getMeasuredWidth() - dp(6) - scrimPopupContainerLayout.getMeasuredWidth(); } if (AndroidUtilities.isTablet()) { int[] location = new int[2]; fragmentView.getLocationInWindow(location); popupX += location[0]; } int totalHeight = contentView.getHeight(); int height = scrimPopupContainerLayout.getMeasuredHeight() + dp(48); int keyboardHeight = contentView.measureKeyboardHeight(); if (keyboardHeight > dp(20)) { totalHeight += keyboardHeight; } int popupY; if (height < totalHeight) { popupY = (int) (chatListView.getY() + v.getTop() + y); if (height - backgroundPaddings.top - backgroundPaddings.bottom > dp(240)) { popupY += dp(240) - height; } if (popupY < chatListView.getY() + dp(24)) { popupY = (int) (chatListView.getY() + dp(24)); } else if (popupY > totalHeight - height - dp(8)) { popupY = totalHeight - height - dp(8); } } else { popupY = inBubbleMode ? 0 : AndroidUtilities.statusBarHeight; } final int finalPopupX = scrimPopupX = popupX; final int finalPopupY = scrimPopupY = popupY; scrimPopupContainerLayout.setMaxHeight(totalHeight - popupY); scrimPopupWindow.showAtLocation(chatListView, Gravity.LEFT | Gravity.TOP, finalPopupX, finalPopupY); scrimPopupWindow.dimBehind(); }; if ( ChatObject.canBlockUsers(currentChat) && message.currentEvent != null && message.currentEvent.action instanceof TLRPC.TL_channelAdminLogEventActionDeleteMessage && message.messageOwner != null && message.messageOwner.from_id != null ) { TLRPC.User user = getMessagesController().getUser(selectedObject.messageOwner.from_id.user_id); if (user != null && !UserObject.isUserSelf(user)) { callbackSent = true; getMessagesController().getChannelParticipant(currentChat, user, participant -> AndroidUtilities.runOnUIThread(() -> { selectedParticipant = participant; if (participant != null) { if (ChatObject.canUserDoAction(currentChat, participant, ChatObject.ACTION_SEND) || ChatObject.canUserDoAction(currentChat, participant, ChatObject.ACTION_SEND_MEDIA)) { items.add(getString(R.string.Restrict)); icons.add(R.drawable.msg_block2); options.add(OPTION_RESTRICT); } items.add(getString(R.string.Ban)); icons.add(R.drawable.msg_block); options.add(OPTION_BAN); } proceed.run(); })); } } if (!callbackSent) { proceed.run(); } return true; } private CharSequence getMessageContent(MessageObject messageObject, int previousUid, boolean name) { SpannableStringBuilder str = new SpannableStringBuilder(); if (name) { long fromId = messageObject.getFromChatId(); if (previousUid != fromId) { if (fromId > 0) { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(fromId); if (user != null) { str.append(ContactsController.formatName(user.first_name, user.last_name)).append(":\n"); } } else if (fromId < 0) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-fromId); if (chat != null) { str.append(chat.title).append(":\n"); } } } } if (TextUtils.isEmpty(messageObject.messageText)) { str.append(messageObject.messageOwner.message); } else { str.append(messageObject.messageText); } return str; } private TextureView createTextureView(boolean add) { if (parentLayout == null) { return null; } if (roundVideoContainer == null) { if (Build.VERSION.SDK_INT >= 21) { roundVideoContainer = new FrameLayout(getParentActivity()) { @Override public void setTranslationY(float translationY) { super.setTranslationY(translationY); contentView.invalidate(); } }; roundVideoContainer.setOutlineProvider(new ViewOutlineProvider() { @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void getOutline(View view, Outline outline) { outline.setOval(0, 0, AndroidUtilities.roundMessageSize, AndroidUtilities.roundMessageSize); } }); roundVideoContainer.setClipToOutline(true); } else { roundVideoContainer = new FrameLayout(getParentActivity()) { @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); aspectPath.reset(); aspectPath.addCircle(w / 2, h / 2, w / 2, Path.Direction.CW); aspectPath.toggleInverseFillType(); } @Override public void setTranslationY(float translationY) { super.setTranslationY(translationY); contentView.invalidate(); } @Override public void setVisibility(int visibility) { super.setVisibility(visibility); if (visibility == VISIBLE) { setLayerType(View.LAYER_TYPE_HARDWARE, null); } } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); canvas.drawPath(aspectPath, aspectPaint); } }; aspectPath = new Path(); aspectPaint = new Paint(Paint.ANTI_ALIAS_FLAG); aspectPaint.setColor(0xff000000); aspectPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); } roundVideoContainer.setWillNotDraw(false); roundVideoContainer.setVisibility(View.INVISIBLE); aspectRatioFrameLayout = new AspectRatioFrameLayout(getParentActivity()); aspectRatioFrameLayout.setBackgroundColor(0); if (add) { roundVideoContainer.addView(aspectRatioFrameLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); } videoTextureView = new TextureView(getParentActivity()); videoTextureView.setOpaque(false); aspectRatioFrameLayout.addView(videoTextureView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); } if (roundVideoContainer.getParent() == null) { contentView.addView(roundVideoContainer, 1, new FrameLayout.LayoutParams(AndroidUtilities.roundMessageSize, AndroidUtilities.roundMessageSize)); } roundVideoContainer.setVisibility(View.INVISIBLE); aspectRatioFrameLayout.setDrawingReady(false); return videoTextureView; } private void destroyTextureView() { if (roundVideoContainer == null || roundVideoContainer.getParent() == null) { return; } contentView.removeView(roundVideoContainer); aspectRatioFrameLayout.setDrawingReady(false); roundVideoContainer.setVisibility(View.INVISIBLE); if (Build.VERSION.SDK_INT < 21) { roundVideoContainer.setLayerType(View.LAYER_TYPE_NONE, null); } } private void processSelectedOption(int option) { closeMenu(); if (selectedObject == null) { return; } switch (option) { case OPTION_COPY: { AndroidUtilities.addToClipboard(getMessageContent(selectedObject, 0, true)); BulletinFactory.of(ChannelAdminLogActivity.this).createCopyBulletin(getString("MessageCopied", R.string.MessageCopied)).show(); break; } case OPTION_SAVE_TO_GALLERY: { String path = selectedObject.messageOwner.attachPath; if (path != null && path.length() > 0) { File temp = new File(path); if (!temp.exists()) { path = null; } } if (path == null || path.length() == 0) { path = getFileLoader().getPathToMessage(selectedObject.messageOwner).toString(); } if (selectedObject.type == MessageObject.TYPE_VIDEO || selectedObject.type == MessageObject.TYPE_PHOTO) { if (Build.VERSION.SDK_INT >= 23 && (Build.VERSION.SDK_INT <= 28 || BuildVars.NO_SCOPED_STORAGE) && getParentActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { getParentActivity().requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 4); selectedObject = null; selectedParticipant = null; return; } MediaController.saveFile(path, getParentActivity(), selectedObject.type == MessageObject.TYPE_VIDEO ? 1 : 0, null, null); } break; } case OPTION_APPLY_FILE: { File locFile = null; if (selectedObject.messageOwner.attachPath != null && selectedObject.messageOwner.attachPath.length() != 0) { File f = new File(selectedObject.messageOwner.attachPath); if (f.exists()) { locFile = f; } } if (locFile == null) { File f = getFileLoader().getPathToMessage(selectedObject.messageOwner); if (f.exists()) { locFile = f; } } if (locFile != null) { if (locFile.getName().toLowerCase().endsWith("attheme")) { if (chatLayoutManager != null) { int lastPosition = chatLayoutManager.findLastVisibleItemPosition(); if (lastPosition < chatLayoutManager.getItemCount() - 1) { scrollToPositionOnRecreate = chatLayoutManager.findFirstVisibleItemPosition(); RecyclerListView.Holder holder = (RecyclerListView.Holder) chatListView.findViewHolderForAdapterPosition(scrollToPositionOnRecreate); if (holder != null) { scrollToOffsetOnRecreate = holder.itemView.getTop(); } else { scrollToPositionOnRecreate = -1; } } else { scrollToPositionOnRecreate = -1; } } Theme.ThemeInfo themeInfo = Theme.applyThemeFile(locFile, selectedObject.getDocumentName(), null, true); if (themeInfo != null) { presentFragment(new ThemePreviewActivity(themeInfo)); } else { scrollToPositionOnRecreate = -1; if (getParentActivity() == null) { selectedObject = null; selectedParticipant = null; return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(getString("AppName", R.string.AppName)); builder.setMessage(getString("IncorrectTheme", R.string.IncorrectTheme)); builder.setPositiveButton(getString("OK", R.string.OK), null); showDialog(builder.create()); } } else { if (LocaleController.getInstance().applyLanguageFile(locFile, currentAccount)) { presentFragment(new LanguageSelectActivity()); } else { if (getParentActivity() == null) { selectedObject = null; selectedParticipant = null; return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(getString("AppName", R.string.AppName)); builder.setMessage(getString("IncorrectLocalization", R.string.IncorrectLocalization)); builder.setPositiveButton(getString("OK", R.string.OK), null); showDialog(builder.create()); } } } break; } case OPTION_SHARE: { String path = selectedObject.messageOwner.attachPath; if (path != null && path.length() > 0) { File temp = new File(path); if (!temp.exists()) { path = null; } } if (path == null || path.length() == 0) { path = getFileLoader().getPathToMessage(selectedObject.messageOwner).toString(); } Intent intent = new Intent(Intent.ACTION_SEND); intent.setType(selectedObject.getDocument().mime_type); if (Build.VERSION.SDK_INT >= 24) { try { intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(getParentActivity(), ApplicationLoader.getApplicationId() + ".provider", new File(path))); intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } catch (Exception ignore) { intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(path))); } } else { intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(path))); } try { getParentActivity().startActivityForResult(Intent.createChooser(intent, getString("ShareFile", R.string.ShareFile)), 500); } catch (Exception e) { } break; } case OPTION_SAVE_TO_GALLERY2: { String path = selectedObject.messageOwner.attachPath; if (path != null && path.length() > 0) { File temp = new File(path); if (!temp.exists()) { path = null; } } if (path == null || path.length() == 0) { path = getFileLoader().getPathToMessage(selectedObject.messageOwner).toString(); } if (Build.VERSION.SDK_INT >= 23 && (Build.VERSION.SDK_INT <= 28 || BuildVars.NO_SCOPED_STORAGE) && getParentActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { getParentActivity().requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 4); selectedObject = null; selectedParticipant = null; return; } MediaController.saveFile(path, getParentActivity(), 0, null, null); break; } case OPTION_SAVE_STICKER: { showDialog(new StickersAlert(getParentActivity(), this, selectedObject.getInputStickerSet(), null, null)); break; } case OPTION_SAVE_TO_DOWNLOADS_OR_MUSIC: { if (Build.VERSION.SDK_INT >= 23 && (Build.VERSION.SDK_INT <= 28 || BuildVars.NO_SCOPED_STORAGE) && getParentActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { getParentActivity().requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 4); selectedObject = null; selectedParticipant = null; return; } String fileName = FileLoader.getDocumentFileName(selectedObject.getDocument()); if (TextUtils.isEmpty(fileName)) { fileName = selectedObject.getFileName(); } String path = selectedObject.messageOwner.attachPath; if (path != null && path.length() > 0) { File temp = new File(path); if (!temp.exists()) { path = null; } } if (path == null || path.length() == 0) { path = getFileLoader().getPathToMessage(selectedObject.messageOwner).toString(); } MediaController.saveFile(path, getParentActivity(), selectedObject.isMusic() ? 3 : 2, fileName, selectedObject.getDocument() != null ? selectedObject.getDocument().mime_type : ""); break; } case OPTION_SAVE_TO_GIFS: { TLRPC.Document document = selectedObject.getDocument(); MessagesController.getInstance(currentAccount).saveGif(selectedObject, document); break; } case OPTION_ADD_CONTACT: { Bundle args = new Bundle(); args.putLong("user_id", selectedObject.messageOwner.media.user_id); args.putString("phone", selectedObject.messageOwner.media.phone_number); args.putBoolean("addContact", true); presentFragment(new ContactAddActivity(args)); break; } case OPTION_COPY_PHONE: { AndroidUtilities.addToClipboard(selectedObject.messageOwner.media.phone_number); BulletinFactory.of(ChannelAdminLogActivity.this).createCopyBulletin(getString("PhoneCopied", R.string.PhoneCopied)).show(); break; } case OPTION_CALL: { try { Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + selectedObject.messageOwner.media.phone_number)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getParentActivity().startActivityForResult(intent, 500); } catch (Exception e) { FileLog.e(e); } break; } case OPTION_REPORT_FALSE_POSITIVE: { TLRPC.TL_channels_reportAntiSpamFalsePositive req = new TLRPC.TL_channels_reportAntiSpamFalsePositive(); req.channel = getMessagesController().getInputChannel(currentChat.id); req.msg_id = selectedObject.getRealId(); getConnectionsManager().sendRequest(req, (res, err) -> { AndroidUtilities.runOnUIThread(() -> { if (res instanceof TLRPC.TL_boolTrue) { BulletinFactory.of(this).createSimpleBulletin(R.raw.msg_antispam, getString("ChannelAntiSpamFalsePositiveReported", R.string.ChannelAntiSpamFalsePositiveReported)).show(); } else if (res instanceof TLRPC.TL_boolFalse) { BulletinFactory.of(this).createSimpleBulletin(R.raw.error, getString("UnknownError", R.string.UnknownError)).show(); } else { BulletinFactory.of(this).createSimpleBulletin(R.raw.error, getString("UnknownError", R.string.UnknownError)).show(); } }); }); break; } case OPTION_RESTRICT: { if (selectedParticipant != null) { TLRPC.User user = getMessagesController().getUser(DialogObject.getPeerDialogId(selectedParticipant.peer)); if (selectedParticipant.banned_rights == null) { selectedParticipant.banned_rights = new TLRPC.TL_chatBannedRights(); } selectedParticipant.banned_rights.send_plain = true; selectedParticipant.banned_rights.send_messages = true; selectedParticipant.banned_rights.send_media = true; selectedParticipant.banned_rights.send_stickers = true; selectedParticipant.banned_rights.send_gifs = true; selectedParticipant.banned_rights.send_games = true; selectedParticipant.banned_rights.send_inline = true; selectedParticipant.banned_rights.send_polls = true; selectedParticipant.banned_rights.send_photos = true; selectedParticipant.banned_rights.send_videos = true; selectedParticipant.banned_rights.send_roundvideos = true; selectedParticipant.banned_rights.send_audios = true; selectedParticipant.banned_rights.send_voices = true; selectedParticipant.banned_rights.send_docs = true; getMessagesController().setParticipantBannedRole(currentChat.id, user, null, selectedParticipant.banned_rights, true, getFragmentForAlert(1), () -> { BulletinFactory.of(this).createSimpleBulletin(R.raw.ic_ban, AndroidUtilities.replaceTags(LocaleController.formatString(R.string.RestrictedParticipantSending, UserObject.getFirstName(user)))).show(false); reloadLastMessages(); }); } break; } case OPTION_BAN: { getMessagesController().deleteParticipantFromChat(currentChat.id, getMessagesController().getInputPeer(selectedObject.messageOwner.from_id), false, false, () -> { reloadLastMessages(); }); if (currentChat != null && selectedObject.messageOwner.from_id instanceof TLRPC.TL_peerUser && BulletinFactory.canShowBulletin(this)) { TLRPC.User user = getMessagesController().getUser(selectedObject.messageOwner.from_id.user_id); if (user != null) { BulletinFactory.createRemoveFromChatBulletin(this, user, currentChat.title).show(); } } break; } } selectedObject = null; selectedParticipant = null; } private int getMessageType(MessageObject messageObject) { if (messageObject == null) { return -1; } if (messageObject.type == 6) { return -1; } else if (messageObject.type == 10 || messageObject.type == MessageObject.TYPE_ACTION_PHOTO || messageObject.type == MessageObject.TYPE_PHONE_CALL) { if (messageObject.getId() == 0) { return -1; } return 1; } else { if (messageObject.isVoice()) { return 2; } else if (messageObject.isSticker() || messageObject.isAnimatedSticker()) { TLRPC.InputStickerSet inputStickerSet = messageObject.getInputStickerSet(); if (inputStickerSet instanceof TLRPC.TL_inputStickerSetID) { if (!MediaDataController.getInstance(currentAccount).isStickerPackInstalled(inputStickerSet.id)) { return 7; } } else if (inputStickerSet instanceof TLRPC.TL_inputStickerSetShortName) { if (!MediaDataController.getInstance(currentAccount).isStickerPackInstalled(inputStickerSet.short_name)) { return 7; } } } else if ((!messageObject.isRoundVideo() || messageObject.isRoundVideo() && BuildVars.DEBUG_VERSION) && (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto || messageObject.getDocument() != null || messageObject.isMusic() || messageObject.isVideo())) { boolean canSave = false; if (messageObject.messageOwner.attachPath != null && messageObject.messageOwner.attachPath.length() != 0) { File f = new File(messageObject.messageOwner.attachPath); if (f.exists()) { canSave = true; } } if (!canSave) { File f = getFileLoader().getPathToMessage(messageObject.messageOwner); if (f.exists()) { canSave = true; } } if (canSave) { if (messageObject.getDocument() != null) { String mime = messageObject.getDocument().mime_type; if (mime != null) { if (messageObject.getDocumentName().toLowerCase().endsWith("attheme")) { return 10; } else if (mime.endsWith("/xml")) { return 5; } else if (mime.endsWith("/png") || mime.endsWith("/jpg") || mime.endsWith("/jpeg")) { return 6; } } } return 4; } } else if (messageObject.type == MessageObject.TYPE_CONTACT) { return 8; } else if (messageObject.isMediaEmpty()) { return 3; } return 2; } } private void loadAdmins() { TLRPC.TL_channels_getParticipants req = new TLRPC.TL_channels_getParticipants(); req.channel = MessagesController.getInputChannel(currentChat); req.filter = new TLRPC.TL_channelParticipantsAdmins(); req.offset = 0; req.limit = 200; int reqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { if (error == null) { TLRPC.TL_channels_channelParticipants res = (TLRPC.TL_channels_channelParticipants) response; getMessagesController().putUsers(res.users, false); getMessagesController().putChats(res.chats, false); admins = res.participants; if (currentChat != null) { TLRPC.ChatFull chatFull = getMessagesController().getChatFull(currentChat.id); if (chatFull != null && chatFull.antispam) { TLRPC.ChannelParticipant antispamParticipant = new TLRPC.ChannelParticipant() {}; antispamParticipant.user_id = getMessagesController().telegramAntispamUserId; antispamParticipant.peer = getMessagesController().getPeer(antispamParticipant.user_id); loadAntispamUser(getMessagesController().telegramAntispamUserId); admins.add(0, antispamParticipant); } } if (visibleDialog instanceof AdminLogFilterAlert2) { ((AdminLogFilterAlert2) visibleDialog).setCurrentAdmins(admins); } } })); ConnectionsManager.getInstance(currentAccount).bindRequestToGuid(reqId, classGuid); } private void loadAntispamUser(long userId) { if (getMessagesController().getUser(userId) != null) { return; } TLRPC.TL_users_getUsers req = new TLRPC.TL_users_getUsers(); TLRPC.TL_inputUser inputUser = new TLRPC.TL_inputUser(); inputUser.user_id = userId; req.id.add(inputUser); ConnectionsManager.getInstance(currentAccount).sendRequest(req, (res, err) -> { if (res instanceof TLRPC.Vector) { ArrayList<Object> objects = ((TLRPC.Vector) res).objects; ArrayList<TLRPC.User> users = new ArrayList<>(); for (int i = 0; i < objects.size(); ++i) { if (objects.get(i) instanceof TLRPC.User) { users.add((TLRPC.User) objects.get(i)); } } getMessagesController().putUsers(users, false); } }); } @Override public void onRemoveFromParent() { MediaController.getInstance().setTextureView(videoTextureView, null, null, false); } private void hideFloatingDateView(boolean animated) { if (floatingDateView.getTag() != null && !currentFloatingDateOnScreen && (!scrollingFloatingDate || currentFloatingTopIsNotMessage)) { floatingDateView.setTag(null); if (animated) { floatingDateAnimation = new AnimatorSet(); floatingDateAnimation.setDuration(150); floatingDateAnimation.playTogether(ObjectAnimator.ofFloat(floatingDateView, "alpha", 0.0f)); floatingDateAnimation.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (animation.equals(floatingDateAnimation)) { floatingDateAnimation = null; } } }); floatingDateAnimation.setStartDelay(500); floatingDateAnimation.start(); } else { if (floatingDateAnimation != null) { floatingDateAnimation.cancel(); floatingDateAnimation = null; } floatingDateView.setAlpha(0.0f); } } } private void checkScrollForLoad(boolean scroll) { if (chatLayoutManager == null || paused) { return; } int firstVisibleItem = chatLayoutManager.findFirstVisibleItemPosition(); int visibleItemCount = firstVisibleItem == RecyclerView.NO_POSITION ? 0 : Math.abs(chatLayoutManager.findLastVisibleItemPosition() - firstVisibleItem) + 1; if (visibleItemCount > 0) { int totalItemCount = chatAdapter.getItemCount(); int checkLoadCount; if (scroll) { checkLoadCount = 4; } else { checkLoadCount = 1; } if (firstVisibleItem <= checkLoadCount && !loading && !endReached) { loadMessages(false); } } } private void moveScrollToLastMessage() { if (chatListView != null && !messages.isEmpty()) { chatLayoutManager.scrollToPositionWithOffset(filteredMessages.size() - 1, -100000 - chatListView.getPaddingTop()); } } private void updateTextureViewPosition() { boolean foundTextureViewMessage = false; int count = chatListView.getChildCount(); for (int a = 0; a < count; a++) { View view = chatListView.getChildAt(a); if (view instanceof ChatMessageCell) { ChatMessageCell messageCell = (ChatMessageCell) view; MessageObject messageObject = messageCell.getMessageObject(); if (roundVideoContainer != null && messageObject.isRoundVideo() && MediaController.getInstance().isPlayingMessage(messageObject)) { ImageReceiver imageReceiver = messageCell.getPhotoImage(); roundVideoContainer.setTranslationX(imageReceiver.getImageX()); roundVideoContainer.setTranslationY(fragmentView.getPaddingTop() + messageCell.getTop() + imageReceiver.getImageY()); fragmentView.invalidate(); roundVideoContainer.invalidate(); foundTextureViewMessage = true; break; } } } if (roundVideoContainer != null) { MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject(); if (!foundTextureViewMessage) { roundVideoContainer.setTranslationY(-AndroidUtilities.roundMessageSize - 100); fragmentView.invalidate(); if (messageObject != null && messageObject.isRoundVideo()) { if (checkTextureViewPosition || PipRoundVideoView.getInstance() != null) { MediaController.getInstance().setCurrentVideoVisible(false); } } } else { MediaController.getInstance().setCurrentVideoVisible(true); } } } private void updateMessagesVisiblePart() { if (chatListView == null) { return; } int count = chatListView.getChildCount(); int height = chatListView.getMeasuredHeight(); int minPositionHolder = Integer.MAX_VALUE; int minPositionDateHolder = Integer.MAX_VALUE; View minDateChild = null; View minChild = null; View minMessageChild = null; boolean foundTextureViewMessage = false; for (int a = 0; a < count; a++) { View view = chatListView.getChildAt(a); if (view instanceof ChatMessageCell) { ChatMessageCell messageCell = (ChatMessageCell) view; int top = messageCell.getTop(); int bottom = messageCell.getBottom(); int viewTop = top >= 0 ? 0 : -top; int viewBottom = messageCell.getMeasuredHeight(); if (viewBottom > height) { viewBottom = viewTop + height; } messageCell.setVisiblePart(viewTop, viewBottom - viewTop, contentView.getHeightWithKeyboard() - dp(48) - chatListView.getTop(), 0, view.getY() + actionBar.getMeasuredHeight() - contentView.getBackgroundTranslationY(), contentView.getMeasuredWidth(), contentView.getBackgroundSizeY(), 0, 0); MessageObject messageObject = messageCell.getMessageObject(); if (roundVideoContainer != null && messageObject.isRoundVideo() && MediaController.getInstance().isPlayingMessage(messageObject)) { ImageReceiver imageReceiver = messageCell.getPhotoImage(); roundVideoContainer.setTranslationX(imageReceiver.getImageX()); roundVideoContainer.setTranslationY(fragmentView.getPaddingTop() + top + imageReceiver.getImageY()); fragmentView.invalidate(); roundVideoContainer.invalidate(); foundTextureViewMessage = true; } } else if (view instanceof ChatActionCell) { ChatActionCell cell = (ChatActionCell) view; cell.setVisiblePart(view.getY() + actionBar.getMeasuredHeight() - contentView.getBackgroundTranslationY(), contentView.getBackgroundSizeY()); if (cell.hasGradientService()) { cell.invalidate(); } } if (view.getBottom() <= chatListView.getPaddingTop()) { continue; } int position = view.getBottom(); if (position < minPositionHolder) { minPositionHolder = position; if (view instanceof ChatMessageCell || view instanceof ChatActionCell) { minMessageChild = view; } minChild = view; } if (chatListItemAnimator == null || (!chatListItemAnimator.willRemoved(view) && !chatListItemAnimator.willAddedFromAlpha(view))) { if (view instanceof ChatActionCell && ((ChatActionCell) view).getMessageObject().isDateObject) { if (view.getAlpha() != 1.0f) { view.setAlpha(1.0f); } if (position < minPositionDateHolder) { minPositionDateHolder = position; minDateChild = view; } } } } if (roundVideoContainer != null) { if (!foundTextureViewMessage) { roundVideoContainer.setTranslationY(-AndroidUtilities.roundMessageSize - 100); fragmentView.invalidate(); MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject(); if (messageObject != null && messageObject.isRoundVideo() && checkTextureViewPosition) { MediaController.getInstance().setCurrentVideoVisible(false); } } else { MediaController.getInstance().setCurrentVideoVisible(true); } } if (minMessageChild != null) { MessageObject messageObject; if (minMessageChild instanceof ChatMessageCell) { messageObject = ((ChatMessageCell) minMessageChild).getMessageObject(); } else { messageObject = ((ChatActionCell) minMessageChild).getMessageObject(); } floatingDateView.setCustomDate(messageObject.messageOwner.date, false, true); } currentFloatingDateOnScreen = false; currentFloatingTopIsNotMessage = !(minChild instanceof ChatMessageCell || minChild instanceof ChatActionCell); if (minDateChild != null) { if (minDateChild.getTop() > chatListView.getPaddingTop() || currentFloatingTopIsNotMessage) { if (minDateChild.getAlpha() != 1.0f) { minDateChild.setAlpha(1.0f); } hideFloatingDateView(!currentFloatingTopIsNotMessage); } else { if (minDateChild.getAlpha() != 0.0f) { minDateChild.setAlpha(0.0f); } if (floatingDateAnimation != null) { floatingDateAnimation.cancel(); floatingDateAnimation = null; } if (floatingDateView.getTag() == null) { floatingDateView.setTag(1); } if (floatingDateView.getAlpha() != 1.0f) { floatingDateView.setAlpha(1.0f); } currentFloatingDateOnScreen = true; } int offset = minDateChild.getBottom() - chatListView.getPaddingTop(); if (offset > floatingDateView.getMeasuredHeight() && offset < floatingDateView.getMeasuredHeight() * 2) { floatingDateView.setTranslationY(-floatingDateView.getMeasuredHeight() * 2 + offset); } else { floatingDateView.setTranslationY(0); } } else { hideFloatingDateView(true); floatingDateView.setTranslationY(0); } } @Override public void onTransitionAnimationStart(boolean isOpen, boolean backward) { if (isOpen) { notificationsLocker.lock(); openAnimationEnded = false; } } @Override public void onTransitionAnimationEnd(boolean isOpen, boolean backward) { if (isOpen) { notificationsLocker.unlock(); openAnimationEnded = true; } } @Override public void onResume() { super.onResume(); activityResumeTime = System.currentTimeMillis(); if (contentView != null) { contentView.onResume(); } paused = false; checkScrollForLoad(false); if (wasPaused) { wasPaused = false; if (chatAdapter != null) { chatAdapter.notifyDataSetChanged(); } } } @Override public void onPause() { super.onPause(); if (contentView != null) { contentView.onPause(); } if (undoView != null) { undoView.hide(true, 0); } paused = true; wasPaused = true; if (AvatarPreviewer.hasVisibleInstance()) { AvatarPreviewer.getInstance().close(); } } @Override public void onBecomeFullyHidden() { if (undoView != null) { undoView.hide(true, 0); } } public void openVCard(TLRPC.User user, String vcard, String first_name, String last_name) { try { File f = AndroidUtilities.getSharingDirectory(); f.mkdirs(); f = new File(f, "vcard.vcf"); BufferedWriter writer = new BufferedWriter(new FileWriter(f)); writer.write(vcard); writer.close(); showDialog(new PhonebookShareAlert(this, null, user, null, f, first_name, last_name)); } catch (Exception e) { FileLog.e(e); } } @Override public void onConfigurationChanged(android.content.res.Configuration newConfig) { if (visibleDialog instanceof DatePickerDialog) { visibleDialog.dismiss(); } } private void alertUserOpenError(MessageObject message) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(getString("AppName", R.string.AppName)); builder.setPositiveButton(getString("OK", R.string.OK), null); if (message.type == MessageObject.TYPE_VIDEO) { builder.setMessage(getString("NoPlayerInstalled", R.string.NoPlayerInstalled)); } else { builder.setMessage(LocaleController.formatString("NoHandleAppInstalled", R.string.NoHandleAppInstalled, message.getDocument().mime_type)); } showDialog(builder.create()); } public TLRPC.Chat getCurrentChat() { return currentChat; } private void addCanBanUser(Bundle bundle, long uid) { if (!currentChat.megagroup || admins == null || !ChatObject.canBlockUsers(currentChat)) { return; } for (int a = 0; a < admins.size(); a++) { TLRPC.ChannelParticipant channelParticipant = admins.get(a); if (MessageObject.getPeerId(channelParticipant.peer) == uid) { if (!channelParticipant.can_edit) { return; } break; } } bundle.putLong("ban_chat_id", currentChat.id); } public void showOpenUrlAlert(final String url, boolean ask) { if (Browser.isInternalUrl(url, null) || !ask) { Browser.openUrl(getParentActivity(), url, true); } else { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(getString("OpenUrlTitle", R.string.OpenUrlTitle)); builder.setMessage(LocaleController.formatString("OpenUrlAlert2", R.string.OpenUrlAlert2, url)); builder.setPositiveButton(getString("Open", R.string.Open), (dialogInterface, i) -> Browser.openUrl(getParentActivity(), url, true)); builder.setNegativeButton(getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); } } // private void removeMessageObject(MessageObject messageObject) { // int index = messages.indexOf(messageObject); // if (index == -1) { // return; // } // messages.remove(index); // if (chatAdapter != null) { // chatAdapter.notifyItemRemoved(chatAdapter.messagesStartRow + messages.size() - index - 1); // } // } public class ChatActivityAdapter extends RecyclerView.Adapter { private Context mContext; private int rowCount; private int loadingUpRow; private int messagesStartRow; private int messagesEndRow; public ChatActivityAdapter(Context context) { mContext = context; setHasStableIds(true); } private final ArrayList<Long> oldStableIds = new ArrayList<>(); private final ArrayList<Long> stableIds = new ArrayList<>(); public void updateRows() { updateRows(true); } public void updateRows(boolean animated) { rowCount = 0; if (!filteredMessages.isEmpty()) { if (!endReached) { loadingUpRow = rowCount++; } else { loadingUpRow = -1; } messagesStartRow = rowCount; rowCount += filteredMessages.size(); messagesEndRow = rowCount; } else { loadingUpRow = -1; messagesStartRow = -1; messagesEndRow = -1; } } @Override public int getItemCount() { return rowCount; } @Override public long getItemId(int position) { if (position >= messagesStartRow && position < messagesEndRow) { return filteredMessages.get(filteredMessages.size() - (position - messagesStartRow) - 1).stableId; } else if (position == loadingUpRow) { return 2; } return 5; } public MessageObject getMessageObject(int position) { if (position >= messagesStartRow && position < messagesEndRow) { return filteredMessages.get(filteredMessages.size() - (position - messagesStartRow) - 1); } return null; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view; if (viewType == 0) { if (!chatMessageCellsCache.isEmpty()) { view = chatMessageCellsCache.get(0); chatMessageCellsCache.remove(0); } else { view = new ChatMessageCell(mContext); } ChatMessageCell chatMessageCell = (ChatMessageCell) view; chatMessageCell.setDelegate(new ChatMessageCell.ChatMessageCellDelegate() { @Override public boolean shouldShowTopicButton() { return ChatObject.isForum(currentChat); } @Override public void didPressTopicButton(ChatMessageCell cell) { MessageObject message = cell.getMessageObject(); if (message != null) { Bundle args = new Bundle(); args.putLong("chat_id", -message.getDialogId()); ChatActivity chatActivity = new ChatActivity(args); ForumUtilities.applyTopic(chatActivity, MessagesStorage.TopicKey.of(message.getDialogId(), MessageObject.getTopicId(currentAccount, message.messageOwner, true))); presentFragment(chatActivity); } } @Override public boolean canDrawOutboundsContent() { return true; } @Override public void didPressSideButton(ChatMessageCell cell) { if (getParentActivity() == null) { return; } showDialog(ShareAlert.createShareAlert(mContext, cell.getMessageObject(), null, ChatObject.isChannel(currentChat) && !currentChat.megagroup, null, false)); } @Override public boolean needPlayMessage(ChatMessageCell cell, MessageObject messageObject, boolean muted) { if (messageObject.isVoice() || messageObject.isRoundVideo()) { boolean result = MediaController.getInstance().playMessage(messageObject, muted); MediaController.getInstance().setVoiceMessagesPlaylist(null, false); return result; } else if (messageObject.isMusic()) { return MediaController.getInstance().setPlaylist(filteredMessages, messageObject, 0); } return false; } @Override public void didPressChannelAvatar(ChatMessageCell cell, TLRPC.Chat chat, int postId, float touchX, float touchY) { if (chat != null && chat != currentChat) { Bundle args = new Bundle(); args.putLong("chat_id", chat.id); if (postId != 0) { args.putInt("message_id", postId); } if (MessagesController.getInstance(currentAccount).checkCanOpenChat(args, ChannelAdminLogActivity.this)) { presentFragment(new ChatActivity(args), true); } } } @Override public void didPressOther(ChatMessageCell cell, float x, float y) { createMenu(cell); } @Override public void didPressUserAvatar(ChatMessageCell cell, TLRPC.User user, float touchX, float touchY) { if (user != null && user.id != UserConfig.getInstance(currentAccount).getClientUserId()) { openProfile(user); } } @Override public boolean didLongPressUserAvatar(ChatMessageCell cell, TLRPC.User user, float touchX, float touchY) { if (user != null && user.id != UserConfig.getInstance(currentAccount).getClientUserId()) { final AvatarPreviewer.MenuItem[] menuItems = {AvatarPreviewer.MenuItem.OPEN_PROFILE, AvatarPreviewer.MenuItem.SEND_MESSAGE}; final TLRPC.UserFull userFull = getMessagesController().getUserFull(user.id); final AvatarPreviewer.Data data; if (userFull != null) { data = AvatarPreviewer.Data.of(userFull, menuItems); } else { data = AvatarPreviewer.Data.of(user, classGuid, menuItems); } if (AvatarPreviewer.canPreview(data)) { AvatarPreviewer.getInstance().show((ViewGroup) fragmentView, data, item -> { switch (item) { case SEND_MESSAGE: openDialog(cell, user); break; case OPEN_PROFILE: openProfile(user); break; } }); return true; } } return false; } private void openProfile(TLRPC.User user) { Bundle args = new Bundle(); args.putLong("user_id", user.id); addCanBanUser(args, user.id); ProfileActivity fragment = new ProfileActivity(args); fragment.setPlayProfileAnimation(0); presentFragment(fragment); } private void openDialog(ChatMessageCell cell, TLRPC.User user) { if (user != null) { Bundle args = new Bundle(); args.putLong("user_id", user.id); if (getMessagesController().checkCanOpenChat(args, ChannelAdminLogActivity.this)) { presentFragment(new ChatActivity(args)); } } } @Override public void didPressCancelSendButton(ChatMessageCell cell) { } @Override public void didLongPress(ChatMessageCell cell, float x, float y) { createMenu(cell); } @Override public boolean canPerformActions() { return true; } @Override public void didPressUrl(ChatMessageCell cell, final CharacterStyle url, boolean longPress) { if (url == null) { return; } MessageObject messageObject = cell.getMessageObject(); if (url instanceof URLSpanMono) { ((URLSpanMono) url).copyToClipboard(); if (AndroidUtilities.shouldShowClipboardToast()) { Toast.makeText(getParentActivity(), getString("TextCopied", R.string.TextCopied), Toast.LENGTH_SHORT).show(); } } else if (url instanceof URLSpanUserMention) { long peerId = Utilities.parseLong(((URLSpanUserMention) url).getURL()); if (peerId > 0) { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(peerId); if (user != null) { MessagesController.openChatOrProfileWith(user, null, ChannelAdminLogActivity.this, 0, false); } } else { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-peerId); if (chat != null) { MessagesController.openChatOrProfileWith(null, chat, ChannelAdminLogActivity.this, 0, false); } } } else if (url instanceof URLSpanNoUnderline) { String str = ((URLSpanNoUnderline) url).getURL(); if (str.startsWith("@")) { MessagesController.getInstance(currentAccount).openByUserName(str.substring(1), ChannelAdminLogActivity.this, 0); } else if (str.startsWith("#")) { DialogsActivity fragment = new DialogsActivity(null); fragment.setSearchString(str); presentFragment(fragment); } } else { final String urlFinal = ((URLSpan) url).getURL(); if (longPress) { BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity()); builder.setTitle(urlFinal); builder.setItems(new CharSequence[]{getString("Open", R.string.Open), getString("Copy", R.string.Copy)}, (dialog, which) -> { if (which == 0) { Browser.openUrl(getParentActivity(), urlFinal, true); } else if (which == 1) { String url1 = urlFinal; if (url1.startsWith("mailto:")) { url1 = url1.substring(7); } else if (url1.startsWith("tel:")) { url1 = url1.substring(4); } AndroidUtilities.addToClipboard(url1); } }); showDialog(builder.create()); } else { if (url instanceof URLSpanReplacement) { showOpenUrlAlert(((URLSpanReplacement) url).getURL(), true); } else { if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage && messageObject.messageOwner.media.webpage != null && messageObject.messageOwner.media.webpage.cached_page != null) { String lowerUrl = urlFinal.toLowerCase(); String lowerUrl2 = messageObject.messageOwner.media.webpage.url.toLowerCase(); if ((Browser.isTelegraphUrl(lowerUrl, false) || lowerUrl.contains("t.me/iv")) && (lowerUrl.contains(lowerUrl2) || lowerUrl2.contains(lowerUrl))) { ArticleViewer.getInstance().setParentActivity(getParentActivity(), ChannelAdminLogActivity.this); ArticleViewer.getInstance().open(messageObject); return; } } Browser.openUrl(getParentActivity(), urlFinal, true); } } } } @Override public void needOpenWebView(MessageObject message, String url, String title, String description, String originalUrl, int w, int h) { EmbedBottomSheet.show(ChannelAdminLogActivity.this, message, provider, title, description, originalUrl, url, w, h, false); } @Override public void didPressReplyMessage(ChatMessageCell cell, int id) { MessageObject messageObject = cell.getMessageObject(); MessageObject reply = messageObject.replyMessageObject; if (reply.getDialogId() == -currentChat.id) { for (int i = 0; i < filteredMessages.size(); ++i) { MessageObject msg = filteredMessages.get(i); if (msg != null && msg.contentType != 1 && msg.getRealId() == reply.getRealId()) { scrollToMessage(msg, true); return; } } } Bundle args = new Bundle(); args.putLong("chat_id", currentChat.id); args.putInt("message_id", reply.getRealId()); presentFragment(new ChatActivity(args)); } @Override public void didPressViaBot(ChatMessageCell cell, String username) { } @Override public void didPressImage(ChatMessageCell cell, float x, float y) { MessageObject message = cell.getMessageObject(); if (message.getInputStickerSet() != null) { showDialog(new StickersAlert(getParentActivity(), ChannelAdminLogActivity.this, message.getInputStickerSet(), null, null)); } else if (message.isVideo() || message.type == MessageObject.TYPE_PHOTO || message.type == MessageObject.TYPE_TEXT && !message.isWebpageDocument() || message.isGif()) { PhotoViewer.getInstance().setParentActivity(ChannelAdminLogActivity.this); PhotoViewer.getInstance().openPhoto(message, null, 0, 0, 0, provider); } else if (message.type == MessageObject.TYPE_VIDEO) { try { File f = null; if (message.messageOwner.attachPath != null && message.messageOwner.attachPath.length() != 0) { f = new File(message.messageOwner.attachPath); } if (f == null || !f.exists()) { f = getFileLoader().getPathToMessage(message.messageOwner); } Intent intent = new Intent(Intent.ACTION_VIEW); if (Build.VERSION.SDK_INT >= 24) { intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setDataAndType(FileProvider.getUriForFile(getParentActivity(), ApplicationLoader.getApplicationId() + ".provider", f), "video/mp4"); } else { intent.setDataAndType(Uri.fromFile(f), "video/mp4"); } getParentActivity().startActivityForResult(intent, 500); } catch (Exception e) { alertUserOpenError(message); } } else if (message.type == MessageObject.TYPE_GEO) { if (!AndroidUtilities.isMapsInstalled(ChannelAdminLogActivity.this)) { return; } LocationActivity fragment = new LocationActivity(0); fragment.setMessageObject(message); presentFragment(fragment); } else if (message.type == MessageObject.TYPE_FILE || message.type == MessageObject.TYPE_TEXT) { if (message.getDocumentName().toLowerCase().endsWith("attheme")) { File locFile = null; if (message.messageOwner.attachPath != null && message.messageOwner.attachPath.length() != 0) { File f = new File(message.messageOwner.attachPath); if (f.exists()) { locFile = f; } } if (locFile == null) { File f = getFileLoader().getPathToMessage(message.messageOwner); if (f.exists()) { locFile = f; } } if (chatLayoutManager != null) { int lastPosition = chatLayoutManager.findLastVisibleItemPosition(); if (lastPosition < chatLayoutManager.getItemCount() - 1) { scrollToPositionOnRecreate = chatLayoutManager.findFirstVisibleItemPosition(); RecyclerListView.Holder holder = (RecyclerListView.Holder) chatListView.findViewHolderForAdapterPosition(scrollToPositionOnRecreate); if (holder != null) { scrollToOffsetOnRecreate = holder.itemView.getTop(); } else { scrollToPositionOnRecreate = -1; } } else { scrollToPositionOnRecreate = -1; } } Theme.ThemeInfo themeInfo = Theme.applyThemeFile(locFile, message.getDocumentName(), null, true); if (themeInfo != null) { presentFragment(new ThemePreviewActivity(themeInfo)); return; } else { scrollToPositionOnRecreate = -1; } } try { AndroidUtilities.openForView(message, getParentActivity(), null); } catch (Exception e) { alertUserOpenError(message); } } } @Override public void didPressInstantButton(ChatMessageCell cell, int type) { MessageObject messageObject = cell.getMessageObject(); if (type == 0) { if (messageObject.messageOwner.media != null && messageObject.messageOwner.media.webpage != null && messageObject.messageOwner.media.webpage.cached_page != null) { ArticleViewer.getInstance().setParentActivity(getParentActivity(), ChannelAdminLogActivity.this); ArticleViewer.getInstance().open(messageObject); } } else if (type == 5) { openVCard(getMessagesController().getUser(messageObject.messageOwner.media.user_id), messageObject.messageOwner.media.vcard, messageObject.messageOwner.media.first_name, messageObject.messageOwner.media.last_name); } else { if (messageObject.messageOwner.media != null && messageObject.messageOwner.media.webpage != null) { Browser.openUrl(getParentActivity(), messageObject.messageOwner.media.webpage.url); } } } @Override public void didPressBotButton(ChatMessageCell cell, TLRPC.KeyboardButton button) { MessageObject messageObject = cell.getMessageObject(); if (expandedEvents.contains(messageObject.eventId)) { expandedEvents.remove(messageObject.eventId); } else { expandedEvents.add(messageObject.eventId); } saveScrollPosition(true); filterDeletedMessages(); chatAdapter.notifyDataSetChanged(); } }); chatMessageCell.setAllowAssistant(true); } else if (viewType == 1) { view = new ChatActionCell(mContext) { @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); // if alpha == 0, then visibleToUser == false, so we need to override it // to keep accessibility working correctly info.setVisibleToUser(true); } }; ((ChatActionCell) view).setDelegate(new ChatActionCell.ChatActionCellDelegate() { @Override public void didClickImage(ChatActionCell cell) { MessageObject message = cell.getMessageObject(); if (message.type == MessageObject.TYPE_ACTION_WALLPAPER) { presentFragment(new ChannelColorActivity(getDialogId()).setOnApplied(ChannelAdminLogActivity.this)); return; } PhotoViewer.getInstance().setParentActivity(ChannelAdminLogActivity.this); TLRPC.PhotoSize photoSize = FileLoader.getClosestPhotoSizeWithSize(message.photoThumbs, 640); if (photoSize != null) { ImageLocation imageLocation = ImageLocation.getForPhoto(photoSize, message.messageOwner.action.photo); PhotoViewer.getInstance().openPhoto(photoSize.location, imageLocation, provider); } else { PhotoViewer.getInstance().openPhoto(message, null, 0, 0, 0, provider); } } @Override public boolean didLongPress(ChatActionCell cell, float x, float y) { return createMenu(cell); } @Override public void needOpenUserProfile(long uid) { if (uid < 0) { Bundle args = new Bundle(); args.putLong("chat_id", -uid); if (MessagesController.getInstance(currentAccount).checkCanOpenChat(args, ChannelAdminLogActivity.this)) { presentFragment(new ChatActivity(args), true); } } else if (uid != UserConfig.getInstance(currentAccount).getClientUserId()) { Bundle args = new Bundle(); args.putLong("user_id", uid); addCanBanUser(args, uid); ProfileActivity fragment = new ProfileActivity(args); fragment.setPlayProfileAnimation(0); presentFragment(fragment); } } public void needOpenInviteLink(final TLRPC.TL_chatInviteExported invite) { if (linviteLoading) { return; } Object cachedInvite = invitesCache.containsKey(invite.link) ? invitesCache.get(invite.link) : null; if (cachedInvite == null) { TLRPC.TL_messages_getExportedChatInvite req = new TLRPC.TL_messages_getExportedChatInvite(); req.peer = getMessagesController().getInputPeer(-currentChat.id); req.link = invite.link; linviteLoading = true; boolean[] canceled = new boolean[1]; final AlertDialog progressDialog = new AlertDialog(getParentActivity(), AlertDialog.ALERT_TYPE_SPINNER); progressDialog.setOnCancelListener(dialogInterface -> { linviteLoading = false; canceled[0] = true; }); progressDialog.showDelayed(300); int reqId = getConnectionsManager().sendRequest(req, (response, error) -> { TLRPC.TL_messages_exportedChatInvite resInvite = null; if (error == null) { resInvite = (TLRPC.TL_messages_exportedChatInvite) response; for (int i = 0; i < resInvite.users.size(); i++) { TLRPC.User user = resInvite.users.get(i); if (usersMap == null) { usersMap = new HashMap<>(); } usersMap.put(user.id, user); } } TLRPC.TL_messages_exportedChatInvite finalInvite = resInvite; AndroidUtilities.runOnUIThread(() -> { linviteLoading = false; invitesCache.put(invite.link, finalInvite == null ? 0 : finalInvite); if (canceled[0]) { return; } progressDialog.dismiss(); if (finalInvite != null) { showInviteLinkBottomSheet(finalInvite, usersMap); } else { BulletinFactory.of(ChannelAdminLogActivity.this).createSimpleBulletin(R.raw.linkbroken, getString("LinkHashExpired", R.string.LinkHashExpired)).show(); } }); }); getConnectionsManager().bindRequestToGuid(reqId, classGuid); } else if (cachedInvite instanceof TLRPC.TL_messages_exportedChatInvite) { showInviteLinkBottomSheet((TLRPC.TL_messages_exportedChatInvite) cachedInvite, usersMap); } else { BulletinFactory.of(ChannelAdminLogActivity.this).createSimpleBulletin(R.raw.linkbroken, getString("LinkHashExpired", R.string.LinkHashExpired)).show(); } } @Override public BaseFragment getBaseFragment() { return ChannelAdminLogActivity.this; } @Override public long getDialogId() { return -currentChat.id; } @Override public void didPressReplyMessage(ChatActionCell cell, int id) { } }); } else if (viewType == 2) { view = new ChatUnreadCell(mContext, null); } else { view = new ChatLoadingCell(mContext, contentView, null); } view.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT)); return new RecyclerListView.Holder(view); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (position == loadingUpRow) { ChatLoadingCell loadingCell = (ChatLoadingCell) holder.itemView; loadingCell.setProgressVisible(true); } else if (position >= messagesStartRow && position < messagesEndRow) { MessageObject message = filteredMessages.get(filteredMessages.size() - (position - messagesStartRow) - 1); View view = holder.itemView; if (view instanceof ChatMessageCell) { final ChatMessageCell messageCell = (ChatMessageCell) view; messageCell.isChat = true; int nextType = getItemViewType(position + 1); int prevType = getItemViewType(position - 1); boolean pinnedBotton; boolean pinnedTop; if (!(message.messageOwner.reply_markup instanceof TLRPC.TL_replyInlineMarkup) && nextType == holder.getItemViewType()) { MessageObject nextMessage = filteredMessages.get(filteredMessages.size() - (position + 1 - messagesStartRow) - 1); pinnedBotton = nextMessage.isOutOwner() == message.isOutOwner() && (nextMessage.getFromChatId() == message.getFromChatId()) && Math.abs(nextMessage.messageOwner.date - message.messageOwner.date) <= 5 * 60; if (pinnedBotton) { long topicId = message.replyToForumTopic == null ? MessageObject.getTopicId(currentAccount, message.messageOwner, true) : message.replyToForumTopic.id; long prevTopicId = nextMessage.replyToForumTopic == null ? MessageObject.getTopicId(currentAccount, nextMessage.messageOwner, true) : nextMessage.replyToForumTopic.id; if (topicId != prevTopicId) { pinnedBotton = false; } } } else { pinnedBotton = false; } if (prevType == holder.getItemViewType()) { MessageObject prevMessage = filteredMessages.get(filteredMessages.size() - (position - messagesStartRow)); pinnedTop = !(prevMessage.messageOwner.reply_markup instanceof TLRPC.TL_replyInlineMarkup) && prevMessage.isOutOwner() == message.isOutOwner() && (prevMessage.getFromChatId() == message.getFromChatId()) && Math.abs(prevMessage.messageOwner.date - message.messageOwner.date) <= 5 * 60; if (pinnedTop) { long topicId = message.replyToForumTopic == null ? MessageObject.getTopicId(currentAccount, message.messageOwner, true) : message.replyToForumTopic.id; long prevTopicId = prevMessage.replyToForumTopic == null ? MessageObject.getTopicId(currentAccount, prevMessage.messageOwner, true) : prevMessage.replyToForumTopic.id; if (topicId != prevTopicId) { pinnedTop = false; } } } else { pinnedTop = false; } messageCell.setMessageObject(message, null, pinnedBotton, pinnedTop); messageCell.setHighlighted(false); messageCell.setHighlightedText(searchQuery); } else if (view instanceof ChatActionCell) { ChatActionCell actionCell = (ChatActionCell) view; actionCell.setMessageObject(message); actionCell.setAlpha(1.0f); } } } @Override public int getItemViewType(int position) { if (position >= messagesStartRow && position < messagesEndRow) { return filteredMessages.get(filteredMessages.size() - (position - messagesStartRow) - 1).contentType; } return 4; } @Override public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) { if (holder.itemView instanceof ChatMessageCell || holder.itemView instanceof ChatActionCell) { View view = holder.itemView; holder.itemView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { view.getViewTreeObserver().removeOnPreDrawListener(this); int height = chatListView.getMeasuredHeight(); int top = view.getTop(); int bottom = view.getBottom(); int viewTop = top >= 0 ? 0 : -top; int viewBottom = view.getMeasuredHeight(); if (viewBottom > height) { viewBottom = viewTop + height; } if (holder.itemView instanceof ChatMessageCell) { ((ChatMessageCell) view).setVisiblePart(viewTop, viewBottom - viewTop, contentView.getHeightWithKeyboard() - dp(48) - chatListView.getTop(), 0, view.getY() + actionBar.getMeasuredHeight() - contentView.getBackgroundTranslationY(), contentView.getMeasuredWidth(), contentView.getBackgroundSizeY(), 0, 0); } else if (holder.itemView instanceof ChatActionCell) { if (actionBar != null && contentView != null) { ((ChatActionCell) view).setVisiblePart(view.getY() + actionBar.getMeasuredHeight() - contentView.getBackgroundTranslationY(), contentView.getBackgroundSizeY()); } } return true; } }); } if (holder.itemView instanceof ChatMessageCell) { final ChatMessageCell messageCell = (ChatMessageCell) holder.itemView; MessageObject message = messageCell.getMessageObject(); messageCell.setBackgroundDrawable(null); messageCell.setCheckPressed(true, false); messageCell.setHighlighted(false); } } public void updateRowWithMessageObject(MessageObject messageObject) { int index = filteredMessages.indexOf(messageObject); if (index == -1) { return; } notifyItemChanged(messagesStartRow + filteredMessages.size() - index - 1); } @Override public void notifyDataSetChanged() { updateRows(); try { super.notifyDataSetChanged(); } catch (Exception e) { FileLog.e(e); } } @Override public void notifyItemChanged(int position) { updateRows(false); try { super.notifyItemChanged(position); } catch (Exception e) { FileLog.e(e); } } @Override public void notifyItemRangeChanged(int positionStart, int itemCount) { updateRows(false); try { super.notifyItemRangeChanged(positionStart, itemCount); } catch (Exception e) { FileLog.e(e); } } @Override public void notifyItemInserted(int position) { updateRows(false); try { super.notifyItemInserted(position); } catch (Exception e) { FileLog.e(e); } } @Override public void notifyItemMoved(int fromPosition, int toPosition) { updateRows(false); try { super.notifyItemMoved(fromPosition, toPosition); } catch (Exception e) { FileLog.e(e); } } @Override public void notifyItemRangeInserted(int positionStart, int itemCount) { updateRows(false); try { super.notifyItemRangeInserted(positionStart, itemCount); } catch (Exception e) { FileLog.e(e); } } @Override public void notifyItemRemoved(int position) { updateRows(false); try { super.notifyItemRemoved(position); } catch (Exception e) { FileLog.e(e); } } @Override public void notifyItemRangeRemoved(int positionStart, int itemCount) { updateRows(false); try { super.notifyItemRangeRemoved(positionStart, itemCount); } catch (Exception e) { FileLog.e(e); } } } private void showInviteLinkBottomSheet(TLRPC.TL_messages_exportedChatInvite invite, HashMap<Long, TLRPC.User> usersMap) { TLRPC.ChatFull chatInfo = getMessagesController().getChatFull(currentChat.id); InviteLinkBottomSheet inviteLinkBottomSheet = new InviteLinkBottomSheet(contentView.getContext(), (TLRPC.TL_chatInviteExported) invite.invite, chatInfo, usersMap, ChannelAdminLogActivity.this, chatInfo.id, false, ChatObject.isChannel(currentChat)); inviteLinkBottomSheet.setInviteDelegate(new InviteLinkBottomSheet.InviteDelegate() { @Override public void permanentLinkReplaced(TLRPC.TL_chatInviteExported oldLink, TLRPC.TL_chatInviteExported newLink) { } @Override public void linkRevoked(TLRPC.TL_chatInviteExported invite) { TLRPC.TL_channelAdminLogEvent event = new TLRPC.TL_channelAdminLogEvent(); int size = filteredMessages.size(); invite.revoked = true; TLRPC.TL_channelAdminLogEventActionExportedInviteRevoke revokeAction = new TLRPC.TL_channelAdminLogEventActionExportedInviteRevoke(); revokeAction.invite = invite; event.action = revokeAction; event.date = (int) (System.currentTimeMillis() / 1000L); event.user_id = getAccountInstance().getUserConfig().clientUserId; MessageObject messageObject = new MessageObject(currentAccount, event, messages, messagesByDays, currentChat, mid, true); if (messageObject.contentType < 0) { return; } filterDeletedMessages(); int addCount = filteredMessages.size() - size; if (addCount > 0) { chatListItemAnimator.setShouldAnimateEnterFromBottom(true); chatAdapter.notifyItemRangeInserted(chatAdapter.messagesEndRow, addCount); moveScrollToLastMessage(); } invitesCache.remove(invite.link); } @Override public void onLinkDeleted(TLRPC.TL_chatInviteExported invite) { int size = filteredMessages.size(); int messagesEndRow = chatAdapter.messagesEndRow; TLRPC.TL_channelAdminLogEvent event = new TLRPC.TL_channelAdminLogEvent(); TLRPC.TL_channelAdminLogEventActionExportedInviteDelete deleteAction = new TLRPC.TL_channelAdminLogEventActionExportedInviteDelete(); deleteAction.invite = invite; event.action = deleteAction; event.date = (int) (System.currentTimeMillis() / 1000L); event.user_id = getAccountInstance().getUserConfig().clientUserId; MessageObject messageObject = new MessageObject(currentAccount, event, messages, messagesByDays, currentChat, mid, true); if (messageObject.contentType < 0) { return; } filterDeletedMessages(); int addCount = filteredMessages.size() - size; if (addCount > 0) { chatListItemAnimator.setShouldAnimateEnterFromBottom(true); chatAdapter.notifyItemRangeInserted(chatAdapter.messagesEndRow, addCount); moveScrollToLastMessage(); } invitesCache.remove(invite.link); } @Override public void onLinkEdited(TLRPC.TL_chatInviteExported invite) { TLRPC.TL_channelAdminLogEvent event = new TLRPC.TL_channelAdminLogEvent(); TLRPC.TL_channelAdminLogEventActionExportedInviteEdit editAction = new TLRPC.TL_channelAdminLogEventActionExportedInviteEdit(); editAction.new_invite = invite; editAction.prev_invite = invite; event.action = editAction; event.date = (int) (System.currentTimeMillis() / 1000L); event.user_id = getAccountInstance().getUserConfig().clientUserId; MessageObject messageObject = new MessageObject(currentAccount, event, messages, messagesByDays, currentChat, mid, true); if (messageObject.contentType < 0) { return; } filterDeletedMessages(); chatAdapter.notifyDataSetChanged(); moveScrollToLastMessage(); } }); inviteLinkBottomSheet.show(); } @Override public ArrayList<ThemeDescription> getThemeDescriptions() { ArrayList<ThemeDescription> themeDescriptions = new ArrayList<>(); themeDescriptions.add(new ThemeDescription(fragmentView, 0, null, null, null, null, Theme.key_chat_wallpaper)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_actionBarDefault)); themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_LISTGLOWCOLOR, null, null, null, null, Theme.key_actionBarDefault)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_ITEMSCOLOR, null, null, null, null, Theme.key_actionBarDefaultIcon)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SELECTORCOLOR, null, null, null, null, Theme.key_actionBarDefaultSelector)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SUBMENUBACKGROUND, null, null, null, null, Theme.key_actionBarDefaultSubmenuBackground)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SUBMENUITEM, null, null, null, null, Theme.key_actionBarDefaultSubmenuItem)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SUBMENUITEM | ThemeDescription.FLAG_IMAGECOLOR, null, null, null, null, Theme.key_actionBarDefaultSubmenuItemIcon)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_actionBarDefault)); themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_LISTGLOWCOLOR, null, null, null, null, Theme.key_actionBarDefault)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_ITEMSCOLOR, null, null, null, null, Theme.key_actionBarDefaultIcon)); themeDescriptions.add(new ThemeDescription(avatarContainer.getTitleTextView(), ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_actionBarDefaultTitle)); themeDescriptions.add(new ThemeDescription(avatarContainer.getSubtitleTextView(), ThemeDescription.FLAG_TEXTCOLOR, null, new Paint[]{Theme.chat_statusPaint, Theme.chat_statusRecordPaint}, null, null, Theme.key_actionBarDefaultSubtitle, null)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SELECTORCOLOR, null, null, null, null, Theme.key_actionBarDefaultSelector)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.avatarDrawables, null, Theme.key_avatar_text)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_backgroundRed)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_backgroundOrange)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_backgroundViolet)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_backgroundGreen)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_backgroundCyan)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_backgroundBlue)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_backgroundPink)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_nameInMessageRed)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_nameInMessageOrange)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_nameInMessageViolet)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_nameInMessageGreen)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_nameInMessageCyan)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_nameInMessageBlue)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_nameInMessagePink)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInDrawable, Theme.chat_msgInMediaDrawable}, null, Theme.key_chat_inBubble)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInSelectedDrawable, Theme.chat_msgInMediaSelectedDrawable}, null, Theme.key_chat_inBubbleSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgInDrawable.getShadowDrawables(), null, Theme.key_chat_inBubbleShadow)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgInMediaDrawable.getShadowDrawables(), null, Theme.key_chat_inBubbleShadow)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgOutDrawable.getShadowDrawables(), null, Theme.key_chat_outBubbleShadow)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgOutMediaDrawable.getShadowDrawables(), null, Theme.key_chat_outBubbleShadow)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutDrawable, Theme.chat_msgOutMediaDrawable}, null, Theme.key_chat_outBubble)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutDrawable, Theme.chat_msgOutMediaDrawable}, null, Theme.key_chat_outBubbleGradient1)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutDrawable, Theme.chat_msgOutMediaDrawable}, null, Theme.key_chat_outBubbleGradient2)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutDrawable, Theme.chat_msgOutMediaDrawable}, null, Theme.key_chat_outBubbleGradient3)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutSelectedDrawable, Theme.chat_msgOutMediaSelectedDrawable}, null, Theme.key_chat_outBubbleSelected)); themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_TEXTCOLOR, new Class[]{ChatActionCell.class}, Theme.chat_actionTextPaint, null, null, Theme.key_chat_serviceText)); themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_LINKCOLOR, new Class[]{ChatActionCell.class}, Theme.chat_actionTextPaint, null, null, Theme.key_chat_serviceLink)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_botCardDrawable, Theme.chat_shareIconDrawable, Theme.chat_botInlineDrawable, Theme.chat_botLinkDrawable, Theme.chat_goIconDrawable, Theme.chat_commentStickerDrawable}, null, Theme.key_chat_serviceIcon)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class, ChatActionCell.class}, null, null, null, Theme.key_chat_serviceBackground)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class, ChatActionCell.class}, null, null, null, Theme.key_chat_serviceBackgroundSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_messageTextIn)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_messageTextOut)); themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_LINKCOLOR, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_messageLinkIn, null)); themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_LINKCOLOR, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_messageLinkOut, null)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutCheckDrawable}, null, Theme.key_chat_outSentCheck)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutCheckSelectedDrawable}, null, Theme.key_chat_outSentCheckSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutCheckReadDrawable, Theme.chat_msgOutHalfCheckDrawable}, null, Theme.key_chat_outSentCheckRead)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutCheckReadSelectedDrawable, Theme.chat_msgOutHalfCheckSelectedDrawable}, null, Theme.key_chat_outSentCheckReadSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgMediaCheckDrawable, Theme.chat_msgMediaHalfCheckDrawable}, null, Theme.key_chat_mediaSentCheck)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutViewsDrawable, Theme.chat_msgOutRepliesDrawable, Theme.chat_msgOutPinnedDrawable}, null, Theme.key_chat_outViews)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutViewsSelectedDrawable, Theme.chat_msgOutRepliesSelectedDrawable, Theme.chat_msgOutPinnedSelectedDrawable}, null, Theme.key_chat_outViewsSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInViewsDrawable, Theme.chat_msgInRepliesDrawable, Theme.chat_msgInPinnedDrawable}, null, Theme.key_chat_inViews)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInViewsSelectedDrawable, Theme.chat_msgInRepliesSelectedDrawable, Theme.chat_msgInPinnedSelectedDrawable}, null, Theme.key_chat_inViewsSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgMediaViewsDrawable, Theme.chat_msgMediaRepliesDrawable, Theme.chat_msgMediaPinnedDrawable}, null, Theme.key_chat_mediaViews)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutMenuDrawable}, null, Theme.key_chat_outMenu)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutMenuSelectedDrawable}, null, Theme.key_chat_outMenuSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInMenuDrawable}, null, Theme.key_chat_inMenu)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInMenuSelectedDrawable}, null, Theme.key_chat_inMenuSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgMediaMenuDrawable}, null, Theme.key_chat_mediaMenu)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutInstantDrawable}, null, Theme.key_chat_outInstant)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInInstantDrawable, Theme.chat_commentDrawable, Theme.chat_commentArrowDrawable}, null, Theme.key_chat_inInstant)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgOutCallDrawable, null, Theme.key_chat_outInstant)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgOutCallSelectedDrawable, null, Theme.key_chat_outInstantSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgInCallDrawable, null, Theme.key_chat_inInstant)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgInCallSelectedDrawable, null, Theme.key_chat_inInstantSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgCallUpGreenDrawable}, null, Theme.key_chat_outGreenCall)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgCallDownRedDrawable}, null, Theme.key_fill_RedNormal)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgCallDownGreenDrawable}, null, Theme.key_chat_inGreenCall)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, Theme.chat_msgErrorPaint, null, null, Theme.key_chat_sentError)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgErrorDrawable}, null, Theme.key_chat_sentErrorIcon)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, Theme.chat_durationPaint, null, null, Theme.key_chat_previewDurationText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, Theme.chat_gamePaint, null, null, Theme.key_chat_previewGameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inPreviewInstantText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outPreviewInstantText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, Theme.chat_deleteProgressPaint, null, null, Theme.key_chat_secretTimeText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_stickerNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, Theme.chat_botButtonPaint, null, null, Theme.key_chat_botButtonText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inForwardedNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outForwardedNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inViaBotNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outViaBotNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_stickerViaBotNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inReplyLine)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outReplyLine)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outReplyLine2)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_stickerReplyLine)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inReplyNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outReplyNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_stickerReplyNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inReplyMessageText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outReplyMessageText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inReplyMediaMessageText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outReplyMediaMessageText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inReplyMediaMessageSelectedText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outReplyMediaMessageSelectedText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_stickerReplyMessageText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inPreviewLine)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outPreviewLine)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inSiteNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outSiteNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inContactNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outContactNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inContactPhoneText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outContactPhoneText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_mediaProgress)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inAudioProgress)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outAudioProgress)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inAudioSelectedProgress)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outAudioSelectedProgress)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_mediaTimeText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inTimeText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outTimeText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inTimeSelectedText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outTimeSelectedText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inAudioPerformerText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outAudioPerformerText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inAudioTitleText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outAudioTitleText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inAudioDurationText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outAudioDurationText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inAudioDurationSelectedText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outAudioDurationSelectedText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inAudioSeekbar)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outAudioSeekbar)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inAudioSeekbarSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outAudioSeekbarSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inAudioSeekbarFill)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inAudioCacheSeekbar)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outAudioSeekbarFill)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outAudioCacheSeekbar)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inVoiceSeekbar)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outVoiceSeekbar)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inVoiceSeekbarSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outVoiceSeekbarSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inVoiceSeekbarFill)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outVoiceSeekbarFill)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inFileProgress)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outFileProgress)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inFileProgressSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outFileProgressSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inFileNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outFileNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inFileInfoText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outFileInfoText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inFileInfoSelectedText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outFileInfoSelectedText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inFileBackground)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outFileBackground)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inFileBackgroundSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outFileBackgroundSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inVenueInfoText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outVenueInfoText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inVenueInfoSelectedText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outVenueInfoSelectedText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_mediaInfoText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, Theme.chat_urlPaint, null, null, Theme.key_chat_inReplyLine)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, Theme.chat_textSearchSelectionPaint, null, null, Theme.key_chat_outReplyLine)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outLoader)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outMediaIcon)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outLoaderSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outMediaIconSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inLoader)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inMediaIcon)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inLoaderSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inMediaIconSelected)); themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_BACKGROUNDFILTER, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_contactDrawable[0]}, null, Theme.key_chat_inContactBackground)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_contactDrawable[0]}, null, Theme.key_chat_inContactIcon)); themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_BACKGROUNDFILTER, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_contactDrawable[1]}, null, Theme.key_chat_outContactBackground)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_contactDrawable[1]}, null, Theme.key_chat_outContactIcon)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inLocationBackground)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_locationDrawable[0]}, null, Theme.key_chat_inLocationIcon)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_locationDrawable[1]}, null, Theme.key_chat_outLocationIcon)); themeDescriptions.add(new ThemeDescription(bottomOverlayChat, 0, null, Theme.chat_composeBackgroundPaint, null, null, Theme.key_chat_messagePanelBackground)); themeDescriptions.add(new ThemeDescription(bottomOverlayChat, 0, null, null, new Drawable[]{Theme.chat_composeShadowDrawable}, null, Theme.key_chat_messagePanelShadow)); themeDescriptions.add(new ThemeDescription(bottomOverlayChatText, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_chat_fieldOverlayText)); themeDescriptions.add(new ThemeDescription(emptyView, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_chat_serviceText)); themeDescriptions.add(new ThemeDescription(progressBar, ThemeDescription.FLAG_PROGRESSBAR, null, null, null, null, Theme.key_chat_serviceText)); themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_USEBACKGROUNDDRAWABLE, new Class[]{ChatUnreadCell.class}, new String[]{"backgroundLayout"}, null, null, null, Theme.key_chat_unreadMessagesStartBackground)); themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_IMAGECOLOR, new Class[]{ChatUnreadCell.class}, new String[]{"imageView"}, null, null, null, Theme.key_chat_unreadMessagesStartArrowIcon)); themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_TEXTCOLOR, new Class[]{ChatUnreadCell.class}, new String[]{"textView"}, null, null, null, Theme.key_chat_unreadMessagesStartText)); themeDescriptions.add(new ThemeDescription(progressView2, ThemeDescription.FLAG_SERVICEBACKGROUND, null, null, null, null, Theme.key_chat_serviceBackground)); themeDescriptions.add(new ThemeDescription(emptyView, ThemeDescription.FLAG_SERVICEBACKGROUND, null, null, null, null, Theme.key_chat_serviceBackground)); themeDescriptions.add(new ThemeDescription(undoView, ThemeDescription.FLAG_BACKGROUNDFILTER, null, null, null, null, Theme.key_undo_background)); themeDescriptions.add(new ThemeDescription(undoView, 0, new Class[]{UndoView.class}, new String[]{"undoImageView"}, null, null, null, Theme.key_undo_cancelColor)); themeDescriptions.add(new ThemeDescription(undoView, 0, new Class[]{UndoView.class}, new String[]{"undoTextView"}, null, null, null, Theme.key_undo_cancelColor)); themeDescriptions.add(new ThemeDescription(undoView, 0, new Class[]{UndoView.class}, new String[]{"infoTextView"}, null, null, null, Theme.key_undo_infoColor)); themeDescriptions.add(new ThemeDescription(undoView, 0, new Class[]{UndoView.class}, new String[]{"textPaint"}, null, null, null, Theme.key_undo_infoColor)); themeDescriptions.add(new ThemeDescription(undoView, 0, new Class[]{UndoView.class}, new String[]{"progressPaint"}, null, null, null, Theme.key_undo_infoColor)); themeDescriptions.add(new ThemeDescription(undoView, ThemeDescription.FLAG_IMAGECOLOR, new Class[]{UndoView.class}, new String[]{"leftImageView"}, null, null, null, Theme.key_undo_infoColor)); return themeDescriptions; } public void scrollToMessage(MessageObject object, boolean select) { wasManualScroll = true; int scrollDirection = RecyclerAnimationScrollHelper.SCROLL_DIRECTION_UNSET; int scrollFromIndex = 0; if (filteredMessages.size() > 0) { int end = chatLayoutManager.findLastVisibleItemPosition(); for (int i = chatLayoutManager.findFirstVisibleItemPosition(); i <= end; i++) { if (i >= chatAdapter.messagesStartRow && i < chatAdapter.messagesEndRow) { MessageObject messageObject = filteredMessages.get(i - chatAdapter.messagesStartRow); if (messageObject.contentType == 1 || messageObject.getRealId() == 0 || messageObject.isSponsored()) { continue; } scrollFromIndex = i - chatAdapter.messagesStartRow; boolean scrollDown = messageObject.getRealId() < object.getRealId(); scrollDirection = scrollDown ? RecyclerAnimationScrollHelper.SCROLL_DIRECTION_DOWN : RecyclerAnimationScrollHelper.SCROLL_DIRECTION_UP; break; } } } chatScrollHelper.setScrollDirection(scrollDirection); if (object != null) { int index = filteredMessages.indexOf(object); if (index != -1) { if (scrollFromIndex > 0) { scrollDirection = scrollFromIndex > index ? RecyclerAnimationScrollHelper.SCROLL_DIRECTION_DOWN : RecyclerAnimationScrollHelper.SCROLL_DIRECTION_UP; chatScrollHelper.setScrollDirection(scrollDirection); } removeSelectedMessageHighlight(); if (select) { highlightMessageId = object.getRealId(); } // chatAdapter.updateRowsSafe(); int position = chatAdapter.messagesStartRow + filteredMessages.indexOf(object); updateVisibleRows(); boolean found = false; int offsetY = 0; int count = chatListView.getChildCount(); for (int a = 0; a < count; a++) { View view = chatListView.getChildAt(a); if (view instanceof ChatMessageCell) { ChatMessageCell cell = (ChatMessageCell) view; MessageObject messageObject = cell.getMessageObject(); if (messageObject != null && messageObject.getRealId() == object.getRealId()) { found = true; view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); offsetY = scrollOffsetForQuote(messageObject); } } else if (view instanceof ChatActionCell) { ChatActionCell cell = (ChatActionCell) view; MessageObject messageObject = cell.getMessageObject(); if (messageObject != null && messageObject.getRealId() == object.getRealId()) { found = true; view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); } } if (found) { int yOffset = getScrollOffsetForMessage(view.getHeight()) - offsetY; int scrollY = (int) (view.getTop() - /*chatListViewPaddingTop - */yOffset); int maxScrollOffset = chatListView.computeVerticalScrollRange() - chatListView.computeVerticalScrollOffset() - chatListView.computeVerticalScrollExtent(); if (maxScrollOffset < 0) { maxScrollOffset = 0; } if (scrollY > maxScrollOffset) { scrollY = maxScrollOffset; } if (scrollY != 0) { // scrollByTouch = false; chatListView.smoothScrollBy(0, scrollY); chatListView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER); } break; } } if (!found) { int yOffset = getScrollOffsetForMessage(object); chatScrollHelperCallback.scrollTo = object; chatScrollHelperCallback.lastBottom = false; chatScrollHelperCallback.lastItemOffset = yOffset; // chatScrollHelperCallback.lastPadding = (int) chatListViewPaddingTop; chatScrollHelper.setScrollDirection(scrollDirection); chatScrollHelper.scrollToPosition(chatScrollHelperCallback.position = position, chatScrollHelperCallback.offset = yOffset, chatScrollHelperCallback.bottom = false, true); // canShowPagedownButton = true; // updatePagedownButtonVisibility(true); } } } // returnToMessageId = fromMessageId; // returnToLoadIndex = loadIndex; // needSelectFromMessageId = select; } private boolean wasManualScroll; private MessageObject scrollToMessage; public int highlightMessageId = Integer.MAX_VALUE; public boolean showNoQuoteAlert; public String highlightMessageQuote; public int highlightMessageQuoteOffset = -1; private int scrollToMessagePosition = -10000; private Runnable unselectRunnable; private void startMessageUnselect() { if (unselectRunnable != null) { AndroidUtilities.cancelRunOnUIThread(unselectRunnable); } unselectRunnable = () -> { highlightMessageId = Integer.MAX_VALUE; highlightMessageQuote = null; highlightMessageQuoteOffset = -1; showNoQuoteAlert = false; updateVisibleRows(); unselectRunnable = null; }; AndroidUtilities.runOnUIThread(unselectRunnable, highlightMessageQuote != null ? 2500 : 1000); } private void removeSelectedMessageHighlight() { if (highlightMessageQuote != null) { return; } if (unselectRunnable != null) { AndroidUtilities.cancelRunOnUIThread(unselectRunnable); unselectRunnable = null; } highlightMessageId = Integer.MAX_VALUE; highlightMessageQuote = null; } private void updateVisibleRows() { updateVisibleRows(false); } private void updateVisibleRows(boolean suppressUpdateMessageObject) { if (chatListView == null) { return; } int lastVisibleItem = RecyclerView.NO_POSITION; int top = 0; // if (!wasManualScroll && unreadMessageObject != null) { // int n = chatListView.getChildCount(); // for (int i = 0; i < n; i++) { // View child = chatListView.getChildAt(i); // if (child instanceof ChatMessageCell && ((ChatMessageCell) child).getMessageObject() == unreadMessageObject) { // int unreadMessageIndex = messages.indexOf(unreadMessageObject); // if (unreadMessageIndex >= 0) { // lastVisibleItem = chatAdapter.messagesStartRow + messages.indexOf(unreadMessageObject); // top = getScrollingOffsetForView(child); // } // break; // } // } // } int count = chatListView.getChildCount(); // MessageObject editingMessageObject = chatActivityEnterView != null ? chatActivityEnterView.getEditingMessageObject() : null; // long linkedChatId = chatInfo != null ? chatInfo.linked_chat_id : 0; for (int a = 0; a < count; a++) { View view = chatListView.getChildAt(a); if (view instanceof ChatMessageCell) { ChatMessageCell cell = (ChatMessageCell) view; MessageObject messageObject = cell.getMessageObject(); if (messageObject == null) continue; boolean disableSelection = false; boolean selected = false; if (actionBar.isActionModeShowed()) { highlightMessageQuote = null; // cell.setCheckBoxVisible(threadMessageObjects == null || !threadMessageObjects.contains(messageObject), true); // int idx = messageObject.getDialogId() == dialog_id ? 0 : 1; // if (selectedMessagesIds[idx].indexOfKey(messageObject.getId()) >= 0) { // setCellSelectionBackground(messageObject, cell, idx, true); // selected = true; // } else { // cell.setDrawSelectionBackground(false); // cell.setChecked(false, false, true); // } disableSelection = true; } else { cell.setDrawSelectionBackground(false); cell.setCheckBoxVisible(false, true); cell.setChecked(false, false, true); } // if ((!cell.getMessageObject().deleted || cell.linkedChatId != linkedChatId) && !suppressUpdateMessageObject) { // cell.setIsUpdating(true); // cell.linkedChatId = chatInfo != null ? chatInfo.linked_chat_id : 0; // cell.setMessageObject(cell.getMessageObject(), cell.getCurrentMessagesGroup(), cell.isPinnedBottom(), cell.isPinnedTop()); // cell.setIsUpdating(false); // } // if (cell != scrimView) { // cell.setCheckPressed(!disableSelection, disableSelection && selected); // } cell.setHighlighted(highlightMessageId != Integer.MAX_VALUE && messageObject != null && messageObject.getRealId() == highlightMessageId); if (highlightMessageId != Integer.MAX_VALUE) { startMessageUnselect(); } if (cell.isHighlighted() && highlightMessageQuote != null) { if (!cell.setHighlightedText(highlightMessageQuote, true, highlightMessageQuoteOffset) && showNoQuoteAlert) { showNoQuoteFound(); } showNoQuoteAlert = false; } else if (!TextUtils.isEmpty(searchQuery)) { cell.setHighlightedText(searchQuery); } else { cell.setHighlightedText(null); } cell.setSpoilersSuppressed(chatListView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE); } else if (view instanceof ChatActionCell) { ChatActionCell cell = (ChatActionCell) view; if (!suppressUpdateMessageObject) { cell.setMessageObject(cell.getMessageObject()); } cell.setSpoilersSuppressed(chatListView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE); } } if (lastVisibleItem != RecyclerView.NO_POSITION) { chatLayoutManager.scrollToPositionWithOffset(lastVisibleItem, top); } } public void showNoQuoteFound() { BulletinFactory.of(this).createSimpleBulletin(R.raw.error, getString(R.string.QuoteNotFound)).show(true); } private ChatMessageCell dummyMessageCell; private int getScrollOffsetForMessage(MessageObject object) { return getScrollOffsetForMessage(getHeightForMessage(object, !TextUtils.isEmpty(highlightMessageQuote))) - scrollOffsetForQuote(object); } private int getScrollOffsetForMessage(int messageHeight) { return (int) Math.max(-dp(2), (chatListView.getMeasuredHeight() - /*blurredViewBottomOffset - chatListViewPaddingTop - */messageHeight) / 2); } private int scrollOffsetForQuote(MessageObject object) { if (TextUtils.isEmpty(highlightMessageQuote) || object == null) { if (dummyMessageCell != null) { dummyMessageCell.computedGroupCaptionY = 0; dummyMessageCell.computedCaptionLayout = null; } return 0; } int offsetY; CharSequence text; ArrayList<MessageObject.TextLayoutBlock> textLayoutBlocks; // if (object.getGroupId() != 0) { // MessageObject.GroupedMessages group = getGroup(object.getGroupId()); // if (dummyMessageCell == null || dummyMessageCell.computedCaptionLayout == null || group == null || group.captionMessage == null) { // if (dummyMessageCell != null) { // dummyMessageCell.computedGroupCaptionY = 0; // dummyMessageCell.computedCaptionLayout = null; // } // return 0; // } // offsetY = dummyMessageCell.computedGroupCaptionY; // text = group.captionMessage.caption; // textLayoutBlocks = dummyMessageCell.computedCaptionLayout.textLayoutBlocks; // } else if (!TextUtils.isEmpty(object.caption) && dummyMessageCell != null && dummyMessageCell.captionLayout != null) { offsetY = (int) dummyMessageCell.captionY; text = object.caption; textLayoutBlocks = dummyMessageCell.captionLayout.textLayoutBlocks; } else { offsetY = 0; text = object.messageText; textLayoutBlocks = object.textLayoutBlocks; if (dummyMessageCell != null && dummyMessageCell.linkPreviewAbove) { offsetY += dummyMessageCell.linkPreviewHeight + dp(10); } } if (dummyMessageCell != null) { dummyMessageCell.computedGroupCaptionY = 0; dummyMessageCell.computedCaptionLayout = null; } if (textLayoutBlocks == null || text == null) { return 0; } int index = MessageObject.findQuoteStart(text.toString(), highlightMessageQuote, highlightMessageQuoteOffset); if (index < 0) { return 0; } for (int i = 0; i < textLayoutBlocks.size(); ++i) { MessageObject.TextLayoutBlock block = textLayoutBlocks.get(i); StaticLayout layout = block.textLayout; String layoutText = layout.getText().toString(); if (index > block.charactersOffset) { final float y; if (index - block.charactersOffset > layoutText.length() - 1) { y = offsetY + (int) (block.textYOffset + block.padTop + block.height); } else { y = offsetY + block.textYOffset + block.padTop + layout.getLineTop(layout.getLineForOffset(index - block.charactersOffset)); } if (y > AndroidUtilities.displaySize.y * (isKeyboardVisible() ? .7f : .5f)) { return (int) (y - AndroidUtilities.displaySize.y * (isKeyboardVisible() ? .7f : .5f)); } return 0; } } return 0; } private int getHeightForMessage(MessageObject object, boolean withGroupCaption) { if (getParentActivity() == null) { return 0; } if (dummyMessageCell == null) { dummyMessageCell = new ChatMessageCell(getParentActivity()); } dummyMessageCell.isChat = currentChat != null; dummyMessageCell.isMegagroup = ChatObject.isChannel(currentChat) && currentChat.megagroup; return dummyMessageCell.computeHeight(object, null, withGroupCaption); } public boolean isKeyboardVisible() { return contentView.getKeyboardHeight() > dp(20); } private int scrollCallbackAnimationIndex; private final ChatScrollCallback chatScrollHelperCallback = new ChatScrollCallback(); public class ChatScrollCallback extends RecyclerAnimationScrollHelper.AnimationCallback { private MessageObject scrollTo; private int position = 0; private boolean bottom = true; private int offset = 0; private int lastItemOffset; private boolean lastBottom; private int lastPadding; @Override public void onStartAnimation() { super.onStartAnimation(); scrollCallbackAnimationIndex = getNotificationCenter().setAnimationInProgress(scrollCallbackAnimationIndex, allowedNotificationsDuringChatListAnimations); // if (pinchToZoomHelper.isInOverlayMode()) { // pinchToZoomHelper.finishZoom(); // } } @Override public void onEndAnimation() { if (scrollTo != null) { // chatAdapter.updateRowsSafe(); int lastItemPosition = chatAdapter.messagesStartRow + filteredMessages.indexOf(scrollTo); if (lastItemPosition >= 0) { chatLayoutManager.scrollToPositionWithOffset(lastItemPosition, (int) (lastItemOffset + lastPadding/* - chatListViewPaddingTop*/), lastBottom); } } else { // chatAdapter.updateRowsSafe(); chatLayoutManager.scrollToPositionWithOffset(position, offset, bottom); } scrollTo = null; checkTextureViewPosition = true; // chatListView.getOnScrollListener().onScrolled(chatListView, 0, chatScrollHelper.getScrollDirection() == RecyclerAnimationScrollHelper.SCROLL_DIRECTION_DOWN ? 1 : -1); updateVisibleRows(); AndroidUtilities.runOnUIThread(() -> getNotificationCenter().onAnimationFinish(scrollCallbackAnimationIndex)); } @Override public void recycleView(View view) { if (view instanceof ChatMessageCell) { chatMessageCellsCache.add((ChatMessageCell) view); } } } private long savedScrollEventId; private int savedScrollPosition = -1; private int savedScrollOffset; public void saveScrollPosition(boolean fromTop) { if (chatListView != null && chatLayoutManager != null && chatListView.getChildCount() > 0) { View view = null; int position = -1; int top = fromTop ? Integer.MAX_VALUE : Integer.MIN_VALUE; for (int i = 0; i < chatListView.getChildCount(); i++) { View child = chatListView.getChildAt(i); int childPosition = chatListView.getChildAdapterPosition(child); if (childPosition >= 0 && (fromTop ? child.getTop() < top : child.getTop() > top)) { view = child; position = childPosition; top = child.getTop(); } } if (view != null) { long eventId = 0; if (view instanceof ChatMessageCell) { eventId = ((ChatMessageCell) view).getMessageObject().eventId; } else if (view instanceof ChatActionCell) { eventId = ((ChatActionCell) view).getMessageObject().eventId; } savedScrollEventId = eventId; savedScrollPosition = position; savedScrollOffset = getScrollingOffsetForView(view); } } } private int getScrollingOffsetForView(View v) { return chatListView.getMeasuredHeight() - v.getBottom() - chatListView.getPaddingBottom(); } public void applyScrolledPosition() { if (chatListView != null && chatLayoutManager != null && savedScrollPosition >= 0) { int adaptedPosition = savedScrollPosition; if (savedScrollEventId != 0) { for (int i = 0; i < chatAdapter.getItemCount(); ++i) { MessageObject msg = chatAdapter.getMessageObject(i); if (msg != null && msg.eventId == savedScrollEventId) { adaptedPosition = i; break; } } } chatLayoutManager.scrollToPositionWithOffset(adaptedPosition, savedScrollOffset, true); savedScrollPosition = -1; savedScrollEventId = 0; } } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/ui/ChannelAdminLogActivity.java
41,718
package org.telegram.ui.Stories; import android.content.Intent; import android.content.SharedPreferences; import android.text.TextUtils; import android.util.Log; import android.util.SparseArray; import android.webkit.MimeTypeMap; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.collection.LongSparseArray; import com.google.android.exoplayer2.util.Consumer; import org.telegram.SQLite.SQLiteCursor; import org.telegram.SQLite.SQLiteDatabase; import org.telegram.SQLite.SQLitePreparedStatement; import org.telegram.messenger.AccountInstance; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.BuildVars; import org.telegram.messenger.ChatObject; import org.telegram.messenger.DialogObject; import org.telegram.messenger.DownloadController; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.ImageLocation; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MediaController; import org.telegram.messenger.MediaDataController; import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesStorage; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.NotificationsController; import org.telegram.messenger.R; import org.telegram.messenger.SendMessagesHelper; import org.telegram.messenger.UserConfig; import org.telegram.messenger.UserObject; import org.telegram.messenger.Utilities; import org.telegram.messenger.VideoEditedInfo; import org.telegram.messenger.support.LongSparseIntArray; import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.NativeByteBuffer; import org.telegram.tgnet.RequestDelegate; import org.telegram.tgnet.SerializedData; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import org.telegram.tgnet.tl.TL_stories; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.Components.Bulletin; import org.telegram.ui.Components.BulletinFactory; import org.telegram.ui.Components.Premium.LimitReachedBottomSheet; import org.telegram.ui.Components.Reactions.ReactionsLayoutInBubble; import org.telegram.ui.LaunchActivity; import org.telegram.ui.StatisticActivity; import org.telegram.ui.Stories.recorder.DraftsController; import org.telegram.ui.Stories.recorder.StoryEntry; import org.telegram.ui.Stories.recorder.StoryPrivacyBottomSheet; import org.telegram.ui.Stories.recorder.StoryRecorder; import org.telegram.ui.Stories.recorder.StoryUploadingService; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.SortedSet; import java.util.TreeSet; public class StoriesController { public final static int STATE_READ = 0; public final static int STATE_UNREAD = 1; public final static int STATE_UNREAD_CLOSE_FRIEND = 2; private final int currentAccount; private final LongSparseArray<ArrayList<UploadingStory>> uploadingStoriesByDialogId = new LongSparseArray<>(); private final LongSparseArray<ArrayList<UploadingStory>> uploadingAndEditingStories = new LongSparseArray<>(); private final LongSparseArray<HashMap<Integer, UploadingStory>> editingStories = new LongSparseArray<>(); public LongSparseIntArray dialogIdToMaxReadId = new LongSparseIntArray(); TL_stories.PeerStories currentUserStories; private ArrayList<TL_stories.PeerStories> dialogListStories = new ArrayList<>(); private ArrayList<TL_stories.PeerStories> hiddenListStories = new ArrayList<>(); private LongSparseArray<TL_stories.PeerStories> allStoriesMap = new LongSparseArray(); private LongSparseIntArray loadingDialogsStories = new LongSparseIntArray(); StoriesStorage storiesStorage; SharedPreferences mainSettings; final LongSparseArray<ViewsForPeerStoriesRequester> pollingViewsForSelfStoriesRequester = new LongSparseArray<>(); public final static Comparator<TL_stories.StoryItem> storiesComparator = Comparator.comparingInt(o -> o.date); //load all stories once and manage they by updates //reload only if user get diffToLong boolean allStoriesLoaded; boolean allHiddenStoriesLoaded; boolean loadingFromDatabase; String state = ""; boolean hasMore; private boolean loadingFromServer; private boolean loadingFromServerHidden; private boolean storiesReadLoaded; private int totalStoriesCount; private int totalStoriesCountHidden; private final DraftsController draftsController; public LongSparseArray<SparseArray<SelfStoryViewsPage.ViewsModel>> selfViewsModel = new LongSparseArray<>(); private String stateHidden; private boolean hasMoreHidden = true; private boolean firstLoad = true; private TL_stories.TL_storiesStealthMode stealthMode; public StoriesController(int currentAccount) { this.currentAccount = currentAccount; storiesStorage = new StoriesStorage(currentAccount); mainSettings = MessagesController.getInstance(currentAccount).getMainSettings(); state = mainSettings.getString("last_stories_state", ""); stateHidden = mainSettings.getString("last_stories_state_hidden", ""); totalStoriesCountHidden = mainSettings.getInt("total_stores_hidden", 0); totalStoriesCount = mainSettings.getInt("total_stores", 0); storiesReadLoaded = mainSettings.getBoolean("read_loaded", false); stealthMode = readStealthMode(mainSettings.getString("stories_stealth_mode", null)); storiesStorage.getMaxReadIds(longSparseIntArray -> dialogIdToMaxReadId = longSparseIntArray); sortStoriesRunnable = () -> { sortDialogStories(dialogListStories); sortDialogStories(hiddenListStories); NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesUpdated); }; draftsController = new DraftsController(currentAccount); } private TL_stories.TL_storiesStealthMode readStealthMode(String string) { if (string == null) { return null; } SerializedData serializedData = new SerializedData(Utilities.hexToBytes(string)); try { TL_stories.TL_storiesStealthMode storiesStealthMode = TL_stories.TL_storiesStealthMode.TLdeserialize(serializedData, serializedData.readInt32(true), true); return storiesStealthMode; } catch (Throwable e) { FileLog.e(e); } return null; } private void writeStealthMode(TL_stories.TL_storiesStealthMode mode) { SharedPreferences.Editor editor = MessagesController.getInstance(currentAccount).getMainSettings().edit(); if (mode == null) { editor.remove("stories_stealth_mode").apply(); return; } SerializedData data = new SerializedData(mode.getObjectSize()); mode.serializeToStream(data); editor.putString("stories_stealth_mode", Utilities.bytesToHex(data.toByteArray())).apply(); } public void loadAllStories() { if (!firstLoad) { loadStories(); loadStoriesRead(); } } private void loadStoriesRead() { if (storiesReadLoaded) { return; } TL_stories.TL_stories_getAllReadPeerStories allReadUserStories = new TL_stories.TL_stories_getAllReadPeerStories(); ConnectionsManager.getInstance(currentAccount).sendRequest(allReadUserStories, (response, error) -> { TLRPC.Updates updates = (TLRPC.Updates) response; if (updates == null) { return; } MessagesController.getInstance(currentAccount).processUpdateArray(updates.updates, updates.users, updates.chats, false, updates.date); AndroidUtilities.runOnUIThread(() -> { storiesReadLoaded = true; mainSettings.edit().putBoolean("read_loaded", true).apply(); }); }); } private void sortDialogStories(ArrayList<TL_stories.PeerStories> list) { fixDeletedAndNonContactsStories(list); Collections.sort(list, peerStoriesComparator); } private void fixDeletedAndNonContactsStories(ArrayList<TL_stories.PeerStories> list) { for (int k = 0; k < list.size(); k++) { TL_stories.PeerStories userStories = list.get(k); long dialogId = DialogObject.getPeerDialogId(userStories.peer); boolean removed = false; if (dialogId > 0) { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(dialogId); if (user != null && !isContactOrService(user)) { list.remove(k); k--; removed = true; } } for (int i = 0; i < userStories.stories.size(); i++) { if (userStories.stories.get(i) instanceof TL_stories.TL_storyItemDeleted) { userStories.stories.remove(i); i--; } } if (!removed && userStories.stories.isEmpty() && !hasUploadingStories(dialogId)) { list.remove(k); k--; } } } @NonNull public DraftsController getDraftsController() { return draftsController; } public boolean hasStories(long dialogId) { if (dialogId == 0) { return false; } if (hasUploadingStories(dialogId)) { return true; } if (isLastUploadingFailed(dialogId)) { return true; } TL_stories.PeerStories stories = allStoriesMap.get(dialogId); if (stories == null) { stories = getStoriesFromFullPeer(dialogId); } return stories != null && !stories.stories.isEmpty(); } public TL_stories.PeerStories getStoriesFromFullPeer(long dialogId) { if (dialogId > 0) { TLRPC.UserFull userFull = MessagesController.getInstance(currentAccount).getUserFull(dialogId); return userFull == null ? null : userFull.stories; } else { TLRPC.ChatFull chatFull = MessagesController.getInstance(currentAccount).getChatFull(-dialogId); return chatFull == null ? null : chatFull.stories; } } public boolean hasStories() { return (dialogListStories != null && dialogListStories.size() > 0) || hasSelfStories(); } public void loadStories() { if (firstLoad) { loadingFromDatabase = true; storiesStorage.getAllStories(allStories -> { loadingFromDatabase = false; if (allStories != null) { processAllStoriesResponse(allStories, false, true, false); loadFromServer(false); loadFromServer(true); } else { cleanup(); loadStories(); } }); } else { loadFromServer(false); loadFromServer(true); } firstLoad = false; } public void loadHiddenStories() { if (hasMoreHidden) { loadFromServer(true); } } public void toggleHidden(long dialogId, boolean hide, boolean request, boolean notify) { ArrayList<TL_stories.PeerStories> removeFrom; ArrayList<TL_stories.PeerStories> insertTo; boolean remove = true; if (hide) { // remove = true; removeFrom = dialogListStories; insertTo = hiddenListStories; } else { removeFrom = hiddenListStories; insertTo = dialogListStories; } TL_stories.PeerStories removed = null; for (int i = 0; i < removeFrom.size(); i++) { if (DialogObject.getPeerDialogId(removeFrom.get(i).peer) == dialogId) { if (remove) { removed = removeFrom.remove(i); } else { removed = removeFrom.get(i); } break; } } if (removed != null) { boolean found = false; for (int i = 0; i < insertTo.size(); i++) { if (DialogObject.getPeerDialogId(insertTo.get(i).peer) == dialogId) { found = true; break; } } if (!found) { insertTo.add(0, removed); AndroidUtilities.cancelRunOnUIThread(sortStoriesRunnable); sortStoriesRunnable.run(); } } if (notify) { NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesUpdated); } MessagesController.getInstance(currentAccount).checkArchiveFolder(); if (request) { if (dialogId >= 0) { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(dialogId); user.stories_hidden = hide; MessagesStorage.getInstance(currentAccount).putUsersAndChats(Collections.singletonList(user), null, false, true); MessagesController.getInstance(currentAccount).putUser(user, false); } else { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); chat.stories_hidden = hide; MessagesStorage.getInstance(currentAccount).putUsersAndChats(null, Collections.singletonList(chat), false, true); MessagesController.getInstance(currentAccount).putChat(chat, false); } TL_stories.TL_stories_togglePeerStoriesHidden req = new TL_stories.TL_stories_togglePeerStoriesHidden(); req.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialogId); req.hidden = hide; ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> { }); } } private void loadFromServer(boolean hidden) { if ((hidden && loadingFromServerHidden) || (!hidden && loadingFromServer) || loadingFromDatabase) { return; } if (hidden) { loadingFromServerHidden = true; } else { loadingFromServer = true; } TL_stories.TL_stories_getAllStories req = new TL_stories.TL_stories_getAllStories(); String state = hidden ? stateHidden : this.state; boolean hasMore = hidden ? hasMoreHidden : this.hasMore; if (!TextUtils.isEmpty(state)) { req.state = state; req.flags |= 1; } boolean isNext = false; if (hasMore && !TextUtils.isEmpty(state)) { isNext = req.next = true; } req.include_hidden = hidden; boolean finalIsNext = isNext; ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { if (hidden) { loadingFromServerHidden = false; } else { loadingFromServer = false; } FileLog.d("StoriesController loaded stories from server state=" + req.state + " more=" + req.next + " " + response); if (response instanceof TL_stories.TL_stories_allStories) { TL_stories.TL_stories_allStories storiesResponse = (TL_stories.TL_stories_allStories) response; MessagesStorage.getInstance(currentAccount).putUsersAndChats(storiesResponse.users, null, true, true); if (!hidden) { this.totalStoriesCount = ((TL_stories.TL_stories_allStories) response).count; this.hasMore = ((TL_stories.TL_stories_allStories) response).has_more; this.state = storiesResponse.state; mainSettings.edit().putString("last_stories_state", this.state) .putBoolean("last_stories_has_more", this.hasMore) .putInt("total_stores", this.totalStoriesCount) .apply(); } else { this.totalStoriesCountHidden = ((TL_stories.TL_stories_allStories) response).count; this.hasMoreHidden = ((TL_stories.TL_stories_allStories) response).has_more; this.stateHidden = storiesResponse.state; mainSettings.edit().putString("last_stories_state_hidden", this.stateHidden) .putBoolean("last_stories_has_more_hidden", this.hasMoreHidden) .putInt("total_stores_hidden", this.totalStoriesCountHidden) .apply(); } processAllStoriesResponse(storiesResponse, hidden, false, finalIsNext); } else if (response instanceof TL_stories.TL_stories_allStoriesNotModified) { if (!hidden) { this.hasMore = mainSettings.getBoolean("last_stories_has_more", false); this.state = ((TL_stories.TL_stories_allStoriesNotModified) response).state; mainSettings.edit().putString("last_stories_state", this.state).apply(); } else { this.hasMoreHidden = mainSettings.getBoolean("last_stories_has_more_hidden", false); this.stateHidden = ((TL_stories.TL_stories_allStoriesNotModified) response).state; mainSettings.edit().putString("last_stories_state_hidden", this.stateHidden).apply(); } boolean hasMoreLocal = hidden ? hasMoreHidden : this.hasMore; if (hasMoreLocal) { NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesUpdated); } } })); } private void processAllStoriesResponse(TL_stories.TL_stories_allStories storiesResponse, boolean hidden, boolean fromCache, boolean isNext) { if (!isNext) { if (!hidden) { //allStoriesMap.clear(); dialogListStories.clear(); } else { hiddenListStories.clear(); } } if (BuildVars.LOGS_ENABLED) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < storiesResponse.peer_stories.size(); i++) { if (builder.length() != 0) { builder.append(", "); } long dialogId = DialogObject.getPeerDialogId(storiesResponse.peer_stories.get(i).peer); builder.append(dialogId); } FileLog.d("StoriesController cache=" + fromCache + " hidden=" + hidden + " processAllStoriesResponse {" + builder + "}"); } MessagesController.getInstance(currentAccount).putUsers(storiesResponse.users, fromCache); MessagesController.getInstance(currentAccount).putChats(storiesResponse.chats, fromCache); for (int i = 0; i < storiesResponse.peer_stories.size(); i++) { TL_stories.PeerStories userStories = storiesResponse.peer_stories.get(i); long dialogId = DialogObject.getPeerDialogId(userStories.peer); for (int j = 0; j < userStories.stories.size(); j++) { if (userStories.stories.get(j) instanceof TL_stories.TL_storyItemDeleted) { NotificationsController.getInstance(currentAccount).processDeleteStory(dialogId, userStories.stories.get(j).id); userStories.stories.remove(j); j--; } } if (!userStories.stories.isEmpty()) { putToAllStories(dialogId, userStories); for (int k = 0; k < 2; k++) { ArrayList<TL_stories.PeerStories> storiesList = k == 0 ? hiddenListStories : dialogListStories; for (int j = 0; j < storiesList.size(); j++) { if (DialogObject.getPeerDialogId(storiesList.get(j).peer) == dialogId) { storiesList.remove(j); break; } } } if (dialogId > 0) { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(dialogId); if (user == null) { continue; } if (user.stories_hidden) { addUserToHiddenList(userStories); } else { dialogListStories.add(userStories); preloadUserStories(userStories); } } else { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); if (chat == null) { continue; } if (chat.stories_hidden) { addUserToHiddenList(userStories); } else { dialogListStories.add(userStories); preloadUserStories(userStories); } } } else { allStoriesMap.remove(dialogId); } } if (!fromCache) { storiesStorage.saveAllStories(storiesResponse.peer_stories, isNext, hidden, () -> { // if (!hidden) { // FileLog.d("StoriesController all stories loaded"); // allStoriesLoaded = true; // mainSettings.edit().putBoolean("stories_loaded", true).apply(); // } else { // FileLog.d("StoriesController all hidden stories loaded"); // allHiddenStoriesLoaded = true; // mainSettings.edit().putBoolean("stories_loaded_hidden", true).apply(); // } }); } sortUserStories(); } private void addUserToHiddenList(TL_stories.PeerStories userStories) { boolean found = false; long dialogId = DialogObject.getPeerDialogId(userStories.peer); if (dialogId == UserConfig.getInstance(currentAccount).getClientUserId()) { return; } for (int i = 0; i < hiddenListStories.size(); i++) { if (DialogObject.getPeerDialogId(hiddenListStories.get(i).peer) == dialogId) { found = true; } } if (!found) { hiddenListStories.add(userStories); } MessagesController.getInstance(currentAccount).checkArchiveFolder(); } private void sortUserStories() { AndroidUtilities.cancelRunOnUIThread(sortStoriesRunnable); sortStoriesRunnable.run(); } public void preloadUserStories(TL_stories.PeerStories userStories) { int preloadPosition = 0; for (int i = 0; i < userStories.stories.size(); i++) { if (userStories.stories.get(i).id > userStories.max_read_id) { preloadPosition = i; break; } } if (userStories.stories.isEmpty()) { return; } long dialogId = DialogObject.getPeerDialogId(userStories.peer); preloadStory(dialogId, userStories.stories.get(preloadPosition)); if (preloadPosition > 0) { preloadStory(dialogId, userStories.stories.get(preloadPosition - 1)); } if (preloadPosition < userStories.stories.size() - 1) { preloadStory(dialogId, userStories.stories.get(preloadPosition + 1)); } } private void preloadStory(long dialogId, TL_stories.StoryItem storyItem) { if (storyItem.attachPath != null) { return; } boolean canPreloadStories = DownloadController.getInstance(currentAccount).canPreloadStories(); if (!canPreloadStories) { return; } boolean isVideo = storyItem.media != null && MessageObject.isVideoDocument(storyItem.media.getDocument()); storyItem.dialogId = dialogId; if (isVideo) { TLRPC.PhotoSize size = FileLoader.getClosestPhotoSizeWithSize(storyItem.media.getDocument().thumbs, 1000); FileLoader.getInstance(currentAccount).loadFile(storyItem.media.getDocument(), storyItem, FileLoader.PRIORITY_LOW, 1); FileLoader.getInstance(currentAccount).loadFile(ImageLocation.getForDocument(size, storyItem.media.getDocument()), storyItem, "jpg", FileLoader.PRIORITY_LOW, 1); } else { TLRPC.Photo photo = storyItem.media == null ? null : storyItem.media.photo; if (photo != null && photo.sizes != null) { TLRPC.PhotoSize size = FileLoader.getClosestPhotoSizeWithSize(photo.sizes, Integer.MAX_VALUE); FileLoader.getInstance(currentAccount).loadFile(ImageLocation.getForPhoto(size, photo), storyItem, "jpg", FileLoader.PRIORITY_LOW, 1); } } } public void uploadStory(StoryEntry entry, boolean count) { UploadingStory uploadingStory = new UploadingStory(entry); if (count) { long dialogId = uploadingStory.dialogId; if (entry.isEdit) { HashMap<Integer, UploadingStory> editigStoriesMap = editingStories.get(dialogId); if (editigStoriesMap == null) { editigStoriesMap = new HashMap<>(); editingStories.put(dialogId, editigStoriesMap); } editigStoriesMap.put(entry.editStoryId, uploadingStory); } else { addUploadingStoryToList(dialogId, uploadingStory, uploadingStoriesByDialogId); } addUploadingStoryToList(dialogId, uploadingStory, uploadingAndEditingStories); if (dialogId != UserConfig.getInstance(currentAccount).clientUserId) { boolean found = false; for (int i = 0; i < dialogListStories.size(); i++) { if (DialogObject.getPeerDialogId(dialogListStories.get(i).peer) == dialogId) { found = true; TL_stories.PeerStories peerStories = dialogListStories.remove(i); dialogListStories.add(0, peerStories); break; } } if (!found) { for (int i = 0; i < hiddenListStories.size(); i++) { if (DialogObject.getPeerDialogId(hiddenListStories.get(i).peer) == dialogId) { found = true; TL_stories.PeerStories peerStories = hiddenListStories.remove(i); hiddenListStories.add(0, peerStories); break; } } } if (!found) { TL_stories.PeerStories peerStories = new TL_stories.TL_peerStories(); peerStories.peer = MessagesController.getInstance(currentAccount).getPeer(dialogId); putToAllStories(dialogId, peerStories); dialogListStories.add(0, peerStories); loadAllStoriesForDialog(dialogId); } } } uploadingStory.start(); NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesUpdated); } private void addUploadingStoryToList(long dialogId, UploadingStory uploadingStory, LongSparseArray<ArrayList<UploadingStory>> sparseArray) { ArrayList<StoriesController.UploadingStory> arrayList = sparseArray.get(dialogId); if (arrayList == null) { arrayList = new ArrayList<>(); sparseArray.put(dialogId, arrayList); } arrayList.add(uploadingStory); } public void putUploadingDrafts(ArrayList<StoryEntry> entries) { for (StoryEntry entry : entries) { UploadingStory uploadingStory = new UploadingStory(entry); long dialogId = uploadingStory.dialogId; addUploadingStoryToList(dialogId, uploadingStory, uploadingStoriesByDialogId); } NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesUpdated); } public ArrayList<TL_stories.PeerStories> getDialogListStories() { return dialogListStories; } public TL_stories.PeerStories getStories(long peerId) { return allStoriesMap.get(peerId); } public ArrayList<UploadingStory> getUploadingStories(long dialogId) { return uploadingStoriesByDialogId.get(dialogId); } public boolean isLastUploadingFailed(long dialogId) { ArrayList<UploadingStory> uploadingStories = uploadingStoriesByDialogId.get(dialogId); if (uploadingStories != null && !uploadingStories.isEmpty()) { return uploadingStories.get(uploadingStories.size() - 1).failed; } return false; } public ArrayList<UploadingStory> getUploadingAndEditingStories(long dialogId) { return uploadingAndEditingStories.get(dialogId); } public int getMyStoriesCount() { ArrayList<UploadingStory> myUploadingStories = uploadingAndEditingStories.get(getSelfUserId()); int count = myUploadingStories == null ? 0 : myUploadingStories.size(); TL_stories.PeerStories userStories = getStories(getSelfUserId()); if (userStories != null && userStories.stories != null) { count += userStories.stories.size(); } return count; } public UploadingStory findEditingStory(long dialogId, TL_stories.StoryItem storyItem) { if (storyItem == null) { return null; } HashMap<Integer, UploadingStory> editingStoriesMap = editingStories.get(dialogId); if (editingStoriesMap == null || editingStoriesMap.isEmpty()) { return null; } return editingStoriesMap.get(storyItem.id); } public UploadingStory getEditingStory(long dialogId) { HashMap<Integer, UploadingStory> editingStoriesMap = editingStories.get(dialogId); if (editingStoriesMap == null || editingStoriesMap.isEmpty()) { return null; } Collection<UploadingStory> values = editingStoriesMap.values(); if (values.isEmpty()) { return null; } return values.iterator().next(); } private void applyNewStories(TL_stories.PeerStories stories) { long dialogId = DialogObject.getPeerDialogId(stories.peer); putToAllStories(dialogId, stories); if (dialogId != UserConfig.getInstance(UserConfig.selectedAccount).clientUserId) { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(dialogId); applyToList(stories); if (user != null && !user.stories_hidden) { preloadUserStories(stories); } } FileLog.d("StoriesController applyNewStories " + dialogId); updateStoriesInLists(dialogId, stories.stories); } private void putToAllStories(long dialogId, TL_stories.PeerStories stories) { TL_stories.PeerStories old = allStoriesMap.get(dialogId); if ( old != null && old.stories != null && !old.stories.isEmpty() && stories != null && stories.stories != null && !stories.stories.isEmpty() ) { // do not override loaded stories with skipped ones for (int i = 0; i < stories.stories.size(); ++i) { if (stories.stories.get(i) instanceof TL_stories.TL_storyItemSkipped) { int storyId = stories.stories.get(i).id; for (int j = 0; j < old.stories.size(); ++j) { if (old.stories.get(j).id == storyId && old.stories.get(j) instanceof TL_stories.TL_storyItem) { stories.stories.set(i, old.stories.get(j)); break; } } } } } allStoriesMap.put(dialogId, stories); } public static TL_stories.StoryItem applyStoryUpdate(TL_stories.StoryItem oldStoryItem, TL_stories.StoryItem newStoryItem) { if (newStoryItem == null) { return oldStoryItem; } if (oldStoryItem == null) { return newStoryItem; } if (newStoryItem.min) { oldStoryItem.pinned = newStoryItem.pinned; oldStoryItem.isPublic = newStoryItem.isPublic; oldStoryItem.close_friends = newStoryItem.close_friends; if (newStoryItem.date != 0) { oldStoryItem.date = newStoryItem.date; } if (newStoryItem.expire_date != 0) { oldStoryItem.expire_date = newStoryItem.expire_date; } oldStoryItem.caption = newStoryItem.caption; oldStoryItem.entities = newStoryItem.entities; if (newStoryItem.media != null) { oldStoryItem.media = newStoryItem.media; } // privacy and views shouldn't be copied when min=true return oldStoryItem; } return newStoryItem; } public void processUpdate(TL_stories.TL_updateStory updateStory) { //stage queue if (updateStory.story == null) { return; } long dialogId = DialogObject.getPeerDialogId(updateStory.peer); if (dialogId == 0) { FileLog.d("StoriesController can't update story dialogId == 0"); return; } TLRPC.User user = null; if (dialogId > 0) { user = MessagesController.getInstance(currentAccount).getUser(dialogId); if (user != null && (isContactOrService(user) || user.self)) { storiesStorage.processUpdate(updateStory); } } else { storiesStorage.processUpdate(updateStory); } TLRPC.User finalUser = user; AndroidUtilities.runOnUIThread(() -> { FileLog.d("StoriesController update stories for dialog " + dialogId); updateStoriesInLists(dialogId, Collections.singletonList(updateStory.story)); updateStoriesForFullPeer(dialogId, Collections.singletonList(updateStory.story)); TL_stories.PeerStories currentUserStory = allStoriesMap.get(dialogId); ArrayList<TL_stories.StoryItem> newStoryItems = new ArrayList<>(); int oldStoriesCount = totalStoriesCount; boolean notify = false; if (currentUserStory != null) { boolean changed = false; TL_stories.StoryItem newStory = updateStory.story; if (newStory instanceof TL_stories.TL_storyItemDeleted) { NotificationsController.getInstance(currentAccount).processDeleteStory(dialogId, newStory.id); } boolean found = false; for (int i = 0; i < currentUserStory.stories.size(); i++) { if (currentUserStory.stories.get(i).id == newStory.id) { found = true; if (newStory instanceof TL_stories.TL_storyItemDeleted) { currentUserStory.stories.remove(i); FileLog.d("StoriesController remove story id=" + newStory.id); changed = true; } else { TL_stories.StoryItem oldStory = currentUserStory.stories.get(i); newStory = applyStoryUpdate(oldStory, newStory); newStoryItems.add(newStory); currentUserStory.stories.set(i, newStory); if (newStory.attachPath == null) { newStory.attachPath = oldStory.attachPath; } if (newStory.firstFramePath == null) { newStory.firstFramePath = oldStory.firstFramePath; } FileLog.d("StoriesController update story id=" + newStory.id); } break; } } if (!found) { if (newStory instanceof TL_stories.TL_storyItemDeleted) { FileLog.d("StoriesController can't add new story DELETED"); return; } if (StoriesUtilities.isExpired(currentAccount, newStory)) { FileLog.d("StoriesController can't add new story isExpired"); return; } if (dialogId > 0 && (finalUser == null || (!finalUser.self && !isContactOrService(finalUser)))) { FileLog.d("StoriesController can't add new story user is not contact"); return; } newStoryItems.add(newStory); changed = true; currentUserStory.stories.add(newStory); FileLog.d("StoriesController add new story id=" + newStory.id + " total stories count " + currentUserStory.stories.size()); preloadStory(dialogId, newStory); notify = true; applyToList(currentUserStory); } if (changed) { if (currentUserStory.stories.isEmpty() && !hasUploadingStories(dialogId)) { dialogListStories.remove(currentUserStory); hiddenListStories.remove(currentUserStory); allStoriesMap.remove(DialogObject.getPeerDialogId(currentUserStory.peer)); totalStoriesCount--; } else { Collections.sort(currentUserStory.stories, storiesComparator); } notify = true; } } else { if (updateStory.story instanceof TL_stories.TL_storyItemDeleted) { FileLog.d("StoriesController can't add user " + dialogId + " with new story DELETED"); return; } if (StoriesUtilities.isExpired(currentAccount, updateStory.story)) { FileLog.d("StoriesController can't add user " + dialogId + " with new story isExpired"); return; } if (dialogId > 0 && (finalUser == null || (!finalUser.self && !isContactOrService(finalUser)))) { FileLog.d("StoriesController can't add user cause is not contact"); return; } currentUserStory = new TL_stories.TL_peerStories(); currentUserStory.peer = updateStory.peer; currentUserStory.stories.add(updateStory.story); FileLog.d("StoriesController add new user with story id=" + updateStory.story.id); applyNewStories(currentUserStory); notify = true; totalStoriesCount++; loadAllStoriesForDialog(dialogId); } if (oldStoriesCount != totalStoriesCount) { mainSettings.edit().putInt("total_stores", totalStoriesCount).apply(); } fixDeletedAndNonContactsStories(dialogListStories); fixDeletedAndNonContactsStories(hiddenListStories); if (notify) { NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesUpdated); } MessagesController.getInstance(currentAccount).checkArchiveFolder(); }); } private void updateStoriesForFullPeer(long dialogId, List<TL_stories.StoryItem> newStories) { TL_stories.PeerStories peerStories; if (dialogId > 0) { TLRPC.UserFull userFull = MessagesController.getInstance(currentAccount).getUserFull(dialogId); if (userFull == null) { return; } if (userFull.stories == null) { userFull.stories = new TL_stories.TL_peerStories(); userFull.stories.peer = MessagesController.getInstance(currentAccount).getPeer(dialogId); userFull.stories.max_read_id = getMaxStoriesReadId(dialogId); } peerStories = userFull.stories; } else { TLRPC.ChatFull chatFull = MessagesController.getInstance(currentAccount).getChatFull(-dialogId); if (chatFull == null) { return; } if (chatFull.stories == null) { chatFull.stories = new TL_stories.TL_peerStories(); chatFull.stories.peer = MessagesController.getInstance(currentAccount).getPeer(dialogId); chatFull.stories.max_read_id = getMaxStoriesReadId(dialogId); } peerStories = chatFull.stories; } for (int k = 0; k < newStories.size(); k++) { boolean found = false; TL_stories.StoryItem newStory = newStories.get(k); for (int i = 0; i < peerStories.stories.size(); i++) { if (peerStories.stories.get(i).id == newStory.id) { found = true; if (newStory instanceof TL_stories.TL_storyItemDeleted) { peerStories.stories.remove(i); } else { TL_stories.StoryItem oldStory = peerStories.stories.get(i); newStory = applyStoryUpdate(oldStory, newStory); peerStories.stories.set(i, newStory); if (newStory.attachPath == null) { newStory.attachPath = oldStory.attachPath; } if (newStory.firstFramePath == null) { newStory.firstFramePath = oldStory.firstFramePath; } FileLog.d("StoriesController update story for full peer storyId=" + newStory.id); } break; } } if (!found) { if (newStory instanceof TL_stories.TL_storyItemDeleted) { FileLog.d("StoriesController story is not found, but already deleted storyId=" + newStory.id); } else { FileLog.d("StoriesController add new story for full peer storyId=" + newStory.id); peerStories.stories.add(newStory); } } } } private boolean isContactOrService(TLRPC.User user) { return user != null && (user.contact || user.id == MessagesController.getInstance(currentAccount).storiesChangelogUserId); } private void applyToList(TL_stories.PeerStories currentUserStory) { long dialogId = DialogObject.getPeerDialogId(currentUserStory.peer); TLRPC.User user = null; TLRPC.Chat chat = null; if (dialogId > 0) { user = MessagesController.getInstance(currentAccount).getUser(dialogId); if (user == null) { FileLog.d("StoriesController can't apply story user == null"); return; } } else { chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); if (chat == null) { FileLog.d("StoriesController can't apply story chat == null"); return; } } boolean found = false; for (int i = 0; i < dialogListStories.size(); i++) { if (DialogObject.getPeerDialogId(dialogListStories.get(i).peer) == dialogId) { dialogListStories.remove(i); found = true; break; } } for (int i = 0; i < hiddenListStories.size(); i++) { if (DialogObject.getPeerDialogId(hiddenListStories.get(i).peer) == dialogId) { hiddenListStories.remove(i); found = true; break; } } boolean hidden = (user != null && user.stories_hidden) || (chat != null && chat.stories_hidden); if (BuildVars.LOGS_ENABLED) { FileLog.d("StoriesController move user stories to first " + "hidden=" + hidden + " did=" + dialogId); } if (hidden) { hiddenListStories.add(0, currentUserStory); } else { dialogListStories.add(0, currentUserStory); } if (!found) { loadAllStoriesForDialog(dialogId); } MessagesController.getInstance(currentAccount).checkArchiveFolder(); } HashSet<Long> allStoriesLoading = new HashSet<>(); private void loadAllStoriesForDialog(long user_id) { if (allStoriesLoading.contains(user_id)) { return; } allStoriesLoading.add(user_id); FileLog.d("StoriesController loadAllStoriesForDialog " + user_id); TL_stories.TL_stories_getPeerStories userStories = new TL_stories.TL_stories_getPeerStories(); userStories.peer = MessagesController.getInstance(currentAccount).getInputPeer(user_id); ConnectionsManager.getInstance(currentAccount).sendRequest(userStories, (response, error) -> AndroidUtilities.runOnUIThread(() -> { allStoriesLoading.remove(user_id); if (response == null) { return; } TL_stories.TL_stories_peerStories stories_userStories = (TL_stories.TL_stories_peerStories) response; MessagesController.getInstance(currentAccount).putUsers(stories_userStories.users, false); TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(user_id); TL_stories.PeerStories stories = stories_userStories.stories; long dialogId = DialogObject.getPeerDialogId(stories.peer); allStoriesMap.put(dialogId, stories); if (user != null && (isContactOrService(user) || user.self)) { applyToList(stories); storiesStorage.putPeerStories(stories); } FileLog.d("StoriesController processAllStoriesResponse dialogId=" + user_id + " overwrite stories " + stories_userStories.stories.stories.size()); NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesUpdated); })); } public boolean hasSelfStories() { long clientUserId = UserConfig.getInstance(currentAccount).clientUserId; TL_stories.PeerStories storyItem = allStoriesMap.get(clientUserId); if (storyItem != null && !storyItem.stories.isEmpty()) { return true; } if (!Utilities.isNullOrEmpty(uploadingStoriesByDialogId.get(clientUserId))) { return true; } return false; } public int getSelfStoriesCount() { int count = 0; TL_stories.PeerStories storyItem = allStoriesMap.get(UserConfig.getInstance(currentAccount).clientUserId); if (storyItem != null) { count += storyItem.stories.size(); } count += uploadingStoriesByDialogId.size(); return count; } public void deleteStory(long dialogId, TL_stories.StoryItem storyItem) { if (storyItem == null || storyItem instanceof TL_stories.TL_storyItemDeleted) { return; } for (int k = 0; k < 2; k++) { TL_stories.PeerStories stories = null; TLRPC.UserFull userFull = null; TLRPC.ChatFull chatFull = null; if (k == 0) { stories = allStoriesMap.get(dialogId); } else { if (dialogId >= 0) { userFull = MessagesController.getInstance(currentAccount).getUserFull(dialogId); if (userFull != null) { stories = userFull.stories; } } else { chatFull = MessagesController.getInstance(currentAccount).getChatFull(-dialogId); if (chatFull != null) { stories = chatFull.stories; } } } if (stories != null) { for (int i = 0; i < stories.stories.size(); i++) { if (stories.stories.get(i).id == storyItem.id) { stories.stories.remove(i); if (stories.stories.size() == 0) { if (!hasUploadingStories(dialogId)) { allStoriesMap.remove(dialogId); dialogListStories.remove(stories); hiddenListStories.remove(stories); } if (dialogId > 0) { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(dialogId); if (user != null) { user.stories_unavailable = true; } } else { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); if (chat != null) { chat.stories_unavailable = true; } } } break; } } } if (chatFull != null) { MessagesStorage.getInstance(currentAccount).updateChatInfo(chatFull, false); } if (userFull != null) { MessagesStorage.getInstance(currentAccount).updateUserInfo(userFull, false); } } TL_stories.TL_stories_deleteStories req = new TL_stories.TL_stories_deleteStories(); req.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialogId); req.id.add(storyItem.id); ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> { if (error == null) { AndroidUtilities.runOnUIThread(this::invalidateStoryLimit); } }); storiesStorage.deleteStory(dialogId, storyItem.id); NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesUpdated); MessagesController.getInstance(currentAccount).checkArchiveFolder(); updateDeletedStoriesInLists(dialogId, Arrays.asList(storyItem)); } public void deleteStories(long dialogId, ArrayList<TL_stories.StoryItem> storyItems) { if (storyItems == null) { return; } TL_stories.TL_stories_deleteStories req = new TL_stories.TL_stories_deleteStories(); req.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialogId); if (req.peer == null) { return; } TL_stories.PeerStories stories = allStoriesMap.get(dialogId); for (int i = 0; i < storyItems.size(); ++i) { TL_stories.StoryItem storyItem = storyItems.get(i); if (storyItem instanceof TL_stories.TL_storyItemDeleted) { continue; } if (stories != null) { for (int j = 0; j < stories.stories.size(); j++) { if (stories.stories.get(j).id == storyItem.id) { stories.stories.remove(j); if (stories.stories.isEmpty()) { allStoriesMap.remove(dialogId); } break; } } } req.id.add(storyItem.id); } if (dialogId >= 0) { TLRPC.UserFull userFull = MessagesController.getInstance(currentAccount).getUserFull(dialogId); if (userFull != null && userFull.stories != null) { stories = userFull.stories; } } else { TLRPC.ChatFull chatFull = MessagesController.getInstance(currentAccount).getChatFull(-dialogId); if (chatFull != null && chatFull.stories != null) { stories = chatFull.stories; } } for (int i = 0; i < storyItems.size(); ++i) { TL_stories.StoryItem storyItem = storyItems.get(i); if (storyItem instanceof TL_stories.TL_storyItemDeleted) { continue; } if (stories != null) { for (int j = 0; j < stories.stories.size(); j++) { if (stories.stories.get(j).id == storyItem.id) { stories.stories.remove(j); break; } } } } ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> { AndroidUtilities.runOnUIThread(this::invalidateStoryLimit); }); updateDeletedStoriesInLists(dialogId, storyItems); storiesStorage.deleteStories(dialogId, req.id); NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesUpdated); } public void updateStoriesPinned(long dialogId, ArrayList<TL_stories.StoryItem> storyItems, boolean pinned, Utilities.Callback<Boolean> whenDone) { TL_stories.TL_stories_togglePinned req = new TL_stories.TL_stories_togglePinned(); TL_stories.PeerStories peerStories = getStories(dialogId); for (int i = 0; i < storyItems.size(); ++i) { TL_stories.StoryItem storyItem = storyItems.get(i); if (storyItem instanceof TL_stories.TL_storyItemDeleted) { continue; } storyItem.pinned = pinned; // todo: do update stories in one go in database req.id.add(storyItem.id); if (peerStories != null) { for (int j = 0; j < peerStories.stories.size(); j++) { if (peerStories.stories.get(j).id == storyItem.id) { peerStories.stories.get(j).pinned = pinned; storiesStorage.updateStoryItem(dialogId, storyItem); } } } } FileLog.d("StoriesController updateStoriesPinned"); updateStoriesInLists(dialogId, storyItems); updateStoriesForFullPeer(dialogId, storyItems); req.pinned = pinned; req.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialogId); ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { if (whenDone != null) { whenDone.run(error == null); } })); } private long getSelfUserId() { return UserConfig.getInstance(currentAccount).getClientUserId(); } public void updateStoryItem(long dialogId, TL_stories.StoryItem storyItem) { FileLog.d("StoriesController updateStoryItem " + dialogId + " " + (storyItem == null ? "null" : storyItem.id + "@" + storyItem.dialogId)); storiesStorage.updateStoryItem(dialogId, storyItem); updateStoriesInLists(dialogId, Collections.singletonList(storyItem)); updateStoriesForFullPeer(dialogId, Collections.singletonList(storyItem)); } public boolean markStoryAsRead(long dialogId, TL_stories.StoryItem storyItem) { TL_stories.PeerStories userStories = getStories(dialogId); if (userStories == null) { userStories = getStoriesFromFullPeer(dialogId); } return markStoryAsRead(userStories, storyItem, false); } public boolean markStoryAsRead(TL_stories.PeerStories userStories, TL_stories.StoryItem storyItem, boolean profile) { if (storyItem == null || userStories == null) { return false; } final long dialogId = DialogObject.getPeerDialogId(userStories.peer); if (storyItem.justUploaded) { storyItem.justUploaded = false; } int currentReadId = dialogIdToMaxReadId.get(dialogId); int newReadId = Math.max(userStories.max_read_id, Math.max(currentReadId, storyItem.id)); NotificationsController.getInstance(currentAccount).processReadStories(dialogId, newReadId); userStories.max_read_id = newReadId; dialogIdToMaxReadId.put(dialogId, newReadId); if (newReadId > currentReadId) { if (!profile) { storiesStorage.updateMaxReadId(dialogId, newReadId); } TL_stories.TL_stories_readStories req = new TL_stories.TL_stories_readStories(); req.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialogId); req.max_id = storyItem.id; ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> {}); NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesReadUpdated); return true; } return false; } public int getMaxStoriesReadId(long dialogId) { TL_stories.PeerStories peerStories = getStories(dialogId); if (peerStories == null) { peerStories = getStoriesFromFullPeer(dialogId); } if (peerStories != null) { return Math.max(peerStories.max_read_id, dialogIdToMaxReadId.get(dialogId, 0)); } return dialogIdToMaxReadId.get(dialogId, 0); } public void markStoriesAsReadFromServer(long dialogId, int maxStoryId) { //stage queue AndroidUtilities.runOnUIThread(() -> { int maxStoryReadId = Math.max(dialogIdToMaxReadId.get(dialogId, 0), maxStoryId); dialogIdToMaxReadId.put(dialogId, maxStoryReadId); storiesStorage.updateMaxReadId(dialogId, maxStoryReadId); TL_stories.PeerStories userStories = getStories(dialogId); if (userStories == null) { return; } if (maxStoryId > userStories.max_read_id) { userStories.max_read_id = maxStoryId; Collections.sort(dialogListStories, peerStoriesComparator); NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesUpdated); } }); } public boolean hasUnreadStories(long dialogId) { TL_stories.PeerStories userStories = allStoriesMap.get(dialogId); if (userStories == null) { userStories = getStoriesFromFullPeer(dialogId); } if (userStories == null) { return false; } if (dialogId == UserConfig.getInstance(currentAccount).getClientUserId()) { if (!Utilities.isNullOrEmpty(uploadingStoriesByDialogId.get(dialogId))) { return true; } } for (int i = 0; i < userStories.stories.size(); i++) { TL_stories.StoryItem storyItem = userStories.stories.get(i); if (storyItem == null) continue; // if (userStories.stories.get(i).justUploaded) { // return true; // } if (storyItem.id > userStories.max_read_id) { return true; } } return false; } public int getUnreadState(long dialogId) { return getUnreadState(dialogId, 0); } public int getUnreadState(long dialogId, int storyId) { if (dialogId == 0) { return STATE_READ; } TL_stories.PeerStories peerStories = allStoriesMap.get(dialogId); if (peerStories == null) { peerStories = getStoriesFromFullPeer(dialogId); } if (peerStories == null) { return STATE_READ; } if (dialogId == UserConfig.getInstance(currentAccount).getClientUserId()) { if (!Utilities.isNullOrEmpty(uploadingStoriesByDialogId.get(dialogId))) { return STATE_UNREAD; } } boolean hasUnread = false; int maxReadId = Math.max(peerStories.max_read_id, dialogIdToMaxReadId.get(dialogId, 0)); for (int i = 0; i < peerStories.stories.size(); i++) { if ((storyId == 0 || peerStories.stories.get(i).id == storyId) && peerStories.stories.get(i).id > maxReadId) { hasUnread = true; if (peerStories.stories.get(i).close_friends) { return STATE_UNREAD_CLOSE_FRIEND; } } } if (isLastUploadingFailed(dialogId)) { return STATE_READ; } if (hasUnread) { return STATE_UNREAD; } return STATE_READ; } public boolean hasUploadingStories(long dialogId) { ArrayList<UploadingStory> uploadingStories = uploadingStoriesByDialogId.get(dialogId); HashMap<Integer, UploadingStory> editingStoriesMap = editingStories.get(dialogId); return (uploadingStories != null && !uploadingStories.isEmpty()) || (editingStoriesMap != null && !editingStoriesMap.isEmpty()); } public void cleanup() { allStoriesLoaded = false; allHiddenStoriesLoaded = false; storiesReadLoaded = false; stateHidden = ""; state = ""; mainSettings.edit() .putBoolean("stories_loaded", false) .remove("last_stories_state") .putBoolean("stories_loaded_hidden", false) .remove("last_stories_state_hidden") .putBoolean("read_loaded", false) .apply(); AndroidUtilities.runOnUIThread(draftsController::cleanup); loadStories(); loadStoriesRead(); } public void pollViewsForSelfStories(long dialogId, boolean start) { ViewsForPeerStoriesRequester requester = pollingViewsForSelfStoriesRequester.get(dialogId); if (requester == null) { requester = new ViewsForPeerStoriesRequester(this, dialogId, currentAccount); pollingViewsForSelfStoriesRequester.put(dialogId, requester); } requester.start(start); } public void stopAllPollers() { for (int i = 0; i < pollingViewsForSelfStoriesRequester.size(); i++) { pollingViewsForSelfStoriesRequester.valueAt(i).start(false); } } HashSet<Long> loadingAllStories = new HashSet<>(); void loadSkippedStories(long dialogId) { boolean profile = false; TL_stories.PeerStories peerStories = getStories(dialogId); if (peerStories == null) { profile = true; peerStories = getStoriesFromFullPeer(dialogId); } loadSkippedStories(peerStories, profile); } void loadSkippedStories(TL_stories.PeerStories userStories, boolean profile) { if (userStories == null) { return; } final long dialogId = DialogObject.getPeerDialogId(userStories.peer); final long key = dialogId * (profile ? -1 : 1); if (loadingAllStories.contains(key)) { return; } ArrayList<Integer> storyIdsToLoad = null; if (userStories != null) { for (int i = 0; i < userStories.stories.size(); i++) { if (userStories.stories.get(i) instanceof TL_stories.TL_storyItemSkipped) { if (storyIdsToLoad == null) { storyIdsToLoad = new ArrayList<>(); } storyIdsToLoad.add(userStories.stories.get(i).id); } if (storyIdsToLoad != null && storyIdsToLoad.size() > 14) { break; } } if (storyIdsToLoad != null) { loadingAllStories.add(key); TL_stories.TL_stories_getStoriesByID stories = new TL_stories.TL_stories_getStoriesByID(); stories.id = storyIdsToLoad; stories.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialogId); ConnectionsManager.getInstance(currentAccount).sendRequest(stories, (response, error) -> AndroidUtilities.runOnUIThread(() -> { loadingAllStories.remove(key); TL_stories.PeerStories userStories2 = profile ? userStories : getStories(dialogId); if (userStories2 == null) { return; } if (response instanceof TL_stories.TL_stories_stories) { TL_stories.TL_stories_stories res = (TL_stories.TL_stories_stories) response; for (int i = 0; i < res.stories.size(); i++) { for (int j = 0; j < userStories2.stories.size(); j++) { if (userStories2.stories.get(j).id == res.stories.get(i).id) { userStories2.stories.set(j, res.stories.get(i)); preloadStory(dialogId, res.stories.get(i)); } } } if (!profile) { storiesStorage.updateStories(userStories2); } } NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesUpdated); })); } } } public void loadNextStories(boolean hidden) { if (hasMore) { loadFromServer(hidden); } } public void fillMessagesWithStories(LongSparseArray<ArrayList<MessageObject>> messagesWithUnknownStories, Runnable callback, int classGuid) { storiesStorage.fillMessagesWithStories(messagesWithUnknownStories, callback, classGuid); } LongSparseArray<TL_stories.StoryItem> resolvedStories = new LongSparseArray<>(); public void resolveStoryLink(long peerId, int storyId, Consumer<TL_stories.StoryItem> consumer) { TL_stories.PeerStories userStoriesLocal = getStories(peerId); if (userStoriesLocal != null) { for (int i = 0; i < userStoriesLocal.stories.size(); i++) { if (userStoriesLocal.stories.get(i).id == storyId && !(userStoriesLocal.stories.get(i) instanceof TL_stories.TL_storyItemSkipped)) { consumer.accept(userStoriesLocal.stories.get(i)); return; } } } long hash = peerId + storyId << 12; TL_stories.StoryItem storyItem = resolvedStories.get(hash); if (storyItem != null) { consumer.accept(storyItem); return; } TL_stories.TL_stories_getStoriesByID stories = new TL_stories.TL_stories_getStoriesByID(); stories.id.add(storyId); stories.peer = MessagesController.getInstance(currentAccount).getInputPeer(peerId); ConnectionsManager.getInstance(currentAccount).sendRequest(stories, new RequestDelegate() { @Override public void run(TLObject res, TLRPC.TL_error error) { AndroidUtilities.runOnUIThread(() -> { TL_stories.StoryItem storyItem = null; if (res != null) { TL_stories.TL_stories_stories response = (TL_stories.TL_stories_stories) res; MessagesController.getInstance(currentAccount).putUsers(response.users, false); MessagesController.getInstance(currentAccount).putChats(response.chats, false); if (response.stories.size() > 0) { storyItem = response.stories.get(0); resolvedStories.put(hash, storyItem); } } consumer.accept(storyItem); }); } }); } public ArrayList<TL_stories.PeerStories> getHiddenList() { return hiddenListStories; } public int getUnreadStoriesCount(long dialogId) { TL_stories.PeerStories userStories = allStoriesMap.get(dialogId); for (int i = 0; i < userStories.stories.size(); i++) { if (userStories.max_read_id < userStories.stories.get(i).id) { return userStories.stories.size() - i; } } return 0; } public int getTotalStoriesCount(boolean hidden) { if (hidden) { return hasMoreHidden ? Math.max(1, totalStoriesCountHidden) : hiddenListStories.size(); } else { return hasMore ? Math.max(1, totalStoriesCount) : dialogListStories.size(); } } public void putStories(long dialogId, TL_stories.PeerStories stories) { putToAllStories(dialogId, stories); if (dialogId > 0) { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(dialogId); if (isContactOrService(user) || user.self) { storiesStorage.putPeerStories(stories); applyToList(stories); } } else { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); if (ChatObject.isInChat(chat)) { storiesStorage.putPeerStories(stories); applyToList(stories); } } } public void setLoading(long dialogId, boolean loading) { if (loading) { loadingDialogsStories.put(dialogId, 1); } else { loadingDialogsStories.delete(dialogId); } } public boolean isLoading(long dialogId) { return loadingDialogsStories.get(dialogId, 0) == 1; } public void removeContact(long dialogId) { for (int i = 0; i < dialogListStories.size(); i++) { if (DialogObject.getPeerDialogId(dialogListStories.get(i).peer) == dialogId) { dialogListStories.remove(i); break; } } for (int i = 0; i < hiddenListStories.size(); i++) { if (DialogObject.getPeerDialogId(hiddenListStories.get(i).peer) == dialogId) { hiddenListStories.remove(i); break; } } storiesStorage.deleteAllUserStories(dialogId); MessagesController.getInstance(currentAccount).checkArchiveFolder(); NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesUpdated); } public StoriesStorage getStoriesStorage() { return storiesStorage; } public boolean hasHiddenStories() { return !hiddenListStories.isEmpty(); } public void checkExpiredStories() { checkExpireStories(dialogListStories); checkExpireStories(hiddenListStories); } private void checkExpireStories(ArrayList<TL_stories.PeerStories> dialogListStories) { boolean notify = false; for (int k = 0; k < dialogListStories.size(); k++) { TL_stories.PeerStories stories = dialogListStories.get(k); long dialogId = DialogObject.getPeerDialogId(stories.peer); for (int i = 0; i < stories.stories.size(); i++) { if (StoriesUtilities.isExpired(currentAccount, stories.stories.get(i))) { stories.stories.remove(i); i--; } } if (stories.stories.isEmpty() && !hasUploadingStories(dialogId)) { allStoriesMap.remove(dialogId); dialogListStories.remove(stories); notify = true; } } if (notify) { NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesUpdated); } } public void checkExpiredStories(long dialogId) { TL_stories.PeerStories userStories = getStories(dialogId); if (userStories == null) { return; } for (int i = 0; i < userStories.stories.size(); i++) { if (StoriesUtilities.isExpired(currentAccount, userStories.stories.get(i))) { userStories.stories.remove(i); i--; } } if (userStories.stories.isEmpty() && !hasUnreadStories(dialogId)) { dialogListStories.remove(userStories); hiddenListStories.remove(userStories); NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesUpdated); } } public boolean hasLoadingStories() { return loadingDialogsStories.size() > 0; } public TL_stories.TL_storiesStealthMode getStealthMode() { return stealthMode; } public void setStealthMode(TL_stories.TL_storiesStealthMode stealthMode) { this.stealthMode = stealthMode; NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.stealthModeChanged); writeStealthMode(stealthMode); } public void setStoryReaction(long dialogId, TL_stories.StoryItem storyItem, ReactionsLayoutInBubble.VisibleReaction visibleReaction) { if (storyItem == null) { return; } TL_stories.TL_stories_sendReaction req = new TL_stories.TL_stories_sendReaction(); req.story_id = storyItem.id; req.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialogId); if (visibleReaction == null) { req.reaction = new TLRPC.TL_reactionEmpty(); // req.flags |= 1; storyItem.flags &= ~32768; storyItem.sent_reaction = null; } else if (visibleReaction.documentId != 0) { TLRPC.TL_reactionCustomEmoji reactionCustomEmoji = new TLRPC.TL_reactionCustomEmoji(); reactionCustomEmoji.document_id = visibleReaction.documentId; req.reaction = reactionCustomEmoji; // req.flags |= 1; storyItem.flags |= 32768; storyItem.sent_reaction = reactionCustomEmoji; } else if (visibleReaction.emojicon != null) { TLRPC.TL_reactionEmoji reactionEmoji = new TLRPC.TL_reactionEmoji(); reactionEmoji.emoticon = visibleReaction.emojicon; req.reaction = reactionEmoji; storyItem.flags |= 32768; storyItem.sent_reaction = reactionEmoji; } updateStoryItem(dialogId, storyItem); ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> { }); } public void updateStoryReaction(long dialogId, int storyId, TLRPC.Reaction reaction) { TL_stories.StoryItem storyItem = findStory(dialogId, storyId); if (storyItem != null) { storyItem.sent_reaction = reaction; if (storyItem.sent_reaction != null) { storyItem.flags |= 32768; } else { storyItem.flags &= ~32768; } updateStoryItem(dialogId, storyItem); } } private TL_stories.StoryItem findStory(long dialogId, int storyId) { TL_stories.PeerStories stories = allStoriesMap.get(dialogId); if (stories != null) { for (int i = 0; i < stories.stories.size(); i++) { if (stories.stories.get(i).id == storyId) { return stories.stories.get(i); } } } return null; } public void onPremiumChanged() { selfViewsModel.clear(); } public void updateStoriesFromFullPeer(long dialogId, TL_stories.PeerStories stories) { if (stories == null) { return; } TL_stories.PeerStories peerStories = allStoriesMap.get(dialogId); if (peerStories == null) { return; } FileLog.d("StoriesController update stories from full peer " + dialogId); // peerStories.stories.clear(); // peerStories.stories.addAll(stories.stories); for (int i = 0; i < peerStories.stories.size(); ++i) { if (peerStories.stories.get(i) instanceof TL_stories.TL_storyItemSkipped) { int storyId = peerStories.stories.get(i).id; for (int j = 0; j < stories.stories.size(); ++j) { if (stories.stories.get(j).id == storyId && stories.stories.get(j) instanceof TL_stories.TL_storyItem) { peerStories.stories.set(i, stories.stories.get(j)); break; } } } } } public class UploadingStory implements NotificationCenter.NotificationCenterDelegate { public final long random_id; public final boolean edit; final StoryEntry entry; private boolean entryDestroyed; String path; String firstFramePath; float progress; float convertingProgress, uploadProgress; boolean ready; boolean isVideo; boolean canceled; private int currentRequest; private long firstSecondSize = -1; private long duration; private MessageObject messageObject; private VideoEditedInfo info; private boolean putMessages; private boolean isCloseFriends; public boolean hadFailed; public boolean failed; long dialogId; public UploadingStory(StoryEntry entry) { this.entry = entry; random_id = Utilities.random.nextLong(); edit = entry.isEdit; if (entry.uploadThumbFile != null) { this.firstFramePath = entry.uploadThumbFile.getAbsolutePath(); } failed = hadFailed = entry.isError; if (entry.isEdit) { dialogId = entry.editStoryPeerId; } else { if (entry.peer == null || entry.peer instanceof TLRPC.TL_inputPeerSelf) { dialogId = UserConfig.getInstance(currentAccount).clientUserId; } else { dialogId = DialogObject.getPeerDialogId(entry.peer); } } } private void startForeground() { Intent intent = new Intent(ApplicationLoader.applicationContext, StoryUploadingService.class); intent.putExtra("path", path); intent.putExtra("currentAccount", currentAccount); try { ApplicationLoader.applicationContext.startService(intent); } catch (Throwable e) { FileLog.e(e); } } public void start() { if ((entry.isEdit || entry.isRepost && entry.repostMedia != null) && (!entry.editedMedia && entry.round == null)) { sendUploadedRequest(null); return; } isCloseFriends = entry.privacy != null && entry.privacy.isCloseFriends(); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.fileUploaded); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.fileUploadFailed); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.fileUploadProgressChanged); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.filePreparingFailed); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.filePreparingStarted); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.fileNewChunkAvailable); if (isVideo = entry.wouldBeVideo()) { TLRPC.TL_message message = new TLRPC.TL_message(); message.id = 1; path = message.attachPath = StoryEntry.makeCacheFile(currentAccount, true).getAbsolutePath(); messageObject = new MessageObject(currentAccount, message, (MessageObject) null, false, false); entry.getVideoEditedInfo(info -> { this.info = info; messageObject.videoEditedInfo = info; duration = info.estimatedDuration / 1000L; if (messageObject.videoEditedInfo.needConvert()) { MediaController.getInstance().scheduleVideoConvert(messageObject, false, false); } else { boolean rename = new File(messageObject.videoEditedInfo.originalPath).renameTo(new File(path)); if (rename) { FileLoader.getInstance(currentAccount).uploadFile(path, false, false, ConnectionsManager.FileTypeVideo); } } }); } else { final File destFile = StoryEntry.makeCacheFile(currentAccount, false); path = destFile.getAbsolutePath(); Utilities.themeQueue.postRunnable(() -> { entry.buildPhoto(destFile); AndroidUtilities.runOnUIThread(() -> { ready = true; upload(); }); }); } startForeground(); } public void tryAgain() { failed = false; entryDestroyed = false; progress = 0; uploadProgress = 0; convertingProgress = 0; if (path != null) { try { new File(path).delete(); path = null; } catch (Exception ignore) {} } start(); } private void upload() { if (entry.shareUserIds != null) { putMessages(); } else { FileLoader.getInstance(currentAccount).uploadFile(path, false, !entry.isVideo, isVideo ? Math.max(1, (int) (info != null ? info.estimatedSize : 0)) : 0, entry.isVideo ? ConnectionsManager.FileTypeVideo : ConnectionsManager.FileTypePhoto, true); } } public void cleanup() { NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileUploaded); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileUploadFailed); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileUploadProgressChanged); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.filePreparingFailed); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.filePreparingStarted); NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.fileNewChunkAvailable); if (!failed) { ArrayList<UploadingStory> list = uploadingStoriesByDialogId.get(dialogId); if (list != null) { list.remove(UploadingStory.this); } } ArrayList<UploadingStory> list = uploadingAndEditingStories.get(dialogId); if (list != null) { list.remove(UploadingStory.this); } if (edit) { HashMap<Integer, UploadingStory> map = editingStories.get(dialogId); if (map != null) { map.remove(entry.editStoryId); } } NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesUpdated); if (entry != null && !entry.isEditSaved && !entryDestroyed) { entry.destroy(false); entryDestroyed = true; } NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.uploadStoryEnd, path); } @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.filePreparingStarted) { if (args[0] == messageObject) { this.path = (String) args[1]; upload(); } } else if (id == NotificationCenter.fileNewChunkAvailable) { if (args[0] == messageObject) { String finalPath = (String) args[1]; long availableSize = (Long) args[2]; long finalSize = (Long) args[3]; convertingProgress = (float) args[4]; progress = convertingProgress * .3f + uploadProgress * .7f; NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.uploadStoryProgress, path, progress); if (firstSecondSize < 0 && convertingProgress * duration >= 1000) { firstSecondSize = availableSize; } FileLoader.getInstance(currentAccount).checkUploadNewDataAvailable(finalPath, false, Math.max(1, availableSize), finalSize, convertingProgress); if (finalSize > 0) { if (firstSecondSize < 0) { firstSecondSize = finalSize; } ready = true; } } } else if (id == NotificationCenter.filePreparingFailed) { if (args[0] == messageObject) { if (!edit) { entry.isError = true; entry.error = new TLRPC.TL_error(); entry.error.code = 400; entry.error.text = "FILE_PREPARE_FAILED"; entryDestroyed = true; hadFailed = failed = true; getDraftsController().edit(entry); } cleanup(); } } else if (id == NotificationCenter.fileUploaded) { String location = (String) args[0]; if (path != null && location.equals(path)) { TLRPC.InputFile uploadedFile = (TLRPC.InputFile) args[1]; sendUploadedRequest(uploadedFile); } } else if (id == NotificationCenter.fileUploadFailed) { String location = (String) args[0]; if (path != null && location.equals(path)) { NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.showBulletin, Bulletin.TYPE_ERROR, LocaleController.getString("StoryUploadError", R.string.StoryUploadError)); cleanup(); } } else if (id == NotificationCenter.fileUploadProgressChanged) { String location = (String) args[0]; if (location.equals(path)) { Long loadedSize = (Long) args[1]; Long totalSize = (Long) args[2]; uploadProgress = Math.min(1f, loadedSize / (float) totalSize); progress = convertingProgress * .3f + uploadProgress * .7f; NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.uploadStoryProgress, path, progress); } } } private void sendUploadedRequest(TLRPC.InputFile uploadedFile) { if (canceled) { return; } if (entry.shareUserIds != null) { return; } boolean sendingSameInput = false; TLRPC.InputMedia media = null; if (entry.isRepost && !entry.editedMedia && entry.repostMedia != null) { if (entry.repostMedia instanceof TLRPC.TL_messageMediaDocument) { TLRPC.TL_inputMediaDocument inputMedia = new TLRPC.TL_inputMediaDocument(); TLRPC.TL_inputDocument inputDocument = new TLRPC.TL_inputDocument(); inputDocument.id = entry.repostMedia.document.id; inputDocument.access_hash = entry.repostMedia.document.access_hash; inputDocument.file_reference = entry.repostMedia.document.file_reference; inputMedia.id = inputDocument; inputMedia.spoiler = entry.repostMedia.spoiler; media = inputMedia; sendingSameInput = true; } else if (entry.repostMedia instanceof TLRPC.TL_messageMediaPhoto) { TLRPC.TL_inputMediaPhoto inputMedia = new TLRPC.TL_inputMediaPhoto(); TLRPC.TL_inputPhoto inputPhoto = new TLRPC.TL_inputPhoto(); inputPhoto.id = entry.repostMedia.photo.id; inputPhoto.access_hash = entry.repostMedia.photo.access_hash; inputPhoto.file_reference = entry.repostMedia.photo.file_reference; inputMedia.id = inputPhoto; media = inputMedia; sendingSameInput = true; } } if (media == null && uploadedFile != null) { if (entry.wouldBeVideo()) { TLRPC.TL_inputMediaUploadedDocument inputMediaVideo = new TLRPC.TL_inputMediaUploadedDocument(); inputMediaVideo.file = uploadedFile; TLRPC.TL_documentAttributeVideo attributeVideo = new TLRPC.TL_documentAttributeVideo(); SendMessagesHelper.fillVideoAttribute(path, attributeVideo, null); attributeVideo.supports_streaming = true; attributeVideo.flags |= 4; attributeVideo.preload_prefix_size = (int) firstSecondSize; inputMediaVideo.attributes.add(attributeVideo); if (entry.stickers != null && (!entry.stickers.isEmpty() || entry.editStickers != null && !entry.editStickers.isEmpty())) { inputMediaVideo.flags |= 1; inputMediaVideo.stickers = new ArrayList<>(entry.stickers); if (entry.editStickers != null) { inputMediaVideo.stickers.addAll(entry.editStickers); } inputMediaVideo.attributes.add(new TLRPC.TL_documentAttributeHasStickers()); } media = inputMediaVideo; media.nosound_video = entry.audioPath == null && (entry.muted || !entry.isVideo); media.mime_type = "video/mp4"; } else { TLRPC.TL_inputMediaUploadedPhoto inputMediaPhoto = new TLRPC.TL_inputMediaUploadedPhoto(); inputMediaPhoto.file = uploadedFile; media = inputMediaPhoto; MimeTypeMap myMime = MimeTypeMap.getSingleton(); String ext = "txt"; int idx = path.lastIndexOf('.'); if (idx != -1) { ext = path.substring(idx + 1).toLowerCase(); } String mimeType = myMime.getMimeTypeFromExtension(ext); media.mime_type = mimeType; if (entry.stickers != null && (!entry.stickers.isEmpty() || entry.editStickers != null && !entry.editStickers.isEmpty())) { inputMediaPhoto.flags |= 1; if (entry.editStickers != null) { inputMediaPhoto.stickers.addAll(entry.editStickers); } inputMediaPhoto.stickers = new ArrayList<>(entry.stickers); } } } TLObject req; final int captionLimit = UserConfig.getInstance(currentAccount).isPremium() ? MessagesController.getInstance(currentAccount).storyCaptionLengthLimitPremium : MessagesController.getInstance(currentAccount).storyCaptionLengthLimitDefault; if (edit) { TL_stories.TL_stories_editStory editStory = new TL_stories.TL_stories_editStory(); editStory.id = entry.editStoryId; editStory.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialogId); if (media != null && entry.editedMedia) { editStory.flags |= 1; editStory.media = media; } if (entry.editedCaption && entry.caption != null) { editStory.flags |= 2; CharSequence[] caption = new CharSequence[]{ entry.caption }; if (caption[0].length() > captionLimit) { caption[0] = caption[0].subSequence(0, captionLimit); } if (MessagesController.getInstance(currentAccount).storyEntitiesAllowed()) { editStory.entities = MediaDataController.getInstance(currentAccount).getEntities(caption, true); } else { editStory.entities.clear(); } if (caption[0].length() > captionLimit) { caption[0] = caption[0].subSequence(0, captionLimit); } editStory.caption = caption[0].toString(); } if (entry.editedPrivacy) { editStory.flags |= 4; editStory.privacy_rules.addAll(entry.privacyRules); } if (entry.editedMediaAreas != null) { editStory.media_areas.addAll(entry.editedMediaAreas); } if (entry.mediaEntities != null) { for (int i = 0; i < entry.mediaEntities.size(); ++i) { VideoEditedInfo.MediaEntity mediaEntity = entry.mediaEntities.get(i); if (mediaEntity.mediaArea != null) { editStory.media_areas.add(mediaEntity.mediaArea); } } } if (!editStory.media_areas.isEmpty()) { editStory.flags |= 8; } req = editStory; } else { TL_stories.TL_stories_sendStory sendStory = new TL_stories.TL_stories_sendStory(); sendStory.random_id = random_id; sendStory.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialogId); sendStory.media = media; sendStory.privacy_rules.addAll(entry.privacyRules); sendStory.pinned = entry.pinned; sendStory.noforwards = !entry.allowScreenshots; if (entry.caption != null) { sendStory.flags |= 3; CharSequence[] caption = new CharSequence[]{ entry.caption }; if (caption[0].length() > captionLimit) { caption[0] = caption[0].subSequence(0, captionLimit); } if (MessagesController.getInstance(currentAccount).storyEntitiesAllowed()) { sendStory.entities = MediaDataController.getInstance(currentAccount).getEntities(caption, true); } else { sendStory.entities.clear(); } if (caption[0].length() > captionLimit) { caption[0] = caption[0].subSequence(0, captionLimit); } sendStory.caption = caption[0].toString(); } if (entry.isRepost) { sendStory.flags |= 64; sendStory.fwd_from_id = MessagesController.getInstance(currentAccount).getInputPeer(entry.repostPeer); sendStory.fwd_from_story = entry.repostStoryId; sendStory.fwd_modified = !sendingSameInput; } if (entry.period == Integer.MAX_VALUE) { sendStory.pinned = true; } else { sendStory.flags |= 8; sendStory.period = entry.period; } if (entry.mediaEntities != null) { for (int i = 0; i < entry.mediaEntities.size(); ++i) { VideoEditedInfo.MediaEntity mediaEntity = entry.mediaEntities.get(i); if (mediaEntity.mediaArea != null) { sendStory.media_areas.add(mediaEntity.mediaArea); } } if (!sendStory.media_areas.isEmpty()) { sendStory.flags |= 32; } } req = sendStory; } final RequestDelegate requestDelegate = (response, error) -> { if (response != null) { failed = false; TLRPC.Updates updates = (TLRPC.Updates) response; int storyId = 0; TL_stories.StoryItem storyItem = null; for (int i = 0; i < updates.updates.size(); i++) { if (updates.updates.get(i) instanceof TL_stories.TL_updateStory) { TL_stories.TL_updateStory updateStory = (TL_stories.TL_updateStory) updates.updates.get(i); updateStory.story.attachPath = path; updateStory.story.firstFramePath = firstFramePath; updateStory.story.justUploaded = !edit; storyId = updateStory.story.id; if (storyItem == null) { storyItem = updateStory.story; } else { storyItem.media = updateStory.story.media; } } if (updates.updates.get(i) instanceof TLRPC.TL_updateStoryID) { TLRPC.TL_updateStoryID updateStory = (TLRPC.TL_updateStoryID) updates.updates.get(i); if (storyItem == null) { storyItem = new TL_stories.TL_storyItem(); storyItem.date = ConnectionsManager.getInstance(currentAccount).getCurrentTime(); storyItem.expire_date = storyItem.date + (entry.period == Integer.MAX_VALUE ? 86400 : entry.period); storyItem.parsedPrivacy = null; storyItem.privacy = StoryPrivacyBottomSheet.StoryPrivacy.toOutput(entry.privacyRules); storyItem.pinned = entry.period == Integer.MAX_VALUE; storyItem.dialogId = UserConfig.getInstance(currentAccount).clientUserId; storyItem.attachPath = path; storyItem.firstFramePath = firstFramePath; storyItem.id = updateStory.id; storyItem.justUploaded = !edit; } } } final long did = dialogId; if (canceled) { TL_stories.TL_stories_deleteStories stories_deleteStory = new TL_stories.TL_stories_deleteStories(); stories_deleteStory.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialogId); if (stories_deleteStory.peer != null) { stories_deleteStory.id.add(storyId); ConnectionsManager.getInstance(currentAccount).sendRequest(stories_deleteStory, (response1, error1) -> { AndroidUtilities.runOnUIThread(StoriesController.this::invalidateStoryLimit); }); } } else { if ((storyId == 0 || edit) && storyItem != null) { TL_stories.TL_updateStory tl_updateStory = new TL_stories.TL_updateStory(); tl_updateStory.peer = MessagesController.getInstance(currentAccount).getPeer(did); tl_updateStory.story = storyItem; AndroidUtilities.runOnUIThread(() -> { MessagesController.getInstance(currentAccount).getStoriesController().processUpdate(tl_updateStory); }); } final TL_stories.StoryItem storyItemFinal = storyItem; if (storyItemFinal.media != null && storyItemFinal.attachPath != null) { if (storyItemFinal.media.document != null) { FileLoader.getInstance(currentAccount).setLocalPathTo(storyItemFinal.media.document, storyItemFinal.attachPath); } else if (storyItemFinal.media.photo != null) { TLRPC.Photo photo = storyItemFinal.media.photo; TLRPC.PhotoSize size = FileLoader.getClosestPhotoSizeWithSize(photo.sizes, Integer.MAX_VALUE); FileLoader.getInstance(currentAccount).setLocalPathTo(size, storyItemFinal.attachPath); } } AndroidUtilities.runOnUIThread(() -> { entryDestroyed = true; if (entry.isError) { getDraftsController().delete(entry); } entry.isError = false; entry.error = null; getDraftsController().saveForEdit(entry, did, storyItemFinal); if (!edit) { invalidateStoryLimit(); } }); MessagesController.getInstance(currentAccount).processUpdateArray(updates.updates, updates.users, updates.chats, false, updates.date); } } else if (error != null && !edit) { AndroidUtilities.runOnUIThread(() -> { entry.isError = true; if (checkStoryError(error)) { entry.error = null; } else { entry.error = error; } entryDestroyed = true; hadFailed = failed = true; getDraftsController().edit(entry); }); } AndroidUtilities.runOnUIThread(this::cleanup); }; if (BuildVars.DEBUG_PRIVATE_VERSION && !edit && entry.caption != null && entry.caption.toString().contains("#failtest") && !hadFailed) { TLRPC.TL_error error = new TLRPC.TL_error(); error.code = 400; error.text = "FORCED_TO_FAIL"; requestDelegate.run(null, error); } else { currentRequest = ConnectionsManager.getInstance(currentAccount).sendRequest(req, requestDelegate); } } private void putMessages() { if (entry.shareUserIds == null || putMessages) { return; } final int count = entry.shareUserIds.size(); String caption = entry.caption == null ? null : entry.caption.toString(); ArrayList<TLRPC.MessageEntity> captionEntities = entry.caption == null ? null : MediaDataController.getInstance(currentAccount).getEntities(new CharSequence[]{entry.caption}, true); for (int i = 0; i < count; ++i) { long userId = entry.shareUserIds.get(i); if (entry.wouldBeVideo()) { SendMessagesHelper.prepareSendingVideo(AccountInstance.getInstance(currentAccount), path, null, userId, null, null, null, null, captionEntities, 0, null, !entry.silent, entry.scheduleDate, false, false, caption, null, 0); } else { SendMessagesHelper.prepareSendingPhoto(AccountInstance.getInstance(currentAccount), path, null, null, userId, null, null, null, null, captionEntities, null, null, 0, null, null, !entry.silent, entry.scheduleDate, 0, false, caption, null, 0); } } putMessages = true; } public void cancel() { if (failed) { getDraftsController().delete(entry); uploadingStoriesByDialogId.get(dialogId).remove(UploadingStory.this); } canceled = true; if (entry.wouldBeVideo()) { MediaController.getInstance().cancelVideoConvert(messageObject); } FileLoader.getInstance(currentAccount).cancelFileUpload(path, false); if (currentRequest >= 0) { ConnectionsManager.getInstance(currentAccount).cancelRequest(currentRequest, true); } cleanup(); } public boolean isCloseFriends() { return isCloseFriends; } } private final HashMap<Long, StoriesList>[] storiesLists = new HashMap[3]; @Nullable public StoriesList getStoriesList(long dialogId, int type) { return getStoriesList(dialogId, type, true); } @Nullable private StoriesList getStoriesList(long dialogId, int type, boolean createIfNotExist) { if (storiesLists[type] == null) { storiesLists[type] = new HashMap<>(); } StoriesList list = storiesLists[type].get(dialogId); if (list == null && createIfNotExist) { storiesLists[type].put(dialogId, list = new StoriesList(currentAccount, dialogId, type, this::destroyStoryList)); } return list; } private static String storyItemIds(List<TL_stories.StoryItem> storyItems) { try { if (storyItems == null) { return "null"; } String s = ""; for (int i = 0; i < storyItems.size(); ++i) { if (i > 0) s += ", "; s += storyItems.get(i).id + "@" + storyItems.get(i).dialogId; } return s; } catch (Exception e) { return "err"; } } private static String storyItemMessageIds(List<MessageObject> storyItems) { try { if (storyItems == null) { return "null"; } String s = ""; for (int i = 0; i < storyItems.size(); ++i) { if (i > 0) s += ", "; TL_stories.StoryItem storyItem = storyItems.get(i).storyItem; if (storyItem == null) { s += "null"; } else s += storyItem.id + "@" + storyItem.dialogId; } return s; } catch (Exception e) { return "err"; } } public void updateStoriesInLists(long dialogId, List<TL_stories.StoryItem> storyItems) { FileLog.d("updateStoriesInLists " + dialogId + " storyItems[" + storyItems.size() + "] {" + storyItemIds(storyItems) + "}"); StoriesList pinned = getStoriesList(dialogId, StoriesList.TYPE_PINNED, false); StoriesList archived = getStoriesList(dialogId, StoriesList.TYPE_ARCHIVE, false); if (pinned != null) { pinned.updateStories(storyItems); } if (archived != null) { archived.updateStories(storyItems); } } public void updateDeletedStoriesInLists(long dialogId, List<TL_stories.StoryItem> storyItems) { FileLog.d("updateDeletedStoriesInLists " + dialogId + " storyItems[" + storyItems.size() + "] {" + storyItemIds(storyItems) + "}"); StoriesList pinned = getStoriesList(dialogId, StoriesList.TYPE_PINNED, false); StoriesList archived = getStoriesList(dialogId, StoriesList.TYPE_ARCHIVE, false); if (pinned != null) { pinned.updateDeletedStories(storyItems); } if (archived != null) { archived.updateDeletedStories(storyItems); } } public void destroyStoryList(StoriesList list) { if (storiesLists[list.type] != null) { storiesLists[list.type].remove(list.dialogId); } } public static class StoriesList { private static HashMap<Integer, Long> lastLoadTime; private int maxLinkId = 0; private final ArrayList<Integer> links = new ArrayList<>(); public int link() { final int id = maxLinkId++; links.add(id); AndroidUtilities.cancelRunOnUIThread(destroyRunnable); return id; } public void unlink(int id) { links.remove((Integer) id); if (links.isEmpty()) { AndroidUtilities.cancelRunOnUIThread(destroyRunnable); AndroidUtilities.runOnUIThread(destroyRunnable, 1000 * 60 * 5); } } public static final int TYPE_PINNED = 0; public static final int TYPE_ARCHIVE = 1; public static final int TYPE_STATISTICS = 2; public final int currentAccount; public final long dialogId; public final int type; public final ArrayList<Integer> pinnedIds = new ArrayList<>(); public final HashMap<Long, TreeSet<Integer>> groupedByDay = new HashMap<>(); public final ArrayList<MessageObject> messageObjects = new ArrayList<>(); private final HashMap<Integer, MessageObject> messageObjectsMap = new HashMap<>(); private final SortedSet<Integer> cachedObjects = new TreeSet<>(Comparator.reverseOrder()); private final SortedSet<Integer> loadedObjects = new TreeSet<>(Comparator.reverseOrder()); public final HashSet<Integer> seenStories = new HashSet<>(); private boolean showPhotos = true; private boolean showVideos = true; public void updateFilters(boolean photos, boolean videos) { this.showPhotos = photos; this.showVideos = videos; this.fill(true); } public boolean isOnlyCache() { return loadedObjects.isEmpty() && canLoad(); } public boolean showPhotos() { return showPhotos; } public boolean showVideos() { return showVideos; } private final ArrayList<MessageObject> tempArr = new ArrayList<>(); private final Runnable notify = () -> { NotificationCenter.getInstance(StoriesList.this.currentAccount).postNotificationName(NotificationCenter.storiesListUpdated, StoriesList.this); }; public void fill(boolean notify) { fill(this.messageObjects, showPhotos, showVideos); if (notify) { AndroidUtilities.cancelRunOnUIThread(this.notify); AndroidUtilities.runOnUIThread(this.notify); } } private void fill(ArrayList<MessageObject> arrayList, boolean showPhotos, boolean showVideos) { tempArr.clear(); if (type == TYPE_PINNED) { for (int id : pinnedIds) { MessageObject msg = messageObjectsMap.get(id); if (filter(msg, showPhotos, showVideos)) { tempArr.add(msg); } } } int minId = Integer.MAX_VALUE; for (int id : loadedObjects) { MessageObject msg = messageObjectsMap.get(id); if (type == TYPE_PINNED && pinnedIds.contains(id)) continue; if (filter(msg, showPhotos, showVideos)) { tempArr.add(msg); } if (id < minId) { minId = id; } } if (!done) { Iterator<Integer> i = cachedObjects.iterator(); while (i.hasNext() && (totalCount == -1 || tempArr.size() < totalCount)) { int id = i.next(); if (type == TYPE_PINNED && pinnedIds.contains(id)) continue; if (minId == Integer.MAX_VALUE || id < minId) { MessageObject msg = messageObjectsMap.get(id); if (filter(msg, showPhotos, showVideos)) { tempArr.add(msg); } } } } arrayList.clear(); arrayList.addAll(tempArr); } private boolean filter(MessageObject msg, boolean photos, boolean videos) { return msg != null && msg.isStory() && (photos && msg.isPhoto() || videos && msg.isVideo() || msg.storyItem.media instanceof TLRPC.TL_messageMediaUnsupported); } private boolean done; private int totalCount = -1; private boolean preloading, loading; private boolean invalidateAfterPreload; private boolean error; private Runnable destroyRunnable; private Utilities.CallbackReturn<Integer, Boolean> toLoad; private StoriesList(int currentAccount, long dialogId, int type, Utilities.Callback<StoriesList> destroy) { this.currentAccount = currentAccount; this.dialogId = dialogId; this.type = type; this.destroyRunnable = () -> destroy.run(this); preloadCache(); } private void preloadCache() { if (preloading || loading || error) { return; } preloading = true; final MessagesStorage storage = MessagesStorage.getInstance(currentAccount); storage.getStorageQueue().postRunnable(() -> { SQLiteCursor cursor = null; ArrayList<Integer> pins = new ArrayList<>(); HashSet<Integer> seen = new HashSet<>(); HashSet<Long> loadUserIds = new HashSet<>(); HashSet<Long> loadChatIds = new HashSet<>(); ArrayList<MessageObject> cacheResult = new ArrayList<>(); final ArrayList<TLRPC.User> loadedUsers = new ArrayList<>(); final ArrayList<TLRPC.Chat> loadedChats = new ArrayList<>(); try { SQLiteDatabase database = storage.getDatabase(); cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, seen, pin FROM profile_stories WHERE dialog_id = %d AND type = %d ORDER BY story_id DESC", dialogId, type)); while (cursor.next()) { NativeByteBuffer data = cursor.byteBufferValue(0); if (data != null) { TL_stories.StoryItem storyItem = TL_stories.StoryItem.TLdeserialize(data, data.readInt32(true), true); storyItem.dialogId = dialogId; storyItem.messageId = storyItem.id; MessageObject msg = new MessageObject(currentAccount, storyItem); for (TLRPC.PrivacyRule rule : storyItem.privacy) { if (rule instanceof TLRPC.TL_privacyValueDisallowUsers) { loadUserIds.addAll(((TLRPC.TL_privacyValueDisallowUsers) rule).users); } else if (rule instanceof TLRPC.TL_privacyValueAllowUsers) { loadUserIds.addAll(((TLRPC.TL_privacyValueAllowUsers) rule).users); } } if (storyItem.fwd_from != null && storyItem.fwd_from.from != null) { long did = DialogObject.getPeerDialogId(storyItem.fwd_from.from); if (did >= 0) { loadUserIds.add(did); } else { loadChatIds.add(-did); } } for (int j = 0; j < storyItem.media_areas.size(); ++j) { if (storyItem.media_areas.get(j) instanceof TL_stories.TL_mediaAreaChannelPost) { long channel_id = ((TL_stories.TL_mediaAreaChannelPost) storyItem.media_areas.get(j)).channel_id; loadChatIds.add(channel_id); } } if (storyItem.from_id != null) { long did = DialogObject.getPeerDialogId(storyItem.from_id); if (did >= 0) { loadUserIds.add(did); } else { loadChatIds.add(-did); } } msg.generateThumbs(false); cacheResult.add(msg); data.reuse(); if (cursor.intValue(1) == 1) { seen.add(storyItem.id); } int pinIndex = cursor.intValue(2); if (pinIndex > 0) { pins.add(Utilities.clamp(pinIndex, pins.size() - 1, 0), storyItem.id); } } } cursor.dispose(); if (!loadUserIds.isEmpty()) { storage.getUsersInternal(TextUtils.join(",", loadUserIds), loadedUsers); } if (!loadChatIds.isEmpty()) { storage.getChatsInternal(TextUtils.join(",", loadChatIds), loadedChats); } } catch (Throwable e) { storage.checkSQLException(e); } finally { if (cursor != null) { cursor.dispose(); cursor = null; } } AndroidUtilities.runOnUIThread(() -> { FileLog.d("StoriesList "+type+"{"+ dialogId +"} preloadCache {" + storyItemMessageIds(cacheResult) + "}"); pinnedIds.clear(); pinnedIds.addAll(pins); preloading = false; MessagesController.getInstance(currentAccount).putUsers(loadedUsers, true); MessagesController.getInstance(currentAccount).putChats(loadedChats, true); if (invalidateAfterPreload) { invalidateAfterPreload = false; toLoad = null; invalidateCache(); return; } seenStories.addAll(seen); cachedObjects.clear(); for (int i = 0; i < cacheResult.size(); ++i) { pushObject(cacheResult.get(i), true); } fill(false); if (toLoad != null) { toLoad.run(0); toLoad = null; } NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesListUpdated, StoriesList.this); }); }); } private void pushObject(MessageObject messageObject, boolean cachedOrLoaded) { if (messageObject == null) { return; } messageObjectsMap.put(messageObject.getId(), messageObject); (cachedOrLoaded ? cachedObjects : loadedObjects).add(messageObject.getId()); long id = day(messageObject); TreeSet<Integer> group = groupedByDay.get(id); if (group == null) { groupedByDay.put(id, group = new TreeSet<>(Comparator.reverseOrder())); } group.add(messageObject.getId()); } private boolean removeObject(int storyId, boolean removeFromCache) { MessageObject messageObject = messageObjectsMap.remove(storyId); if (removeFromCache) { cachedObjects.remove(storyId); } loadedObjects.remove(storyId); pinnedIds.remove((Object) storyId); if (messageObject != null) { long id = day(messageObject); Collection<Integer> group = groupedByDay.get(id); if (group != null) { group.remove(storyId); if (group.isEmpty()) { groupedByDay.remove(id); } } return true; } return false; } public static long day(MessageObject messageObject) { if (messageObject == null) { return 0; } final long date = messageObject.messageOwner.date; Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(date * 1000L); final int year = calendar.get(Calendar.YEAR); final int month = calendar.get(Calendar.MONTH); final int day = calendar.get(Calendar.DAY_OF_MONTH); return year * 10000L + month * 100L + day; } public ArrayList<ArrayList<Integer>> getDays() { final ArrayList<Long> keys = new ArrayList<>(groupedByDay.keySet()); Collections.sort(keys, (a, b) -> (int) (b - a)); final ArrayList<ArrayList<Integer>> days = new ArrayList<>(); if (type == TYPE_PINNED && !pinnedIds.isEmpty()) { days.add(new ArrayList<>(pinnedIds)); } for (Long key : keys) { TreeSet<Integer> storyIds = groupedByDay.get(key); if (storyIds != null) { ArrayList<Integer> ids = new ArrayList<>(storyIds); if (type == TYPE_PINNED && !pinnedIds.isEmpty()) { for (int id : pinnedIds) { ids.remove((Object) id); } } if (!ids.isEmpty()) { days.add(ids); } } } return days; } public void invalidateCache() { if (preloading) { invalidateAfterPreload = true; return; } resetCanLoad(); final MessagesStorage storage = MessagesStorage.getInstance(currentAccount); storage.getStorageQueue().postRunnable(() -> { try { SQLiteDatabase database = storage.getDatabase(); database.executeFast(String.format(Locale.US, "DELETE FROM profile_stories WHERE dialog_id = %d AND type = %d", dialogId, type)).stepThis().dispose(); } catch (Throwable e) { storage.checkSQLException(e); } AndroidUtilities.runOnUIThread(() -> { cachedObjects.clear(); fill(true); }); }); } private boolean saving; private void saveCache() { if (saving) { return; } saving = true; final ArrayList<MessageObject> toSave = new ArrayList<>(); final ArrayList<Integer> pinnedIds = new ArrayList<>(this.pinnedIds); fill(toSave, true, true); final MessagesStorage storage = MessagesStorage.getInstance(currentAccount); storage.getStorageQueue().postRunnable(() -> { SQLitePreparedStatement state = null; FileLog.d("StoriesList " + type + "{"+ dialogId +"} saveCache {" + storyItemMessageIds(toSave) + "}"); try { SQLiteDatabase database = storage.getDatabase(); database.executeFast(String.format(Locale.US, "DELETE FROM profile_stories WHERE dialog_id = %d AND type = %d", dialogId, type)).stepThis().dispose(); state = database.executeFast("REPLACE INTO profile_stories VALUES(?, ?, ?, ?, ?, ?)"); for (int i = 0; i < toSave.size(); ++i) { MessageObject messageObject = toSave.get(i); TL_stories.StoryItem storyItem = messageObject.storyItem; if (storyItem == null) { continue; } NativeByteBuffer data = new NativeByteBuffer(storyItem.getObjectSize()); storyItem.serializeToStream(data); state.requery(); state.bindLong(1, dialogId); state.bindInteger(2, storyItem.id); state.bindByteBuffer(3, data); state.bindInteger(4, type); state.bindInteger(5, seenStories.contains(storyItem.id) ? 1 : 0); state.bindInteger(6, 1 + pinnedIds.indexOf(storyItem.id)); state.step(); data.reuse(); } } catch (Throwable e) { storage.checkSQLException(e); } finally { if (state != null) { state.dispose(); state = null; } } AndroidUtilities.runOnUIThread(() -> { saving = false; }); }); } public boolean markAsRead(int storyId) { if (seenStories.contains(storyId)) return false; seenStories.add(storyId); saveCache(); TL_stories.TL_stories_incrementStoryViews req = new TL_stories.TL_stories_incrementStoryViews(); req.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialogId); req.id.add(storyId); ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> {}); NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesReadUpdated); return true; } private boolean canLoad() { if (lastLoadTime == null) { return true; } final int key = Objects.hash(currentAccount, type, dialogId); Long time = lastLoadTime.get(key); if (time == null) { return true; } return System.currentTimeMillis() - time > 1000L * 60 * 2; } private void resetCanLoad() { if (lastLoadTime != null) { lastLoadTime.remove(Objects.hash(currentAccount, type, dialogId)); } } public boolean load(boolean force, final int count) { return load(force, count, Collections.emptyList()); } public boolean load(List<Integer> ids) { boolean force = false; for (Integer id : ids) { if (!messageObjectsMap.containsKey(id)) { force = true; break; } } return load(force, 0, ids); } public boolean load(boolean force, final int count, List<Integer> ids) { if (loading || (done || error || !canLoad()) && !force) { return false; } if (preloading) { toLoad = i -> load(force, count, ids); return false; } final int offset_id; TLObject request; if (type == TYPE_PINNED) { TL_stories.TL_stories_getPinnedStories req = new TL_stories.TL_stories_getPinnedStories(); req.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialogId); if (!loadedObjects.isEmpty()) { req.offset_id = offset_id = loadedObjects.last(); } else { offset_id = -1; } req.limit = count; request = req; } else if (type == TYPE_STATISTICS) { TL_stories.TL_stories_getStoriesByID req = new TL_stories.TL_stories_getStoriesByID(); req.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialogId); req.id.addAll(ids); request = req; offset_id = -1; } else { TL_stories.TL_stories_getStoriesArchive req = new TL_stories.TL_stories_getStoriesArchive(); req.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialogId); if (!loadedObjects.isEmpty()) { req.offset_id = offset_id = loadedObjects.last(); } else { offset_id = -1; } req.limit = count; request = req; } FileLog.d("StoriesList " + type + "{"+ dialogId +"} load"); loading = true; ConnectionsManager.getInstance(currentAccount).sendRequest(request, (response, err) -> { if (response instanceof TL_stories.TL_stories_stories) { ArrayList<MessageObject> newMessageObjects = new ArrayList<>(); TL_stories.TL_stories_stories stories = (TL_stories.TL_stories_stories) response; for (int i = 0; i < stories.stories.size(); ++i) { TL_stories.StoryItem storyItem = stories.stories.get(i); newMessageObjects.add(toMessageObject(storyItem, stories)); } AndroidUtilities.runOnUIThread(() -> { FileLog.d("StoriesList " + type + "{"+ dialogId +"} loaded {" + storyItemMessageIds(newMessageObjects) + "}"); pinnedIds.clear(); pinnedIds.addAll(stories.pinned_to_top); MessagesController.getInstance(currentAccount).putUsers(stories.users, false); MessagesController.getInstance(currentAccount).putChats(stories.chats, false); MessagesStorage.getInstance(currentAccount).putUsersAndChats(stories.users, stories.chats, true, true); loading = false; totalCount = stories.count; for (int i = 0; i < newMessageObjects.size(); ++i) { pushObject(newMessageObjects.get(i), false); } done = loadedObjects.size() >= totalCount; if (!done) { final int loadedFromId = offset_id == -1 ? loadedObjects.first() : offset_id; final int loadedToId = !loadedObjects.isEmpty() ? loadedObjects.last() : 0; Iterator<Integer> i = cachedObjects.iterator(); while (i.hasNext()) { int cachedId = i.next(); if (!loadedObjects.contains(cachedId) && cachedId >= loadedFromId && cachedId <= loadedToId) { i.remove(); removeObject(cachedId, false); } } } else { Iterator<Integer> i = cachedObjects.iterator(); while (i.hasNext()) { int cachedId = i.next(); if (!loadedObjects.contains(cachedId)) { i.remove(); removeObject(cachedId, false); } } } fill(true); if (done) { if (lastLoadTime == null) { lastLoadTime = new HashMap<>(); } lastLoadTime.put(Objects.hash(currentAccount, type, dialogId), System.currentTimeMillis()); } else { resetCanLoad(); } saveCache(); }); } else { AndroidUtilities.runOnUIThread(() -> { loading = false; error = true; NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesListUpdated, StoriesList.this, false); }); } }); return true; } // public void invalidate() { // resetCanLoad(); // final int wasCount = messageObjects.size(); // messageObjectsMap.clear(); // loadedObjects.clear(); // cachedObjects.clear(); // invalidateCache(); // done = false; // error = false; // load(true, Utilities.clamp(wasCount, 50, 10)); // } public void updateDeletedStories(List<TL_stories.StoryItem> storyItems) { FileLog.d("StoriesList " + type + "{"+ dialogId +"} updateDeletedStories {" + storyItemIds(storyItems) + "}"); if (storyItems == null) { return; } boolean changed = false; for (int i = 0; i < storyItems.size(); ++i) { TL_stories.StoryItem storyItem = storyItems.get(i); if (storyItem == null) { continue; } boolean contains = loadedObjects.contains(storyItem.id) || cachedObjects.contains(storyItem.id); if (contains) { changed = true; loadedObjects.remove(storyItem.id); cachedObjects.remove(storyItem.id); if (totalCount != -1) { totalCount--; } } removeObject(storyItem.id, true); } if (changed) { fill(true); saveCache(); } } public void updateStoryViews(List<Integer> ids, ArrayList<TL_stories.StoryViews> storyViews) { if (ids == null || storyViews == null) { return; } boolean changed = false; for (int i = 0; i < ids.size(); ++i) { int id = ids.get(i); if (i >= storyViews.size()) break; TL_stories.StoryViews storyView = storyViews.get(i); MessageObject messageObject = messageObjectsMap.get(id); if (messageObject != null && messageObject.storyItem != null) { messageObject.storyItem.views = storyView; changed = true; } } if (changed) { saveCache(); } } public void updateStories(List<TL_stories.StoryItem> storyItems) { FileLog.d("StoriesList " + type + "{"+ dialogId +"} updateStories {" + storyItemIds(storyItems) + "}"); if (storyItems == null) { return; } boolean changed = false; for (int i = 0; i < storyItems.size(); ++i) { TL_stories.StoryItem storyItem = storyItems.get(i); if (storyItem == null) { continue; } boolean contains = loadedObjects.contains(storyItem.id) || cachedObjects.contains(storyItem.id); boolean shouldContain = type == TYPE_ARCHIVE ? true : storyItem.pinned; if (storyItem instanceof TL_stories.TL_storyItemDeleted) { shouldContain = false; } if (contains != shouldContain) { changed = true; if (!shouldContain) { FileLog.d("StoriesList remove story " + storyItem.id); removeObject(storyItem.id, true); if (totalCount != -1) { totalCount--; } } else { FileLog.d("StoriesList put story " + storyItem.id); pushObject(toMessageObject(storyItem, null), false); if (totalCount != -1) { totalCount++; } } } else if (contains && shouldContain) { MessageObject messageObject = messageObjectsMap.get(storyItem.id); if (messageObject == null || !equal(messageObject.storyItem, storyItem)) { FileLog.d("StoriesList update story " + storyItem.id); messageObjectsMap.put(storyItem.id, toMessageObject(storyItem, null)); changed = true; } } } if (changed) { fill(true); saveCache(); } } public MessageObject findMessageObject(int storyId) { return messageObjectsMap.get(storyId); } public boolean equal(TL_stories.StoryItem a, TL_stories.StoryItem b) { if (a == null && b == null) { return true; } if ((a == null) != (b == null)) { return false; } return ( a == b || a.id == b.id && a.media == b.media && TextUtils.equals(a.caption, b.caption) ); } private MessageObject toMessageObject(TL_stories.StoryItem storyItem, TL_stories.TL_stories_stories stories) { storyItem.dialogId = dialogId; storyItem.messageId = storyItem.id; MessageObject msg = new MessageObject(currentAccount, storyItem); msg.generateThumbs(false); return msg; } public boolean isLoading() { return preloading || loading; } public boolean isFull() { return done; } public boolean isError() { return error; } public int getLoadedCount() { return loadedObjects.size(); } public int getCount() { if (showVideos && showPhotos) { if (totalCount < 0) { return messageObjects.size(); } return Math.max(messageObjects.size(), totalCount); } else { return messageObjects.size(); } } public boolean isPinned(int storyId) { if (type != TYPE_PINNED) return false; return pinnedIds.contains(storyId); } public boolean updatePinned(ArrayList<Integer> ids, boolean pin) { ArrayList<Integer> newPinnedOrder = new ArrayList<>(pinnedIds); for (int i = ids.size() - 1; i >= 0; --i) { int id = ids.get(i); if (pin && !newPinnedOrder.contains(id)) newPinnedOrder.add(0, id); else if (!pin && newPinnedOrder.contains(id)) newPinnedOrder.remove((Object) id); } final int limit = MessagesController.getInstance(currentAccount).storiesPinnedToTopCountMax; boolean hitLimit = newPinnedOrder.size() > limit; if (hitLimit) { return true; // newPinnedOrder.subList(limit, newPinnedOrder.size()).clear(); } boolean changed = pinnedIds.size() != newPinnedOrder.size(); if (!changed) { for (int i = 0; i < pinnedIds.size(); ++i) { if (pinnedIds.get(i) != newPinnedOrder.get(i)) { changed = true; break; } } } if (changed) { pinnedIds.clear(); pinnedIds.addAll(newPinnedOrder); fill(true); TL_stories.TL_togglePinnedToTop req = new TL_stories.TL_togglePinnedToTop(); req.id.addAll(pinnedIds); req.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialogId); ConnectionsManager.getInstance(currentAccount).sendRequest(req, (res, err) -> AndroidUtilities.runOnUIThread(() -> { })); } return hitLimit; } public void updatePinnedOrder(ArrayList<Integer> ids, boolean apply) { ArrayList<Integer> newPinnedOrder = new ArrayList<>(ids); final int limit = MessagesController.getInstance(currentAccount).storiesPinnedToTopCountMax; boolean hitLimit = newPinnedOrder.size() > limit; if (hitLimit) { newPinnedOrder.subList(limit, newPinnedOrder.size()).clear(); } boolean changed = pinnedIds.size() != newPinnedOrder.size(); if (!changed) { for (int i = 0; i < pinnedIds.size(); ++i) { if (pinnedIds.get(i) != newPinnedOrder.get(i)) { changed = true; break; } } } pinnedIds.clear(); pinnedIds.addAll(newPinnedOrder); fill(false); if (apply) { TL_stories.TL_togglePinnedToTop req = new TL_stories.TL_togglePinnedToTop(); req.id.addAll(pinnedIds); req.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialogId); ConnectionsManager.getInstance(currentAccount).sendRequest(req, (res, err) -> AndroidUtilities.runOnUIThread(() -> { })); } } } private final Comparator<TL_stories.PeerStories> peerStoriesComparator = (o1, o2) -> { long dialogId1 = DialogObject.getPeerDialogId(o1.peer); long dialogId2 = DialogObject.getPeerDialogId(o2.peer); boolean hasUploading1 = hasUploadingStories(dialogId1); boolean hasUploading2 = hasUploadingStories(dialogId2); boolean hasUnread1 = hasUnreadStories(dialogId1); boolean hasUnread2 = hasUnreadStories(dialogId2); if (hasUploading1 == hasUploading2) { if (hasUnread1 == hasUnread2) { int service1 = UserObject.isService(dialogId1) ? 1 : 0; int service2 = UserObject.isService(dialogId2) ? 1 : 0; if (service1 == service2) { int i1 = isPremium(dialogId1) ? 1 : 0; int i2 = isPremium(dialogId2) ? 1 : 0; if (i1 == i2) { int date1 = o1.stories.isEmpty() ? 0 : o1.stories.get(o1.stories.size() - 1).date; int date2 = o2.stories.isEmpty() ? 0 : o2.stories.get(o2.stories.size() - 1).date; return date2 - date1; } else { return i2 - i1; } } else { return service2 - service1; } } else { int i1 = hasUnread1 ? 1 : 0; int i2 = hasUnread2 ? 1 : 0; return i2 - i1; } } else { int i1 = hasUploading1 ? 1 : 0; int i2 = hasUploading2 ? 1 : 0; return i2 - i1; } }; private boolean isPremium(long uid) { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(uid); if (user == null) { return false; } return user.premium; } final Runnable sortStoriesRunnable; public void scheduleSort() { AndroidUtilities.cancelRunOnUIThread(sortStoriesRunnable); sortStoriesRunnable.run(); // AndroidUtilities.runOnUIThread(sortStoriesRunnable, 2000); } public boolean hasOnlySelfStories() { return hasSelfStories() && (getDialogListStories().isEmpty() || (getDialogListStories().size() == 1 && DialogObject.getPeerDialogId(getDialogListStories().get(0).peer) == UserConfig.getInstance(currentAccount).clientUserId)); } public void sortHiddenStories() { sortDialogStories(hiddenListStories); NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesUpdated); } public HashSet<Long> blocklist = new HashSet<>(); private LongSparseArray<Boolean> blockedOverride = new LongSparseArray<>(); private int blocklistCount; public boolean blocklistFull = false; private boolean blocklistLoadingReset = false; private boolean blocklistLoading = false; private int blocklistReqId; private long lastBlocklistRequested = 0; public void loadBlocklistAtFirst() { if (lastBlocklistRequested == 0) loadBlocklist(false); } public void loadBlocklist(boolean reset) { if (blocklistLoading) { if (reset && !blocklistLoadingReset) { ConnectionsManager.getInstance(currentAccount).cancelRequest(blocklistReqId, true); blocklistReqId = 0; blocklistLoading = blocklistLoadingReset = false; } else { return; } } if (reset && (System.currentTimeMillis() - lastBlocklistRequested) < 1000 * 60 * 30) { return; } if (!reset && blocklistFull) { return; } blocklistLoading = true; blocklistLoadingReset = reset; TLRPC.TL_contacts_getBlocked req = new TLRPC.TL_contacts_getBlocked(); req.my_stories_from = true; if (reset) { req.offset = 0; req.limit = 100; blocklistFull = false; } else { req.offset = blocklist.size(); req.limit = 25; } ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, err) -> AndroidUtilities.runOnUIThread(() -> { if (response instanceof TLRPC.TL_contacts_blocked) { TLRPC.TL_contacts_blocked res = (TLRPC.TL_contacts_blocked) response; MessagesController.getInstance(currentAccount).putUsers(res.users, false); MessagesController.getInstance(currentAccount).putChats(res.chats, false); blocklist.clear(); for (TLRPC.TL_peerBlocked peer : res.blocked) { long id = DialogObject.getPeerDialogId(peer.peer_id); blocklist.add(id); } blocklistCount = Math.max(blocklist.size(), res.count); blocklistFull = true; } else if (response instanceof TLRPC.TL_contacts_blockedSlice) { TLRPC.TL_contacts_blockedSlice res = (TLRPC.TL_contacts_blockedSlice) response; MessagesController.getInstance(currentAccount).putUsers(res.users, false); MessagesController.getInstance(currentAccount).putChats(res.chats, false); for (TLRPC.TL_peerBlocked peer : res.blocked) { long id = DialogObject.getPeerDialogId(peer.peer_id); blocklist.add(id); } blocklistCount = res.count; blocklistFull = blocklist.size() >= blocklistCount; } else { return; } NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesBlocklistUpdate); blocklistLoading = false; lastBlocklistRequested = System.currentTimeMillis(); })); } public int getBlocklistCount() { return blocklistCount; } public void updateBlockedUsers(HashSet<Long> ids, Runnable done) { TLRPC.TL_contacts_setBlocked req = new TLRPC.TL_contacts_setBlocked(); req.my_stories_from = true; req.limit = blocklist.size(); blocklistCount -= blocklist.size(); if (blocklistCount < 0) { blocklistCount = 0; } blocklist.clear(); for (long id : ids) { TLRPC.InputPeer inputPeer = MessagesController.getInstance(currentAccount).getInputPeer(id); if (inputPeer == null || inputPeer instanceof TLRPC.TL_inputPeerEmpty) { continue; } blocklist.add(id); req.id.add(inputPeer); } blocklistCount += blocklist.size(); req.limit = Math.max(req.limit, blocklist.size()); ConnectionsManager.getInstance(currentAccount).sendRequest(req, (res, err) -> AndroidUtilities.runOnUIThread(() -> { if (done != null) { done.run(); } })); } public boolean isBlocked(TL_stories.StoryView storyView) { if (storyView == null) { return false; } if (blockedOverride.containsKey(storyView.user_id)) { return blockedOverride.get(storyView.user_id); } if (lastBlocklistRequested == 0) { return storyView.blocked_my_stories_from || storyView.blocked; } if (blocklist.contains(storyView.user_id)) { return true; } return storyView.blocked_my_stories_from || storyView.blocked; } public boolean isBlocked(long did) { if (blockedOverride.containsKey(did)) { return blockedOverride.get(did); } return blocklist.contains(did); } public void applyStoryViewsBlocked(TL_stories.StoryViewsList res) { if (res == null || res.views == null) { return; } for (int i = 0; i < res.views.size(); ++i) { TL_stories.StoryView view = res.views.get(i); if (blockedOverride.containsKey(view.user_id)) { blockedOverride.put(view.user_id, view.blocked_my_stories_from); } } } public void updateBlockUser(long did, boolean block) { updateBlockUser(did, block, true); } public void updateBlockUser(long did, boolean block, boolean request) { TLRPC.InputPeer inputPeer = MessagesController.getInstance(currentAccount).getInputPeer(did); if (inputPeer == null || inputPeer instanceof TLRPC.TL_inputPeerEmpty) { return; } blockedOverride.put(did, block); if (blocklist.contains(did) != block) { if (block) { blocklist.add(did); blocklistCount++; } else { blocklist.remove(did); blocklistCount--; } } if (request) { TLObject req; if (block) { TLRPC.TL_contacts_block blockReq = new TLRPC.TL_contacts_block(); blockReq.my_stories_from = true; blockReq.id = inputPeer; req = blockReq; } else { TLRPC.TL_contacts_unblock unblockReq = new TLRPC.TL_contacts_unblock(); unblockReq.my_stories_from = true; unblockReq.id = inputPeer; req = unblockReq; } ConnectionsManager.getInstance(currentAccount).sendRequest(req, null); } NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesBlocklistUpdate); } private boolean storyLimitFetched; private StoryLimit storyLimitCached; public StoryLimit checkStoryLimit() { final int countLimit = UserConfig.getInstance(currentAccount).isPremium() ? MessagesController.getInstance(currentAccount).storyExpiringLimitPremium : MessagesController.getInstance(currentAccount).storyExpiringLimitDefault; if (getMyStoriesCount() >= countLimit) { return new StoryLimit(StoryLimit.LIMIT_COUNT, 0); } if (storyLimitFetched) { return storyLimitCached; } TL_stories.TL_stories_canSendStory tl_stories_canSendStory = new TL_stories.TL_stories_canSendStory(); tl_stories_canSendStory.peer = MessagesController.getInstance(currentAccount).getInputPeer(UserConfig.getInstance(currentAccount).getClientUserId()); ConnectionsManager.getInstance(currentAccount).sendRequest(tl_stories_canSendStory, (res, err) -> AndroidUtilities.runOnUIThread(() -> { storyLimitFetched = true; if (res instanceof TLRPC.TL_boolTrue) { storyLimitCached = null; NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesLimitUpdate); } else { checkStoryError(err); } }), ConnectionsManager.RequestFlagDoNotWaitFloodWait); return null; } public void canSendStoryFor(long dialogId, Consumer<Boolean> consumer, boolean showLimitsBottomSheet, Theme.ResourcesProvider resourcesProvider) { TL_stories.TL_stories_canSendStory tl_stories_canSendStory = new TL_stories.TL_stories_canSendStory(); tl_stories_canSendStory.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialogId); ConnectionsManager.getInstance(currentAccount).sendRequest(tl_stories_canSendStory, (res, err) -> AndroidUtilities.runOnUIThread(() -> { if (err != null) { if (err.text.contains("BOOSTS_REQUIRED")) { if (showLimitsBottomSheet) { MessagesController messagesController = MessagesController.getInstance(currentAccount); messagesController.getBoostsController().getBoostsStats(dialogId, boostsStatus -> { if (boostsStatus == null) { consumer.accept(false); return; } messagesController.getBoostsController().userCanBoostChannel(dialogId, boostsStatus, canApplyBoost -> { if (canApplyBoost == null) { consumer.accept(false); return; } BaseFragment lastFragment = LaunchActivity.getLastFragment(); Runnable runnable = null; if (canPostStories(dialogId)) { runnable = () -> { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); BaseFragment fragment = StatisticActivity.create(chat); BaseFragment lastFragment1 = LaunchActivity.getLastFragment(); if (lastFragment1 != null) { if (StoryRecorder.isVisible()) { BaseFragment.BottomSheetParams params = new BaseFragment.BottomSheetParams(); params.transitionFromLeft = true; lastFragment1.showAsSheet(fragment, params); } else { lastFragment1.presentFragment(fragment); } } }; } LimitReachedBottomSheet.openBoostsForPostingStories(lastFragment, dialogId, canApplyBoost, boostsStatus, runnable); consumer.accept(false); }); consumer.accept(false); }); } else { consumer.accept(false); } } else { BulletinFactory bulletinFactory = BulletinFactory.global(); if (bulletinFactory != null) { bulletinFactory.createErrorBulletin(err.text); } consumer.accept(false); } } else { consumer.accept(true); } }), ConnectionsManager.RequestFlagDoNotWaitFloodWait); } public boolean checkStoryError(TLRPC.TL_error err) { boolean limitUpdate = false; if (err != null && err.text != null) { if (err.text.startsWith("STORY_SEND_FLOOD_WEEKLY_")) { long until = 0; try { until = Long.parseLong(err.text.substring("STORY_SEND_FLOOD_WEEKLY_".length())); } catch (Exception ignore) {} storyLimitCached = new StoryLimit(StoryLimit.LIMIT_WEEK, until); limitUpdate = true; } else if (err.text.startsWith("STORY_SEND_FLOOD_MONTHLY_")) { long until = 0; try { until = Long.parseLong(err.text.substring("STORY_SEND_FLOOD_MONTHLY_".length())); } catch (Exception ignore) {} storyLimitCached = new StoryLimit(StoryLimit.LIMIT_MONTH, until); limitUpdate = true; } else if (err.text.equals("STORIES_TOO_MUCH")) { storyLimitCached = new StoryLimit(StoryLimit.LIMIT_COUNT, 0); limitUpdate = true; } else if (err.text.equals("PREMIUM_ACCOUNT_REQUIRED")) { MessagesController mc = MessagesController.getInstance(currentAccount); if ("enabled".equals(mc.storiesPosting)) { mc.getMainSettings().edit().putString("storiesPosting", mc.storiesPosting = "premium").apply(); NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesEnabledUpdate); } limitUpdate = true; } } if (limitUpdate) { NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesLimitUpdate); } return limitUpdate; } public boolean hasStoryLimit() { StoryLimit storyLimit = checkStoryLimit(); return storyLimit != null && storyLimit.active(currentAccount); } public void invalidateStoryLimit() { storyLimitFetched = false; storyLimitCached = null; } public static class StoryLimit { public static final int LIMIT_COUNT = 1; public static final int LIMIT_WEEK = 2; public static final int LIMIT_MONTH = 3; public int type; public long until; public StoryLimit(int type, long until) { this.type = type; this.until = until; } public int getLimitReachedType() { switch (type) { case LIMIT_WEEK: return LimitReachedBottomSheet.TYPE_STORIES_WEEK; case LIMIT_MONTH: return LimitReachedBottomSheet.TYPE_STORIES_MONTH; default: case LIMIT_COUNT: return LimitReachedBottomSheet.TYPE_STORIES_COUNT; } } public boolean active(int currentAccount) { switch (type) { case LIMIT_WEEK: case LIMIT_MONTH: return ConnectionsManager.getInstance(currentAccount).getCurrentTime() < until; case LIMIT_COUNT: default: return true; } } } public final ArrayList<TLRPC.InputPeer> sendAs = new ArrayList<>(); { sendAs.add(new TLRPC.TL_inputPeerSelf()); } private boolean loadingSendAs = false; private boolean loadedSendAs = false; public void loadSendAs() { if (loadingSendAs || loadedSendAs) { return; } loadingSendAs = true; ConnectionsManager.getInstance(currentAccount).sendRequest(new TL_stories.TL_stories_getChatsToSend(), (res, err) -> AndroidUtilities.runOnUIThread(() -> { sendAs.clear(); sendAs.add(new TLRPC.TL_inputPeerSelf()); if (res instanceof TLRPC.TL_messages_chats) { ArrayList<TLRPC.Chat> chats = ((TLRPC.TL_messages_chats) res).chats; MessagesController.getInstance(currentAccount).putChats(chats, false); for (TLRPC.Chat chat : chats) { TLRPC.InputPeer peer = MessagesController.getInputPeer(chat); sendAs.add(peer); } } loadingSendAs = false; loadedSendAs = true; NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.storiesSendAsUpdate); })); } private void invalidateSendAsList() { // when channel gets deleted or something else happens... loadedSendAs = false; } public boolean canEditStories(long dialogId) { if (dialogId < 0) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); if (chat == null) { return false; } return chat.creator || chat.admin_rights != null && chat.admin_rights.edit_stories; } return false; } public boolean canPostStories(long dialogId) { if (dialogId < 0) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); if (chat == null || !ChatObject.isBoostSupported(chat)) { return false; } return chat.creator || chat.admin_rights != null && chat.admin_rights.post_stories; } return false; } public boolean canEditStory(TL_stories.StoryItem storyItem) { if (storyItem == null) { return false; } if (storyItem.dialogId == getSelfUserId()) { return false; } if (storyItem.dialogId < 0) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-storyItem.dialogId); if (chat == null) { return false; } if (chat.creator) { return true; } if (storyItem.out && chat.admin_rights != null && (chat.admin_rights.post_stories || chat.admin_rights.edit_stories)) { return true; } if (!storyItem.out && chat.admin_rights != null && chat.admin_rights.edit_stories) { return true; } } return false; } public boolean canDeleteStory(TL_stories.StoryItem storyItem) { if (storyItem == null) { return false; } if (storyItem.dialogId == getSelfUserId()) { return false; } if (storyItem.dialogId < 0) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-storyItem.dialogId); if (chat == null) { return false; } if (chat.creator) { return true; } if (storyItem.out && chat.admin_rights != null && (chat.admin_rights.post_stories || chat.admin_rights.delete_stories)) { return true; } if (!storyItem.out && chat.admin_rights != null && chat.admin_rights.delete_stories) { return true; } } return false; } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/ui/Stories/StoriesController.java
41,719
package com.bumptech.glide; import static com.google.common.truth.Truth.assertThat; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; import com.bumptech.glide.test.GlideApp; import com.bumptech.glide.test.ModelGeneratorRule; import com.bumptech.glide.test.ResourceIds; import com.bumptech.glide.testutil.ConcurrencyHelper; import com.bumptech.glide.testutil.TearDownGlide; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; @RunWith(AndroidJUnit4.class) public class AsBytesTest { @Rule public final TearDownGlide tearDownGlide = new TearDownGlide(); @Rule public final ModelGeneratorRule modelGeneratorRule = new ModelGeneratorRule(); private final ConcurrencyHelper concurrency = new ConcurrencyHelper(); private Context context; @Before public void setUp() throws IOException { MockitoAnnotations.initMocks(this); context = ApplicationProvider.getApplicationContext(); } @Test public void loadImageResourceId_asBytes_providesBytesOfBitmap() { byte[] data = concurrency.get( Glide.with(context).as(byte[].class).load(ResourceIds.raw.canonical).submit()); assertThat(data).isNotNull(); assertThat(BitmapFactory.decodeByteArray(data, 0, data.length)).isNotNull(); } @Test public void loadBitmap_asBytes_providesBytesOfBitmap() { Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), ResourceIds.raw.canonical); byte[] data = concurrency.get(Glide.with(context).as(byte[].class).load(bitmap).submit()); assertThat(data).isNotNull(); assertThat(BitmapFactory.decodeByteArray(data, 0, data.length)).isNotNull(); } @Test public void loadBitmapDrawable_asBytes_providesBytesOfBitmap() { Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), ResourceIds.raw.canonical); byte[] data = concurrency.get( Glide.with(context) .as(byte[].class) .load(new BitmapDrawable(context.getResources(), bitmap)) .submit()); assertThat(data).isNotNull(); assertThat(BitmapFactory.decodeByteArray(data, 0, data.length)).isNotNull(); } @Test public void loadVideoResourceId_asBytes_providesBytesOfFrame() { byte[] data = concurrency.get(Glide.with(context).as(byte[].class).load(ResourceIds.raw.video).submit()); assertThat(data).isNotNull(); assertThat(BitmapFactory.decodeByteArray(data, 0, data.length)).isNotNull(); } @Test public void loadVideoResourceId_asBytes_withFrameTime_providesBytesOfFrame() { byte[] data = concurrency.get( GlideApp.with(context) .as(byte[].class) .load(ResourceIds.raw.video) .frame(TimeUnit.SECONDS.toMicros(1)) .submit()); assertThat(data).isNotNull(); assertThat(BitmapFactory.decodeByteArray(data, 0, data.length)).isNotNull(); } @Test public void loadVideoFile_asBytes_providesByteOfFrame() throws IOException { byte[] data = concurrency.get(Glide.with(context).as(byte[].class).load(writeVideoToFile()).submit()); assertThat(data).isNotNull(); assertThat(BitmapFactory.decodeByteArray(data, 0, data.length)).isNotNull(); } @Test public void loadVideoFile_asBytes_withFrameTime_providesByteOfFrame() throws IOException { byte[] data = concurrency.get( GlideApp.with(context) .as(byte[].class) .load(writeVideoToFile()) .frame(TimeUnit.SECONDS.toMicros(1)) .submit()); assertThat(data).isNotNull(); assertThat(BitmapFactory.decodeByteArray(data, 0, data.length)).isNotNull(); } @Test public void loadVideoFilePath_asBytes_providesByteOfFrame() throws IOException { byte[] data = concurrency.get( Glide.with(context) .as(byte[].class) .load(writeVideoToFile().getAbsolutePath()) .submit()); assertThat(data).isNotNull(); assertThat(BitmapFactory.decodeByteArray(data, 0, data.length)).isNotNull(); } @Test public void loadVideoFilePath_asBytes_withFrameTime_providesByteOfFrame() throws IOException { byte[] data = concurrency.get( GlideApp.with(context) .as(byte[].class) .load(writeVideoToFile().getAbsolutePath()) .frame(TimeUnit.SECONDS.toMicros(1)) .submit()); assertThat(data).isNotNull(); assertThat(BitmapFactory.decodeByteArray(data, 0, data.length)).isNotNull(); } @Test public void loadVideoFileUri_asBytes_providesByteOfFrame() throws IOException { byte[] data = concurrency.get(Glide.with(context).as(byte[].class).load(writeVideoToFileUri()).submit()); assertThat(data).isNotNull(); assertThat(BitmapFactory.decodeByteArray(data, 0, data.length)).isNotNull(); } @Test public void loadVideoFileUri_asBytes_withFrameTime_providesByteOfFrame() throws IOException { byte[] data = concurrency.get( GlideApp.with(context) .as(byte[].class) .load(writeVideoToFileUri()) .frame(TimeUnit.SECONDS.toMicros(1)) .submit()); assertThat(data).isNotNull(); assertThat(BitmapFactory.decodeByteArray(data, 0, data.length)).isNotNull(); } private File writeVideoToFile() throws IOException { return modelGeneratorRule.asFile(ResourceIds.raw.video); } private Uri writeVideoToFileUri() throws IOException { return Uri.fromFile(writeVideoToFile()); } }
bumptech/glide
instrumentation/src/androidTest/java/com/bumptech/glide/AsBytesTest.java
41,754
package example_of_simulator; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.geom.Line2D; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; import javax.swing.JPanel; import javax.swing.*; //categories for floor plan 1: //1. offers //2. TV&Image //3. Books&Comics //4. CDs&Vinyls //5. Gaming //6. Computers&Peripherals //7. Photos&Videos //8. Mobile_phones&Tablets // xrwmatizontas etsi ola ta proionta poy vriskonte ston pinaka kathe thesis toy array list public class VisualizationProducts extends JPanel { private static final long serialVersionUID = -6291233936414618049L; private String productsPath="C:\\Users\\Σωτηρία\\Desktop\\eclipse-workspace\\simulator\\src\\example_of_simulator\\Floor Plans and Products\\products_floor_plan_1.txt"; public VisualizationProducts() {} protected void paintComponent(Graphics g) { Scanner s; //kathe thesi eine mia katigoria !! ArrayList<String> products = new ArrayList<String>(); super.paintComponent(g); g.setColor(Color.BLACK); g.fillRect(0, 0, getWidth(), getHeight()); //products try { s = new Scanner(new File(productsPath)); while (s.hasNext()){ products.add(s.next()); } s.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } for(int i=0; i<products.size(); i++) { String[] product = products.get(i).split(","); String category=product[4]; double x= Double.parseDouble(product[2].substring(1)); double y= Double.parseDouble(product[3].substring(0,product[3].length()-1)); Graphics2D g2d = (Graphics2D) g; Shape l; if(category.equals("offers")) { g2d.setPaint(Color.red); l = new Line2D.Double(x, y, x, y); g2d.draw(l); }else if(category.equals("TV&Image")) { g2d.setPaint(Color.cyan); l = new Line2D.Double(x, y, x, y); g2d.draw(l); }else if(category.equals("Books&Comics")) { g2d.setPaint(Color.yellow); l = new Line2D.Double(x, y, x, y); g2d.draw(l); }else if(category.equals("CDs&Vinyls")) { g2d.setPaint(Color.orange); l = new Line2D.Double(x, y, x, y); g2d.draw(l); }else if(category.equals("Gaming")) { g2d.setPaint(Color.magenta); l = new Line2D.Double(x, y, x, y); g2d.draw(l); }else if(category.equals("Computers&Peripherals")) { g2d.setPaint(Color.blue); l = new Line2D.Double(x, y, x, y); g2d.draw(l); }else if(category.equals("Photos&Videos")) { g2d.setPaint(Color.pink); l = new Line2D.Double(x, y, x, y); g2d.draw(l); }else if(category.equals("Mobile_phones&Tablets")) { g2d.setPaint(Color.green); l = new Line2D.Double(x, y, x, y); g2d.draw(l); } } } }
SotiriaKa/My-Generator
VisualizationProducts.java
41,756
package example_of_simulator; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; //8 categories for floor plan : //1. offers //2. TV&Image //3. Books&Comics //4. CDs&Vinyls //5. Gaming //6. Computers&Peripherals //7. Photos&Videos //8. Mobile_phones&Tablets public class DataProducts { public static void main(String[] args) { File file1 = null; BufferedWriter bw=null; int j=1; double x=10.0; double y=20.0; try { file1 = new File("C:\\Users\\Σωτηρία\\Desktop\\eclipse-workspace\\simulator\\src\\example_of_simulator\\Floor Plans and Products\\products_floor_plan_1.txt"); FileOutputStream fos = new FileOutputStream(file1); bw = new BufferedWriter(new OutputStreamWriter(fos)); while (j<500) { bw.write(j+",offer"+j+",("+x+","+y+"),offers"); bw.newLine(); x+=1.84; j++; } y=600.0; x=10.0; int k=0; while(k<400) { bw.write(j+",TV"+j+",("+x+","+y+"),TV&Image"); bw.newLine(); j++; x+=2.3; k++; } k=0; y=20.0; x=10.0; while(k<1000) { bw.write(j+",Book"+j+",("+x+","+y+"),Books&Comics"); bw.newLine(); j++; //(600-20)/1000 y+=0.58; k++; } //ya ta CD kai vinylia x=950.0; y=500.0; k=0; while(k<30) { bw.write(j+",CD"+j+",("+x+","+y+"),CDs&Vinyls"); bw.newLine(); j++; y+=3.3; k++; } x=950.0; y=500.0; k=0; while(k<100) { bw.write(j+",CD"+j+",("+x+","+y+"),CDs&Vinyls"); bw.newLine(); j++; x+=3.5; k++; } //Gaming x=60.0; y=70.0; k=0; while(k<40) { bw.write(j+",gaming"+j+",("+x+","+y+"),Gaming"); bw.newLine(); j++; y+=5.0; k++; } x=160.0; y=70.0; k=0; while(k<40) { bw.write(j+",gaming"+j+",("+x+","+y+"),Gaming"); bw.newLine(); j++; y+=5.0; k++; } x=60.0; y=70.0; k=0; while(k<20) { bw.write(j+",gaming"+j+",("+x+","+y+"),Gaming"); bw.newLine(); j++; x+=5.0; k++; } x=60.0; y=270.0; k=0; while(k<20) { bw.write(j+",gaming"+j+",("+x+","+y+"),Gaming"); bw.newLine(); j++; //(600-20)/1000 x+=5.0; k++; } x=60.0; y=350.0; k=0; while(k<40) { bw.write(j+",gaming"+j+",("+x+","+y+"),Gaming"); bw.newLine(); j++; y+=5.0; k++; } x=160.0; y=350.0; k=0; while(k<40) { bw.write(j+",gaming"+j+",("+x+","+y+"),Gaming"); bw.newLine(); j++; y+=5.0; k++; } x=60.0; y=350.0; k=0; while(k<20) { bw.write(j+",gaming"+j+",("+x+","+y+"),Gaming"); bw.newLine(); j++; x+=5.0; k++; } x=60.0; y=550.0; k=0; while(k<20) { bw.write(j+",gaming"+j+",("+x+","+y+"),Gaming"); bw.newLine(); j++; x+=5.0; k++; } x=240.0; y=70.0; k=0; while(k<20) { bw.write(j+",PC"+j+",("+x+","+y+"),Computers&Peripherals"); bw.newLine(); j++; x+=5.0; k++; } x=240.0; y=70.0; k=0; while(k<40) { bw.write(j+",PC"+j+",("+x+","+y+"),Computers&Peripherals"); bw.newLine(); j++; y+=5.0; k++; } x=240.0; y=270.0; k=0; while(k<20) { bw.write(j+",PC"+j+",("+x+","+y+"),Computers&Peripherals"); bw.newLine(); j++; x+=5.0; k++; } x=340.0; y=70.0; k=0; while(k<40) { bw.write(j+",PC"+j+",("+x+","+y+"),Computers&Peripherals"); bw.newLine(); j++; y+=5.0; k++; } x=420.0; y=70.0; k=0; while(k<20) { bw.write(j+",PC"+j+",("+x+","+y+"),Computers&Peripherals"); bw.newLine(); j++; x+=5.0; k++; } x=420.0; y=70.0; k=0; while(k<40) { bw.write(j+",PC"+j+",("+x+","+y+"),Computers&Peripherals"); bw.newLine(); j++; y+=5.0; k++; } x=420.0; y=270.0; k=0; while(k<20) { bw.write(j+",PC"+j+",("+x+","+y+"),Computers&Peripherals"); bw.newLine(); j++; x+=5.0; k++; } x=520.0; y=70.0; k=0; while(k<40) { bw.write(j+",PC"+j+",("+x+","+y+"),Computers&Peripherals"); bw.newLine(); j++; y+=5.0; k++; } x=240.0; y=350.0; k=0; while(k<20) { bw.write(j+",PC"+j+",("+x+","+y+"),Computers&Peripherals"); bw.newLine(); j++; x+=5.0; k++; } x=240.0; y=350.0; k=0; while(k<40) { bw.write(j+",PC"+j+",("+x+","+y+"),Computers&Peripherals"); bw.newLine(); j++; y+=5.0; k++; } x=240.0; y=550.0; k=0; while(k<20) { bw.write(j+",PC"+j+",("+x+","+y+"),Computers&Peripherals"); bw.newLine(); j++; x+=5.0; k++; } x=340.0; y=350.0; k=0; while(k<40) { bw.write(j+",PC"+j+",("+x+","+y+"),Computers&Peripherals"); bw.newLine(); j++; y+=5.0; k++; } x=420.0; y=350.0; k=0; while(k<20) { bw.write(j+",PC"+j+",("+x+","+y+"),Computers&Peripherals"); bw.newLine(); j++; x+=5.0; k++; } x=420.0; y=350.0; k=0; while(k<40) { bw.write(j+",PC"+j+",("+x+","+y+"),Computers&Peripherals"); bw.newLine(); j++; y+=5.0; k++; } x=420.0; y=550.0; k=0; while(k<20) { bw.write(j+",PC"+j+",("+x+","+y+"),Computers&Peripherals"); bw.newLine(); j++; x+=5.0; k++; } x=520.0; y=350.0; k=0; while(k<40) { bw.write(j+",PC"+j+",("+x+","+y+"),Computers&Peripherals"); bw.newLine(); j++; y+=5.0; k++; } //photos and videos x=600.0; y=70.0; k=0; while(k<20) { bw.write(j+",photo"+j+",("+x+","+y+"),Photos&Videos"); bw.newLine(); j++; x+=5.0; k++; } x=600.0; y=70.0; k=0; while(k<40) { bw.write(j+",photo"+j+",("+x+","+y+"),Photos&Videos"); bw.newLine(); j++; //(600-20)/1000 y+=5.0; k++; } x=600.0; y=270.0; k=0; while(k<20) { bw.write(j+",photo"+j+",("+x+","+y+"),Photos&Videos"); bw.newLine(); j++; x+=5.0; k++; } x=700.0; y=70.0; k=0; while(k<40) { bw.write(j+",photo"+j+",("+x+","+y+"),Photos&Videos"); bw.newLine(); j++; y+=5.0; k++; } x=600.0; y=350.0; k=0; while(k<20) { bw.write(j+",photo"+j+",("+x+","+y+"),Photos&Videos"); bw.newLine(); j++; x+=5.0; k++; } x=600.0; y=350.0; k=0; while(k<40) { bw.write(j+",photo"+j+",("+x+","+y+"),Photos&Videos"); bw.newLine(); j++; y+=5.0; k++; } x=600.0; y=550.0; k=0; while(k<20) { bw.write(j+",photo"+j+",("+x+","+y+"),Photos&Videos"); bw.newLine(); j++; x+=5.0; k++; } x=700.0; y=350.0; k=0; while(k<40) { bw.write(j+",photo"+j+",("+x+","+y+"),Photos&Videos"); bw.newLine(); j++; y+=5.0; k++; } //mobiles kai tablets x=780.0; y=70.0; k=0; while(k<20) { bw.write(j+",mobile"+j+",("+x+","+y+"),Mobile_phones&Tablets"); bw.newLine(); j++; x+=5.0; k++; } x=780.0; y=70.0; k=0; while(k<40) { bw.write(j+",mobile"+j+",("+x+","+y+"),Mobile_phones&Tablets"); bw.newLine(); j++; y+=5.0; k++; } x=780.0; y=270.0; k=0; while(k<20) { bw.write(j+",mobile"+j+",("+x+","+y+"),Mobile_phones&Tablets"); bw.newLine(); j++; x+=5.0; k++; } x=880.0; y=70.0; k=0; while(k<40) { bw.write(j+",mobile"+j+",("+x+","+y+"),Mobile_phones&Tablets"); bw.newLine(); j++; y+=5.0; k++; } x=780.0; y=350.0; k=0; while(k<20) { bw.write(j+",mobile"+j+",("+x+","+y+"),Mobile_phones&Tablets"); bw.newLine(); j++; x+=5.0; k++; } x=780.0; y=350.0; k=0; while(k<40) { bw.write(j+",mobile"+j+",("+x+","+y+"),Mobile_phones&Tablets"); bw.newLine(); j++; y+=5.0; k++; } x=780.0; y=550.0; k=0; while(k<20) { bw.write(j+",mobile"+j+",("+x+","+y+"),Mobile_phones&Tablets"); bw.newLine(); j++; x+=5.0; k++; } x=880.0; y=350.0; k=0; while(k<40) { bw.write(j+",mobile"+j+",("+x+","+y+"),Mobile_phones&Tablets"); bw.newLine(); j++; y+=5.0; k++; } bw.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (bw != null) { bw.close(); } } catch (Exception e) { e.printStackTrace(); } } } }
SotiriaKa/My-Generator
DataProducts.java
41,757
package example_of_simulator; import java.awt.Color; import java.awt.Font; import java.awt.LayoutManager; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class MovingCustomers implements ActionListener, Runnable { private static final int DRAWING_WIDTH = 1290; private static final int DRAWING_HEIGHT = 580; private static final int NUMOBJECTS = 50; private int before_counter = NUMOBJECTS/2; private int N; private BufferedWriter bw=null; private File file = new File("C:\\Users\\Σωτηρία\\Desktop\\eclipse-workspace\\simulator\\src\\example_of_simulator\\Floor Plans and Products\\Costumer_Behavior_Data.txt"); private Object[] ObjectsArray = new Object[NUMOBJECTS]; private JButton btnSelect; private JPanel mainPanel; private JFrame frame; private MoovingPanel moovingPanel; private SelectPanel selectPanel; private ObjectsRun objectsRun; private String filePath=""; private String fileName=""; private RunBefore beforeRun; private ArrayList<String> floor = new ArrayList<String>(); private ArrayList<ArrayList<Integer>> floorLimits = new ArrayList<>(); private int x_door, y_door; private boolean click=false; private int x_real_door; private int y_real_door; private long real_time; private long time_visualization; private long tv1; private long tv2; private boolean visualization=false; public MovingCustomers() { for (int i = 0; i < ObjectsArray.length; i++) { ObjectsArray[i] = new Object(DRAWING_WIDTH, DRAWING_HEIGHT,floorLimits,NUMOBJECTS); } Random rand = new Random(); N = rand.nextInt(8)+3; } @Override public void run() { frame = new JFrame(); frame.setTitle("Moving Objects"); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent event) { exitProcedure(); } }); if(click) { moovingPanel = new MoovingPanel(ObjectsArray, DRAWING_WIDTH, DRAWING_HEIGHT,filePath,fileName); mainPanel = new JPanel(); mainPanel.setLayout((LayoutManager) new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); mainPanel.add(selectPanel); mainPanel.add(moovingPanel); frame.getContentPane().add(mainPanel); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); if (!visualization) { tv1=System.currentTimeMillis(); visualization=true; } objectsRun = new ObjectsRun(this, ObjectsArray, before_counter,N); new Thread(objectsRun).start(); } else { selectPanel = new SelectPanel(); btnSelect = new JButton("Select File"); btnSelect.setBackground(Color.WHITE); btnSelect.setFont(new Font("Lucida Grande", Font.ITALIC, 14)); btnSelect.setBounds(1200, 0, 20, 30); btnSelect.setForeground(Color.BLUE); selectPanel.add(btnSelect); btnSelect.addActionListener(this); frame.add(selectPanel); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); beforeRun = new RunBefore(); new Thread(beforeRun).start(); } } private void exitProcedure() { if(click) { objectsRun.setRunning(false); //time for end visualization tv2 = System.currentTimeMillis(); time_visualization = tv2 - tv1; System.out.println("Visualization duration: "+time_visualization+" milliseconds"); //start time for writing data real_time = System.nanoTime(); System.out.println("Output file creation starts at: "+real_time+" nanoseconds"); } beforeRun.setRunning(false,true); frame.dispose(); try { FileOutputStream fos = new FileOutputStream(file); bw = new BufferedWriter(new OutputStreamWriter(fos)); for(int no=0; no<NUMOBJECTS; no++) { bw.write(ObjectsArray[no].writeFile(no)); bw.newLine(); } //end time for writing data real_time = System.nanoTime(); System.out.println("Output file creation ends at: "+real_time+" nanoseconds"); bw.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (bw != null) { bw.close(); } } catch (Exception e) { e.printStackTrace(); } } System.exit(0); } public void repaintMovingPanel() { moovingPanel.repaint(); } public static void main(String[] args) { SwingUtilities.invokeLater(new MovingCustomers()); } @Override public void actionPerformed(ActionEvent e) { JFileChooser fileChooser = new JFileChooser("."); fileChooser.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Action"); } }); int status = fileChooser.showOpenDialog(null); if (status == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); filePath= file.getPath(); fileName=file.getName(); click=true; beforeRun.stop(); //find the door Scanner s; try { s = new Scanner(new File(filePath)); while (s.hasNext()){ floor.add(s.next()); } s.close(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } String[] part_door = floor.get(floor.size()-1).split(","); int x1_door= Integer.parseInt(part_door[0].substring(1)); int y1_door= Integer.parseInt(part_door[1].substring(0,part_door[1].length()-1)); int x2_door= Integer.parseInt(part_door[2].substring(1)); int y2_door= Integer.parseInt(part_door[3].substring(0,part_door[3].length()-1)); if(x1_door-x2_door==0) { x_door = x1_door; y_door = (y1_door+y2_door)/2; x_real_door = x1_door; y_real_door = y1_door; }else if(y1_door-y2_door==0) { x_door = (x1_door+x2_door)/2; y_door = y1_door; x_real_door = x1_door; y_real_door = y1_door; } for(int i=0; i<floor.size()-1; i++) { String[] part = floor.get(i).split(","); ArrayList<Integer>limits = new ArrayList<Integer>(4); int xleft = Integer.parseInt(part[0].substring(1)); int ytop = Integer.parseInt(part[1].substring(0,part[1].length()-1)); int xright = Integer.parseInt(part[4].substring(1)); int ybottom = Integer.parseInt(part[3].substring(0,part[3].length()-1)); limits.add(xleft); limits.add(xright); limits.add(ybottom); limits.add(ytop); floorLimits.add(limits); for (int j = 0; j < ObjectsArray.length; j++) { ObjectsArray[j].setFloor(floorLimits); } } this.run(); } else if (status == JFileChooser.CANCEL_OPTION) { System.out.println("calceled"); } } public Integer[] getDoor() { Integer [] door= new Integer[4]; door[0]=x_door; door[1]=y_door; door[2]=x_real_door; door[3]=y_real_door; return door; } }
SotiriaKa/My-Generator
MovingCustomers.java
41,758
package example_of_simulator; import java.awt.Color; import java.awt.Graphics; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Random; import java.util.Scanner; public class Object { private static final int size = 10; //size of objects private double x; private double y; private long time_per_step; private double dx; private double dy; private int drawingWidth; private int drawingHeight; private int x_real_door; private int y_real_door; private long start; private long end; private long elapsedTime; private int stand_wait_random; private long stand_wait; private ArrayList<ArrayList<Integer>> floorLimits = new ArrayList<>(); private ArrayList<ArrayList<String>> coordinates_products = new ArrayList<ArrayList<String>>(); private int numobjects; private int stand_wait_search=0; private boolean first_time=true; private boolean initialize_products = true; private long start_time; private boolean first_random = true; private long first_random_time1; private long first_random_time2; private long first_random_time; private long first_random_wait; private boolean color_first; private Color col; private String productsPath="C:\\Users\\Σωτηρία\\Desktop\\eclipse-workspace\\simulator\\src\\example_of_simulator\\Floor Plans and Products\\products_floor_plan_1.txt"; private ArrayList<String> products = new ArrayList<String>(); private ArrayList<String[]> select_product = new ArrayList<String[]>();; private boolean first = true; private int lines = 0; private ArrayList<boolean[]> stages = new ArrayList<boolean[]>(); private ArrayList<Integer> category_moove = new ArrayList<Integer>(); private ArrayList<String> profs= new ArrayList<String>(); private ArrayList<Integer> profile_ids = new ArrayList<Integer>(); private String[][] category_product = {{"offers","500.0,20.0"},{"TV&Image","400.0,600.0"},{"Books&Comics","10.0,310.0"},{"CDs&Vinyls","1000.0,500.0"},{"Gaming","160.0,200.0"},{"Computers&Peripherals","430.0,70.0"},{"Photos&Videos","610.0,500.0"},{"Mobile_phones&Tablets","800.0,500.0"}}; public static int count = 0; public Object(int drawingWidth, int drawingHeight, ArrayList<ArrayList<Integer>> floorLimits,int numobjects) { x = Math.random() * drawingWidth; y = Math.random() * drawingHeight; time_per_step = System.nanoTime(); dx = Math.random() * size;//30D - 15D; dy = Math.random() * size;//30D - 15D; this.drawingWidth = drawingWidth; this.drawingHeight = drawingHeight; this.floorLimits=null; this.numobjects=numobjects; color_first=true; Random r = new Random(); stand_wait_random = (r.nextInt(2)+3)*1000; //ya nai tyxaio plithos milliseconds (1000ms=1sec)!! } public void setFloor(ArrayList<ArrayList<Integer>> limits) { floorLimits=limits; } //ya na ksekinane ola apo tin porta public void init_move(int x_door, int y_door, int x_real_door, int y_real_door) { x=x_door; y=y_door; this.x_real_door=x_real_door; this.y_real_door=y_real_door; } public void move(int i) { //afto ya ta oria tis katopsis twn ekswterikwn toixwn int xleft_f=floorLimits.get(0).get(0)+10; // ta +- 1o einai giati to kathe object exei size = 10 int xright_f=floorLimits.get(0).get(1)-10; int ybottom_f=floorLimits.get(0).get(2)-10; //na shmeiothei oti epeidi ta ytop kai ybottom exoyn kathoristei me ton tropo poy emfanizonte int ytop_f=floorLimits.get(0).get(3)+10; //to ybottom>ytop boolean rand=true; if (i%3 == 1 || i%3 == 2) { //pososto peripoy 66.6% -> !random rand = false; }else { //if () { //posossto peripoy 33.3% -> random rand = true; } if(first) { Scanner s; Path path = Paths.get(productsPath); //products try { s = new Scanner(new File(productsPath)); while (s.hasNext()){ products.add(s.next()); } s.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } try { lines = (int) Files.lines(path).count(); } catch (IOException e) { e.printStackTrace(); } boolean stage[] = new boolean[4]; stage[0]=true; //to stadio mexri na ftasei sto proion stage[1]=false; //to stadio poy kanei voltes stage[2]=false; //to stadio mexri na ftasei sto tameio stage[3]=false; //to stadio poy paei pros tin porta ya na fygei for(int no=0; no<numobjects; no++) { stages.add(stage); } //initialize ya kathe pelati poia katigoria kinisis double rn; for(int n=0; n<numobjects; n++) { rn = Math.random(); if (rn>=0.0 && rn<0.25) { category_moove.add(1); }else if(rn<=0.25 && rn<0.5) { category_moove.add(2); }else if(rn<=0.5 && rn<0.75) { category_moove.add(3); }else { category_moove.add(4); } } //initialize ya kathe pelati an exei profile i oxi String fileProfiles = "C:\\Users\\Σωτηρία\\Desktop\\eclipse-workspace\\simulator\\src\\example_of_simulator\\Floor Plans and Products\\Profiles.txt"; try { s = new Scanner(new File(fileProfiles)); while (s.hasNext()){ profs.add(s.next()); } s.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } for(int p=0; p<profs.size(); p++) { //-1giati i teleftea grammi einai i porta!! String[] pr = profs.get(p).split(","); int id = Integer.parseInt(pr[0]); profile_ids.add(id); } first=false; } if(rand) { random(i, xleft_f, xright_f, ybottom_f, ytop_f); }else { if (x_real_door==450 && y_real_door==600) { random(i, xleft_f, xright_f, ybottom_f, ytop_f); }else { search(i, xleft_f, xright_f, ybottom_f, ytop_f); } } if(first_time) { ArrayList<String> coor_prods = new ArrayList<String>(); coor_prods.add("path in coordinates/time: "); for(int c=0; c<numobjects; c++) { coordinates_products.add(coor_prods); } first_time=false; } coordinates_products.get(i).add("("+x+","+y+")"+"/"+time_per_step); } public void random(int i, int xleft_f, int xright_f, int ybottom_f, int ytop_f) { //afto tha to allaksw se 4 functions kalitera! KAI NA DW POIA KOMMATIA EINAI IDIA YA NA MIN EPANALAMVANO KWDIKA time_per_step = System.nanoTime(); if(y_real_door==(ytop_f-10)) { // if DOOR: PANW y+=dy; int xx=1000; if(i%2==0) { if (stages.get(i)[3]==false) { x+=dx; //0.5*dx; xx=0; } }else { if (stages.get(i)[3]==false) { x-=dx; //0.5*dx; xx=1; } } if (stages.get(i)[3]==true) { if(x<x_real_door) { x+=dx; xx=0; if(x>x_real_door) { x-=dx; xx=1; } }else if(x>x_real_door){ x-=dx; xx=1; if(x<x_real_door) { x+=dx; xx=0; } } else {} y-=1.2*dy; if (x>=x_real_door-10 && y<=y_real_door+10) { y-=15; } } if(x<=xleft_f) { x+=dx; y-=dy; //1; boolean stage[] = new boolean[4]; stage[0]=false; stage[1]=false; stage[2]=false; stage[3]=true; //ya na paei pros tin porta stages.set(i, stage); } if(x>=xright_f) { x-=dx; y-=dy; //1; boolean stage[] = new boolean[4]; stage[0]=false; stage[1]=false; stage[2]=false; stage[3]=true; //ya na paei pros tin porta stages.set(i, stage); } if(x>=1185) { x-=dx; y-=dy; //1; boolean stage[] = new boolean[4]; stage[0]=false; stage[1]=false; stage[2]=false; stage[3]=true; //ya na paei pros tin porta stages.set(i, stage); } if(y>=ybottom_f) { y-=dy; x-=dx; } if(y<=ytop_f) { y+=dy; } for(int j=1; j<floorLimits.size(); j++) { int xleft=floorLimits.get(j).get(0)-10; //-10 to vazoyme giati to obj exei size=10 int xright=floorLimits.get(j).get(1); int ybottom=floorLimits.get(j).get(2); int ytop=floorLimits.get(j).get(3)-10; if (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { y-=dy; //edo ya mia fora ya na afairesei ato poy eixe parei while (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { if(!(ytop==ytop_f || ybottom==ybottom_f)){ y+=dy; }else { y-=dy; } if (xx==0) { x-=dx; } //0.5*dx; } if (xx==1) { x+=dx; } //0.5*dx; } } break; } } }else if(y_real_door==(ybottom_f+10)) { // if DOOR: KATW int yy=1000; int xx=1000; if (i%4==0 || i%4==3) { y-=dy; yy=1; x+=dx; xx=0; if (i%4==0) { if(i==4 || i==12 || i==20 || i==24 || i==32|| i==40 || i==44 || i==52) { if(y>270 && y<300) { if(i==4|| i==20 || i==32 || i==44 || i==52 ) { x-=1.5*dx; xx=1; }else { x-=1.1*dx; xx=1; } y+=dy; yy=0; } }else { if(y>270 && y<330) { if(i==8 || i==28 || i==48 || i==56) { x-=1.3*dx; xx=1; }else { x-=1.8*dx; xx=1; } y+=dy; yy=0; } } }else { if(i==3 || i==11 || i==19 || i==31|| i==39 || i==43 || i==47 ) { if (y>25 && y<35) { if(i==3 || i==19 || i==35 || i==43) { x-=1.9*dx; xx=1; }else { x-=1.45*dx; xx=1; } y+=dy; yy=0; } }else { if (y>20 && y<25) { if(i==7 || i==27 || i==23) { x-=1.3*dx; xx=1; } else { x-=1.85*dx; xx=1; } y+=dy; yy=0; } } } } if (i%4==1 || i%4==2) { y-=dy; yy=1; x-=dx; xx=1; if (i%4==1) { if(i==5 || i==13 || i==25 || i==33 || i==37 || i==45 || i==49) { if(y>250 && y<335) { y+=dy; yy=0; if(i==5 || i==25 || i==45 || i==57) { x+=1.4*dx; xx=0; }else { x+=2*dx; xx=0; } } }else { if(y>250 && y<320) { y+=dy; yy=0; if(i==9 || i==21 || i==41 || i==53) { x+=1.2*dx; xx=0; }else { x+=1.9*dx; xx=0; } } } }else { if(i==2 || i==6 || i==14 || i==18 || i==26 || i==34 || i==38 || i==44 || i==52) { if (y>110 & y<185) { y+=dy; yy=0; if(i==38 || i==44 || i==18 || i==6) { x+=2*dx; xx=0; }else { x+=1.3*dx; xx=0; } } }else { if (y>110 & y<160) { y+=dy; yy=0; if (i==10 || i==40 || i==56 || i==60) { x+=1.8*dx; xx=0; }else { x+=1.2*dx; xx=0; } } } } } /* if (i%2==0) { x+=dx; xx=0; }else { x-=dx; xx=1; } y-=dy; yy=1; if(i%3==0) { if(y>=ybottom_f/2) { if (yy==1) { y+=dy; yy=0; } if (xx==0) { x-=dx; xx=1; }else { x+=dx; xx=0; } }else if (y>=10 && y<=50){ if (yy==1) { y+=dy; yy=0; } if (xx==0) { x-=dx; xx=1; }else { x+=dx; xx=0; } } }*/ /* if(x<=xright_f/2) { if (y>=ybottom_f/2) { if (i%3==0) { x+=dx; xx=0; } }else { if (i%3==1) { x+=dx; xx=0; } } }else { if (y>=ybottom_f/2) { if (i%3==2) { x-=dx; xx=1; } } } */ if(x<=xleft_f) { // if(y>ybottom_f/2) { x+=dx; xx=0; y-=dy; yy=1; } if(x>=xright_f) { // if(y>ybottom_f/2) { x-=dx; xx=1; y-=dy; yy=1; } if(y<=ytop_f) { y+=dy; yy=0; if (xx==0) { x-=dx; xx=1; } else if (xx==1) { x+=dx; xx=0; } } if(y>=ybottom_f) { y-=dy; yy=1; if (xx==0) { x-=dx; xx=1; } else if (xx==1) { x+=dx; xx=0; } } for(int j=1; j<floorLimits.size(); j++) { int xleft=floorLimits.get(j).get(0)-10; //-10 to vazoyme giati to obj exei size=10 int xright=floorLimits.get(j).get(1); int ybottom=floorLimits.get(j).get(2); int ytop=floorLimits.get(j).get(3)-10; if (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { if(x<=561 && x>=539) { while (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { y-=dy; if (xx==0) { x-=dx; } //0.5*dx; } if (xx==1) { x+=dx; } } break; }else { if (yy==0) { y-=dy; } if (yy==1) { y+=dy; } while (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { if(i%2==0) { if (j%2==0) { y-=dy; }else { y+=dy; } }else { y+=dy; } if (xx==0) { x+=dx; } //0.5*dx; } if (xx==1) { x-=dx; } //0.5*dx; } } break; } } } }else if(x_real_door==(xleft_f-10)) { // if DOOR : LEFT x+=dx; int xx=1000; if (i%2==1) { y+=dy; xx=0; }else { y-=dy; xx=1; } if(x>=xright_f) { x-=dx; } if(x<=xleft_f) { x+=dx; } if(y>=ybottom_f) { y-=dy; } if(y<=ytop_f) { y+=dy; } for(int j=1; j<floorLimits.size(); j++) { int xleft=floorLimits.get(j).get(0)-10; //-10 to vazoyme giati to obj exei size=10 int xright=floorLimits.get(j).get(1); int ybottom=floorLimits.get(j).get(2); int ytop=floorLimits.get(j).get(3)-10; if (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { x-=dx; while (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { x+=dx; if (xx==0) { y-=dy; } if (xx==1) { y+=dy; } } break; } } }else if(x_real_door==(xright_f+10)) { // if DOOR : RIGHT x-=dx; int xx=1000; if (i%2==0) { y+=dy; xx=0; }else { y-=dy; xx=1; } if(x<=xleft_f) { x+=dx; } if(x>=xright_f) { x-=dx; } if(y>=ybottom_f) { y-=dy; } if(y<=ytop_f) { y+=dy; } for(int j=1; j<floorLimits.size(); j++) { int xleft=floorLimits.get(j).get(0)-10; //-10 to vazoyme giati to obj exei size=10 int xright=floorLimits.get(j).get(1); int ybottom=floorLimits.get(j).get(2); int ytop=floorLimits.get(j).get(3)-10; if (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { x+=dx; while (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { x-=dx; if (xx==0) { y-=dy; } if (xx==1) { y+=dy; } } break; } } } } public void search(int i, int xleft_f, int xright_f, int ybottom_f, int ytop_f) { time_per_step = System.nanoTime(); double dxp = 0.0; double dyp = 0.0; if(initialize_products) { for(int p=0; p<numobjects; p++) { String sel[]= new String[3]; sel[0]="no"; select_product.add(sel); } initialize_products=false; } if(select_product.get(i)[0].equals("no")) { //tha epilegei tyxaia mia grammi apo to arxeio me ta proionta //kai meta mono afti tha vriskei pio einai to produuct //den xreiazete na diatrexei olo ton pinaka me ta proionta ///1st way: me tin random dialego enan integer apo 0 mexri to #lines toy arxeiou //kai meta pigeneo stin antistixi thesi toy products lalala int product_number = (int)(Math.random() * lines); String[] productp = products.get(product_number).split(","); String categoryp=productp[4]; String xp = productp[2].substring(1); String yp = productp[3].substring(0,productp[3].length()-1); String info_product[] = new String[3]; info_product[0] = categoryp; info_product[1] = xp; info_product[2] = yp; select_product.set(i,info_product); }else { //dld an exoyn vrei product ya na pane pros ta ekei dxp = Double.parseDouble(select_product.get(i)[1]); dyp = Double.parseDouble(select_product.get(i)[2]); } if(profile_ids.contains(i)) { //ara pigainei i pros katigoria polysyxnasti i pros polysyxnasto eidos proion poy exei agorasei!! //random category //prepei na vrei to polysyxnasto proion kai thn polysyxnasti katigoria //kai meta tyxaia kapoia na kinithoyn me vasi to proion(alla oysiastika katigoria poy anikei) kai me vasi tin katigoria int position = profile_ids.indexOf(i); //ya na vro tin thesi sto profile ids kathos ine idia me tin thesi sto profs!!! String[] ctg_prds = profs.get(position).split(","); String[] ctgs = ctg_prds[2].split("/"); //tora afto to kanw ya na do to plithos ton emfanisewn kathe katigorias proiontwn //isos ine ligo poly fail - L O L - ArrayList<String[]> ctgs_al = new ArrayList<String[]>(); for(int ct=0; ct<ctgs.length; ct++) { if(!ctgs_al.contains(ctgs[ct])) { String lala[] = new String[2]; lala[0]=ctgs[ct]; lala[1]=Integer.toString(1); ctgs_al.add(lala); }else { int pos = ctgs_al.indexOf(ctgs[ct]); String lolo[] = new String[2]; lolo[0]=ctgs[ct]; int xa=Integer.parseInt(ctgs_al.get(pos)[1])+1; lolo[1]=Integer.toString(xa); ctgs_al.set(pos, lolo); } } int max=0; int maxposition=0; for(int m=0; m<ctgs_al.size(); m++) { if(max > Integer.parseInt(ctgs_al.get(m)[1])) { max = Integer.parseInt(ctgs_al.get(m)[1]); maxposition=m; } } //kai tora se afto to simeio exoyme tin pio polysuxnasti ya to kathe pelati me profile katigoria proiontwn //SYNEPWS arkei na exoyme ena arraylist me tin kathe katigoria poies einai oi syntetagmenes tis //ya efkolia ya kathe katigoria tha valw kapoia enddeiktika simeia poy simenei oti pigenei se ena proion aftis tis katigorias double x_category=0.0; double y_category=0.0; for(int cps=0; cps<category_product.length; cps++) { if(category_product[cps][0]==ctgs_al.get(maxposition)[0]) { String[] category_coordinates = category_product[cps][1].split(","); x_category = Double.parseDouble(category_coordinates[0]); y_category = Double.parseDouble(category_coordinates[1]); } } if(category_moove.get(i)==1) { category1(i, xleft_f, xright_f, ybottom_f, ytop_f, x_category, y_category); }else if (category_moove.get(i)==2) { category2(i, xleft_f, xright_f, ybottom_f, ytop_f, x_category, y_category); }else if (category_moove.get(i)==3) { category3(i, xleft_f, xright_f, ybottom_f, ytop_f, x_category, y_category); }else if (category_moove.get(i)==4) { category1(i, xleft_f, xright_f, ybottom_f, ytop_f, x_category, y_category); } }else { //random category if(dxp!=0.0 && dyp!=0.0) { if(category_moove.get(i)==1) { category1(i, xleft_f, xright_f, ybottom_f, ytop_f, dxp, dyp); }else if (category_moove.get(i)==2) { category2(i, xleft_f, xright_f, ybottom_f, ytop_f, dxp, dyp); }else if (category_moove.get(i)==3) { category3(i, xleft_f, xright_f, ybottom_f, ytop_f, dxp, dyp); }else if (category_moove.get(i)==4) { category2(i, xleft_f, xright_f, ybottom_f, ytop_f, dxp, dyp); } } } } //afta doylevoyn mono sti periptosi poy i porta einai panw deksia public void category1(int i, int xleft_f, int xright_f, int ybottom_f, int ytop_f, double dxp, double dyp) { //epilegei proion-> tameio -> fevgei if(dxp < x_real_door) { //1st case //if ya stadia kai analoga na paei pros tin antistoixi katefthinsi //prepei na ta kanei me tin seira ara tha ecxo 3 metavlites tis opoies px otan ftasei sto proion tha kanei true afti poy einai ya na paei sto tameio//meta otan tha ftastei sto tameio tha kanei true afti poy einai ya na fygei//kai ennoeite i proti poy tha mpainei tha nai i true metavliti mexri na ftasei k me to poy ftanei tin kanei false ya na min ksanampei //eite mporoyme na exoume enan array 2d me 3 theseis ya kathe boolean metavliti toy analogoy stadioy//opoy i kathe thesi toy array tha antistoixei se kathe object//giati den ginete na xoyme mia ksexoy metavliti boolean kathos trexei afti i sinartisi ya kathe vima kathe antikimenoy!! int xx=1000; //xx=0 -> x+=dx alliws xx=1 -> x-=dx, ara meta an xx=0 -> x-=dx k an xx=1 -> x+=dx int yy=1000; if (stages.get(i)[0]==true) { //dld an einai sto stadio poy prospathei na paei pros to proion if(x>dxp) { x-=dx; xx=1; } if(y<dyp) { y+=dy; yy=0; } if(x<=dxp && y>=dyp) { //shmainei oti efase sto prooion boolean stage[] = new boolean[4]; stage[0]=false; //afto to kanoyme false giati den eimaste allo se afto to stadio stage[1]=false; //afto to afinoyme ws exxei giati einai afto poy synexizei tin volta sto katastima stage[2]=true; //afto to allazoyme se true giati imaste se afto to stadio poy theloyme na paei sto tameio stage[3]=false; //to afisnoyme ws exei stages.set(i, stage); long ws_end = System.currentTimeMillis(); stand_wait = ws_end - start_time; while (stand_wait < stand_wait_search) { //ms x+=0.01; x-=0.01; y+=0.01; y-=0.01; ws_end = System.nanoTime(); stand_wait = ws_end - start_time; } } } //afto okei, to allazo na lew oti i morfi toy arxeioy exei sugkekrimeni tami to tameio -> proteleftea -> prin tin porta!!! if(stages.get(i)[2]==true) { //dld mexri na paei sto tameio //to tameio einai ya x>=1200 kai ta y poy mporei na paei einai [170,235], [285,355], [405,470] if(x<1200-10) { x+=dx; xx=0; } if(y<235+10) { y+=dy; yy=0; } if(y>470) { y-=dy; yy=1; } if(x>=1200-10 && (y<=470 || y>=170+10)) { boolean stage[] = new boolean[4]; stage[0]=false; stage[1]=false; stage[2]=false; stage[3]=true; //ya na paei pros tin porta long ws_end = System.currentTimeMillis(); stand_wait = ws_end - start_time; while (stand_wait < stand_wait_search) { //ms x+=0.01; x-=0.01; y+=0.01; y-=0.01; ws_end = System.nanoTime(); stand_wait = ws_end - start_time; } stages.set(i, stage); } } if (stages.get(i)[3]==true) { if(x<=x_real_door) { x+=dx; xx=0; if(x>=x_real_door) { x-=dx; xx=1; } }else { x-=dx; xx=1; if(x<=x_real_door) { x+=dx; xx=0; } } if(y>y_real_door) { y-=dy; yy=1; } if (x>=x_real_door-10 && y<=y_real_door+10) { y-=15; } } //Oi parakatw elegxoi ya ta eswterika empodia k tin katopsi tha nai idioi kai ya ta 3 stadia (proion, tameio, fevgei) //afta einai ya ta oria tis katopsis //synepws aftoi oi elegxoi tha ginonte sto teleos meta tis if ya na doyme se poio stadio vriskomaste!!! if(x<=xleft_f) { x+=dx; xx=0; y-=dy; //giati door panw boolean stage[] = new boolean[4]; if(i%2==1) { //na paei tameio stage[0]=false; stage[1]=false; stage[2]=true; stage[3]=false; long ws_end =System.currentTimeMillis(); stand_wait = ws_end - start_time; while (stand_wait < stand_wait_search) { //ms x+=0.01; x-=0.01; y+=0.01; y-=0.01; ws_end = System.nanoTime(); stand_wait = ws_end - start_time; } stages.set(i, stage); } else { stage[0]=false; stage[1]=false; stage[2]=false; stage[3]=true; //alliws na fygoyn oi alloi misoi long ws_end = System.currentTimeMillis(); stand_wait = ws_end - start_time; while (stand_wait < stand_wait_search) { //ms x+=0.01; x-=0.01; y+=0.01; y-=0.01; ws_end = System.nanoTime(); stand_wait = ws_end - start_time; } stages.set(i, stage); } } if(x>=xright_f) { x-=dx; xx=1; y-=dy; yy=1; } if(y>=ybottom_f) { y-=dy; yy=1; x-=dx; xx=1; } if(y<=ytop_f) { if(stages.get(i)[3]==false) { y+=dy; yy=0; } } for(int j=1; j<floorLimits.size(); j++) { int xleft=floorLimits.get(j).get(0)-10; //-10 to vazoyme giati to obj exei size=10 int xright=floorLimits.get(j).get(1); int ybottom=floorLimits.get(j).get(2); int ytop=floorLimits.get(j).get(3)-10; if (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { if (yy==0) { y-=dy; } if (yy==1) { y+=dy; } while (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { /* if (yy==0) { y+=dy; } //sto y einai i idia antistoixia, giati theloyme na synexisoyn stin poreia poy pigenan if (yy==1) { y-=dy; }*/ //afto ya na yparxei poikilia ana stand k ana pelati if(i%2==0) { if (j%2==0) { y-=dy; }else { y+=dy; } }else { y+=dy; } if (xx==0) { x-=dx; } //0.5*dx; } if (xx==1) { x+=dx; } //0.5*dx; } } break; } } //NA DW MIPOS AFTOS O TROPOS YA TA ESWTERIKA EMPODIA DINEI KALITERI KINISI!!!!!!!!! /* for(int j=1; j<floorLimits.size(); j++) { int xleft=floorLimits.get(j).get(0)-10; //-10 to vazoyme giati to obj exei size=10 int xright=floorLimits.get(j).get(1); int ybottom=floorLimits.get(j).get(2); int ytop=floorLimits.get(j).get(3)-10; if (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { if(stages.get(i)[0]==true) { if (y>dyp) { y-=dy; }else { y+=dy; } }else if(stages.get(i)[2]==true) { if (y>300) { y-=dy; }else { y+=dy; } }else if(stages.get(i)[3]==true) { if (y>y_real_door) { y-=dy; }else { y+=dy; } }else {} while (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { if(stages.get(i)[0]==true) { //pros proion if (x>dxp) { x-=dx; }else { x+=dx; } if (y>dyp) { y-=dy; }else { y+=dy; } } else if (stages.get(i)[2]==true) { //pros tameio if (x>1200-10) { x-=dx; }else { x+=dx; } if (y>300) { y-=dy; }else { y+=dy; } } else if (stages.get(i)[3]==true) { //pros porta if (x>x_real_door) { x-=dx; }else { x+=dx; } if (y>y_real_door) { y-=dy; }else { y+=dy; } }else {} } break; } }*/ }else { //if (dxp>=x_real_door) int xx=1000; //xx=0 -> x+=dx alliws xx=1 -> x-=dx, ara meta an xx=0 -> x-=dx k an xx=1 -> x+=dx int yy=1000; //edw to proion vriskete pio deksia tis portas, ara me to poy mpainei o pelatis simenei oti to x toy ine mikrotero apo to proion, afoy mpainei apo tin porta!!! if (stages.get(i)[0]==true) { //proion if(x<dxp) { //if dxp>x_real_door, an ine iso den xreiazete na kanei kati exei vrei idi to swsto x!!! x+=dx; xx=0; } if(y<dyp) { y+=dy; yy=0; } //ara allazo kai edo prepei x>=dxp ya na simenei oti eftase!!, efoson pigene apo aristera pros deksia !! //to y idio giati ola ta proionta katw apo tin door if(x>=dxp && y>=dyp) { //shmainei oti efase sto prooion boolean stage[] = new boolean[4]; stage[0]=false; //afto to kanoyme false giati den eimaste allo se afto to stadio stage[1]=false; //afto to afinoyme ws exxei giati einai afto poy synexizei tin volta sto katastima stage[2]=true; //afto to allazoyme se true giati imaste se afto to stadio poy theloyme na paei sto tameio stage[3]=false; //to afisnoyme ws exei stages.set(i, stage); long ws_end = System.currentTimeMillis(); stand_wait = ws_end - start_time; while (stand_wait < stand_wait_search) { //ms x+=0.01; x-=0.01; y+=0.01; y-=0.01; ws_end = System.nanoTime(); stand_wait = ws_end - start_time; } } } //afto okei, to allazo na lew oti i morfi toy arxeioy exei sugkekrimeni tami to tameio -> proteleftea -> prin tin porta!!! if(stages.get(i)[2]==true) { //dld mexri na paei sto tameio //to tameio einai ya x>=1200 kai ta y poy mporei na paei einai [170,235], [285,355], [405,470] if(x<1200-10) { x+=dx; xx=0; } if(y<235+10) { y+=dy; yy=0; } if(y>470) { y-=dy; yy=1; } if(x>=1200-10 && (y<=470 || y>=170+10)) { boolean stage[] = new boolean[4]; stage[0]=false; stage[1]=false; stage[2]=false; stage[3]=true; //ya na paei pros tin porta long ws_end = System.currentTimeMillis(); stand_wait = ws_end - start_time; while (stand_wait < stand_wait_search) { //ms x+=0.01; x-=0.01; y+=0.01; y-=0.01; ws_end = System.nanoTime(); stand_wait = ws_end - start_time; } stages.set(i, stage); } } if (stages.get(i)[3]==true) { //porta if(x<=x_real_door) { x+=dx; xx=0; if(x>=x_real_door) { x-=dx; xx=1; } }else { x-=dx; xx=1; if(x<=x_real_door) { x+=dx; xx=0; } } if(y>y_real_door) { y-=dy; yy=1; } if (x>=x_real_door-10 && y<=y_real_door+10) { y-=15; } } //Oi parakatw elegxoi ya ta eswterika empodia k tin katopsi tha nai idioi kai ya ta 3 stadia (proion, tameio, fevgei) //afta einai ya ta oria tis katopsis //synepws aftoi oi elegxoi tha ginonte sto teleos meta tis if ya na doyme se poio stadio vriskomaste!!! if(x<=xleft_f) { x+=dx; xx=0; y-=dy; //giati door panw boolean stage[] = new boolean[4]; if(i%2==1) { //na paei tameio stage[0]=false; stage[1]=false; stage[2]=true; stage[3]=false; long ws_end =System.currentTimeMillis(); stand_wait = ws_end - start_time; while (stand_wait < stand_wait_search) { //ms x+=0.01; x-=0.01; y+=0.01; y-=0.01; ws_end = System.nanoTime(); stand_wait = ws_end - start_time; } stages.set(i, stage); } else { stage[0]=false; stage[1]=false; stage[2]=false; stage[3]=true; //alliws na fygoyn oi alloi misoi long ws_end = System.currentTimeMillis(); stand_wait = ws_end - start_time; while (stand_wait < stand_wait_search) { //ms x+=0.01; x-=0.01; y+=0.01; y-=0.01; ws_end = System.nanoTime(); stand_wait = ws_end - start_time; } stages.set(i, stage); } } if(x>=xright_f) { x-=dx; xx=1; y-=dy; yy=1; } if(y>=ybottom_f) { y-=dy; yy=1; x-=dx; xx=1; } if(y<=ytop_f) { if(stages.get(i)[3]==false) { y+=dy; yy=0; } } for(int j=1; j<floorLimits.size(); j++) { int xleft=floorLimits.get(j).get(0)-10; //-10 to vazoyme giati to obj exei size=10 int xright=floorLimits.get(j).get(1); int ybottom=floorLimits.get(j).get(2); int ytop=floorLimits.get(j).get(3)-10; if (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { if (yy==0) { y-=dy; } if (yy==1) { y+=dy; } while (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { /* if (yy==0) { y+=dy; } //sto y einai i idia antistoixia, giati theloyme na synexisoyn stin poreia poy pigenan if (yy==1) { y-=dy; }*/ //afto ya na yparxei poikilia ana stand k ana pelati if(i%2==0) { if (j%2==0) { y-=dy; }else { y+=dy; } }else { y+=dy; } if (xx==0) { x-=dx; } //0.5*dx; } if (xx==1) { x+=dx; } //0.5*dx; } } break; } } } } public void category2(int i, int xleft_f, int xright_f, int ybottom_f, int ytop_f, double dxp, double dyp) { //epilegei proion->volta katastima->tameio->fevgei //idio me categoyry1 mono poy apo to stage[0] tora prin paei sto stage[2] pernaei prota apo to stage[1]. Dld stage[0]-> [1] -> [2] -> [3] if(dxp < x_real_door) { //1st case //if ya stadia kai analoga na paei pros tin antistoixi katefthinsi //prepei na ta kanei me tin seira ara tha ecxo 3 metavlites tis opoies px otan ftasei sto proion tha kanei true afti poy einai ya na paei sto tameio//meta otan tha ftastei sto tameio tha kanei true afti poy einai ya na fygei//kai ennoeite i proti poy tha mpainei tha nai i true metavliti mexri na ftasei k me to poy ftanei tin kanei false ya na min ksanampei //eite mporoyme na exoume enan array 2d me 3 theseis ya kathe boolean metavliti toy analogoy stadioy//opoy i kathe thesi toy array tha antistoixei se kathe object//giati den ginete na xoyme mia ksexoy metavliti boolean kathos trexei afti i sinartisi ya kathe vima kathe antikimenoy!! int xx=1000; //xx=0 -> x+=dx alliws xx=1 -> x-=dx, ara meta an xx=0 -> x-=dx k an xx=1 -> x+=dx int yy=1000; if (stages.get(i)[0]==true) { //dld an einai sto stadio poy prospathei na paei pros to proion if(x>dxp) { x-=dx; xx=1; } if(y<dyp) { y+=dy; yy=0; } if(x<=dxp && y>=dyp) { //shmainei oti efase sto prooion boolean stage[] = new boolean[4]; stage[0]=false; //afto to kanoyme false giati den eimaste allo se afto to stadio stage[1]=true; //afto to afinoyme ws exxei giati einai afto poy synexizei tin volta sto katastima stage[2]=false; //afto to allazoyme se true giati imaste se afto to stadio poy theloyme na paei sto tameio stage[3]=false; //to afisnoyme ws exei stages.set(i, stage); long ws_end = System.currentTimeMillis(); stand_wait = ws_end - start_time; while (stand_wait < stand_wait_search) { //ms x+=0.01; x-=0.01; y+=0.01; y-=0.01; ws_end = System.nanoTime(); stand_wait = ws_end - start_time; } } } if (stages.get(i)[1]==true) { //dld an einai sto stadio poy prospathei na paei pros to proion if(first_random) { first_random_time1 = System.currentTimeMillis(); first_random_time2 = System.currentTimeMillis(); first_random_time = first_random_time2 - first_random_time1; Random r = new Random(); first_random_wait = (r.nextInt(4)+5)*1000; //ya nai tyxaio plithos milliseconds (1000ms=1sec) kai na nai sigoyra > 5 seconds first_random = false; } first_random_time2 = System.currentTimeMillis(); first_random_time = first_random_time2 - first_random_time1; if(first_random_time > first_random_wait) { boolean stage[] = new boolean[4]; stage[0]=false; //afto to kanoyme false giati den eimaste allo se afto to stadio stage[1]=false; //afto to afinoyme ws exxei giati einai afto poy synexizei tin volta sto katastima stage[2]=true; //afto to allazoyme se true giati imaste se afto to stadio poy theloyme na paei sto tameio stage[3]=false; //to afisnoyme ws exei stages.set(i, stage); }else { random(i, xleft_f, xright_f, ybottom_f, ytop_f); } } //afto okei, to allazo na lew oti i morfi toy arxeioy exei sugkekrimeni tami to tameio -> proteleftea -> prin tin porta!!! if(stages.get(i)[2]==true) { //dld mexri na paei sto tameio //to tameio einai ya x>=1200 kai ta y poy mporei na paei einai [170,235], [285,355], [405,470] if(x<1200-10) { x+=dx; xx=0; } if(y<235+10) { y+=dy; yy=0; } if(y>470) { y-=dy; yy=1; } if(x>=1200-10 && (y<=470 || y>=170+10)) { boolean stage[] = new boolean[4]; stage[0]=false; stage[1]=false; stage[2]=false; stage[3]=true; //ya na paei pros tin porta long ws_end = System.currentTimeMillis(); stand_wait = ws_end - start_time; while (stand_wait < stand_wait_search) { //ms x+=0.01; x-=0.01; y+=0.01; y-=0.01; ws_end = System.nanoTime(); stand_wait = ws_end - start_time; } stages.set(i, stage); } } if (stages.get(i)[3]==true) { if(x<=x_real_door) { x+=dx; xx=0; if(x>=x_real_door) { x-=dx; xx=1; } }else { x-=dx; xx=1; if(x<=x_real_door) { x+=dx; xx=0; } } if(y>y_real_door) { y-=dy; yy=1; } if (x>=x_real_door-10 && y<=y_real_door+10) { y-=15; } } if(x<=xleft_f) { x+=dx; xx=0; y-=dy; //giati door panw boolean stage[] = new boolean[4]; if(i%2==1) { //na paei tameio stage[0]=false; stage[1]=false; stage[2]=true; stage[3]=false; long ws_end =System.currentTimeMillis(); stand_wait = ws_end - start_time; while (stand_wait < stand_wait_search) { //ms x+=0.01; x-=0.01; y+=0.01; y-=0.01; ws_end = System.nanoTime(); stand_wait = ws_end - start_time; } stages.set(i, stage); } else { stage[0]=false; stage[1]=false; stage[2]=false; stage[3]=true; //alliws na fygoyn oi alloi misoi long ws_end = System.currentTimeMillis(); stand_wait = ws_end - start_time; while (stand_wait < stand_wait_search) { //ms x+=0.01; x-=0.01; y+=0.01; y-=0.01; ws_end = System.nanoTime(); stand_wait = ws_end - start_time; } stages.set(i, stage); } } if(x>=xright_f) { x-=dx; xx=1; y-=dy; yy=1; } if(y>=ybottom_f) { y-=dy; yy=1; x-=dx; xx=1; } if(y<=ytop_f) { if(stages.get(i)[3]==false) { y+=dy; yy=0; } } for(int j=1; j<floorLimits.size(); j++) { int xleft=floorLimits.get(j).get(0)-10; //-10 to vazoyme giati to obj exei size=10 int xright=floorLimits.get(j).get(1); int ybottom=floorLimits.get(j).get(2); int ytop=floorLimits.get(j).get(3)-10; if (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { if (yy==0) { y-=dy; } if (yy==1) { y+=dy; } while (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { if(i%2==0) { if (j%2==0) { y-=dy; }else { y+=dy; } }else { y+=dy; } if (xx==0) { x-=dx; } //0.5*dx; } if (xx==1) { x+=dx; } //0.5*dx; } } break; } } }else { //if (dxp>=x_real_door) int xx=1000; //xx=0 -> x+=dx alliws xx=1 -> x-=dx, ara meta an xx=0 -> x-=dx k an xx=1 -> x+=dx int yy=1000; //edw to proion vriskete pio deksia tis portas, ara me to poy mpainei o pelatis simenei oti to x toy ine mikrotero apo to proion, afoy mpainei apo tin porta!!! if (stages.get(i)[0]==true) { //dld an einai sto stadio poy prospathei na paei pros to proion if(x<dxp) { x+=dx; xx=0; } if(y<dyp) { y+=dy; yy=0; } if(x>=dxp && y>=dyp) { //shmainei oti efase sto prooion boolean stage[] = new boolean[4]; stage[0]=false; //afto to kanoyme false giati den eimaste allo se afto to stadio stage[1]=true; //afto to afinoyme ws exxei giati einai afto poy synexizei tin volta sto katastima stage[2]=false; //afto to allazoyme se true giati imaste se afto to stadio poy theloyme na paei sto tameio stage[3]=false; //to afisnoyme ws exei stages.set(i, stage); long ws_end = System.currentTimeMillis(); stand_wait = ws_end - start_time; while (stand_wait < stand_wait_search) { //ms x+=0.01; x-=0.01; y+=0.01; y-=0.01; ws_end = System.nanoTime(); stand_wait = ws_end - start_time; } } } if (stages.get(i)[1]==true) { //dld an einai sto stadio poy prospathei na paei pros to proion if(first_random) { first_random_time1 = System.currentTimeMillis(); first_random_time2 = System.currentTimeMillis(); first_random_time = first_random_time2 - first_random_time1; Random r = new Random(); first_random_wait = (r.nextInt(4)+5)*1000; //ya nai tyxaio plithos milliseconds (1000ms=1sec) kai na nai sigoyra > 5 seconds first_random = false; } first_random_time2 = System.currentTimeMillis(); first_random_time = first_random_time2 - first_random_time1; if(first_random_time > first_random_wait) { boolean stage[] = new boolean[4]; stage[0]=false; //afto to kanoyme false giati den eimaste allo se afto to stadio stage[1]=false; //afto to afinoyme ws exxei giati einai afto poy synexizei tin volta sto katastima stage[2]=true; //afto to allazoyme se true giati imaste se afto to stadio poy theloyme na paei sto tameio stage[3]=false; //to afisnoyme ws exei stages.set(i, stage); }else { random(i, xleft_f, xright_f, ybottom_f, ytop_f); } } //afto okei, to allazo na lew oti i morfi toy arxeioy exei sugkekrimeni tami to tameio -> proteleftea -> prin tin porta!!! if(stages.get(i)[2]==true) { //dld mexri na paei sto tameio //to tameio einai ya x>=1200 kai ta y poy mporei na paei einai [170,235], [285,355], [405,470] if(x<1200-10) { x+=dx; xx=0; } if(y<235+10) { y+=dy; yy=0; } if(y>470) { y-=dy; yy=1; } if(x>=1200-10 && (y<=470 || y>=170+10)) { boolean stage[] = new boolean[4]; stage[0]=false; stage[1]=false; stage[2]=false; stage[3]=true; //ya na paei pros tin porta long ws_end = System.currentTimeMillis(); stand_wait = ws_end - start_time; while (stand_wait < stand_wait_search) { //ms x+=0.01; x-=0.01; y+=0.01; y-=0.01; ws_end = System.nanoTime(); stand_wait = ws_end - start_time; } stages.set(i, stage); } } if (stages.get(i)[3]==true) { //porta if(x<=x_real_door) { x+=dx; xx=0; if(x>=x_real_door) { x-=dx; xx=1; } }else { x-=dx; xx=1; if(x<=x_real_door) { x+=dx; xx=0; } } if(y>y_real_door) { y-=dy; yy=1; } if (x>=x_real_door-10 && y<=y_real_door+10) { y-=15; } } //Oi parakatw elegxoi ya ta eswterika empodia k tin katopsi tha nai idioi kai ya ta 3 stadia (proion, tameio, fevgei) //afta einai ya ta oria tis katopsis //synepws aftoi oi elegxoi tha ginonte sto teleos meta tis if ya na doyme se poio stadio vriskomaste!!! if(x<=xleft_f) { x+=dx; xx=0; y-=dy; //giati door panw boolean stage[] = new boolean[4]; if(i%2==1) { //na paei tameio stage[0]=false; stage[1]=false; stage[2]=true; stage[3]=false; long ws_end =System.currentTimeMillis(); stand_wait = ws_end - start_time; while (stand_wait < stand_wait_search) { //ms x+=0.01; x-=0.01; y+=0.01; y-=0.01; ws_end = System.nanoTime(); stand_wait = ws_end - start_time; } stages.set(i, stage); } else { stage[0]=false; stage[1]=false; stage[2]=false; stage[3]=true; //alliws na fygoyn oi alloi misoi long ws_end = System.currentTimeMillis(); stand_wait = ws_end - start_time; while (stand_wait < stand_wait_search) { //ms x+=0.01; x-=0.01; y+=0.01; y-=0.01; ws_end = System.nanoTime(); stand_wait = ws_end - start_time; } stages.set(i, stage); } } if(x>=xright_f) { x-=dx; xx=1; y-=dy; yy=1; } if(y>=ybottom_f) { y-=dy; yy=1; x-=dx; xx=1; } if(y<=ytop_f) { if(stages.get(i)[3]==false) { y+=dy; yy=0; } } for(int j=1; j<floorLimits.size(); j++) { int xleft=floorLimits.get(j).get(0)-10; //-10 to vazoyme giati to obj exei size=10 int xright=floorLimits.get(j).get(1); int ybottom=floorLimits.get(j).get(2); int ytop=floorLimits.get(j).get(3)-10; if (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { if (yy==0) { y-=dy; } if (yy==1) { y+=dy; } while (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { /* if (yy==0) { y+=dy; } //sto y einai i idia antistoixia, giati theloyme na synexisoyn stin poreia poy pigenan if (yy==1) { y-=dy; }*/ //afto ya na yparxei poikilia ana stand k ana pelati if(i%2==0) { if (j%2==0) { y-=dy; }else { y+=dy; } }else { y+=dy; } if (xx==0) { x-=dx; } //0.5*dx; } if (xx==1) { x+=dx; } //0.5*dx; } } break; } } } } public void category3(int i, int xleft_f, int xright_f, int ybottom_f, int ytop_f, double dxp, double dyp) { //epilegei proion->fevge (oxi tameio, dld den to agorazei) //dld apo stage[0] -> stage[3] if(dxp < x_real_door) { //1st case //if ya stadia kai analoga na paei pros tin antistoixi katefthinsi //prepei na ta kanei me tin seira ara tha ecxo 3 metavlites tis opoies px otan ftasei sto proion tha kanei true afti poy einai ya na paei sto tameio//meta otan tha ftastei sto tameio tha kanei true afti poy einai ya na fygei//kai ennoeite i proti poy tha mpainei tha nai i true metavliti mexri na ftasei k me to poy ftanei tin kanei false ya na min ksanampei //eite mporoyme na exoume enan array 2d me 3 theseis ya kathe boolean metavliti toy analogoy stadioy//opoy i kathe thesi toy array tha antistoixei se kathe object//giati den ginete na xoyme mia ksexoy metavliti boolean kathos trexei afti i sinartisi ya kathe vima kathe antikimenoy!! int xx=1000; //xx=0 -> x+=dx alliws xx=1 -> x-=dx, ara meta an xx=0 -> x-=dx k an xx=1 -> x+=dx int yy=1000; if (stages.get(i)[0]==true) { //dld an einai sto stadio poy prospathei na paei pros to proion if(x>dxp) { x-=dx; xx=1; } if(y<dyp) { y+=dy; yy=0; } if(x<=dxp && y>=dyp) { //shmainei oti efase sto prooion boolean stage[] = new boolean[4]; stage[0]=false; stage[1]=false; stage[2]=false; stage[3]=true; stages.set(i, stage); long ws_end = System.currentTimeMillis(); stand_wait = ws_end - start_time; while (stand_wait < stand_wait_search) { //ms x+=0.01; x-=0.01; y+=0.01; y-=0.01; ws_end = System.nanoTime(); stand_wait = ws_end - start_time; } } } if (stages.get(i)[3]==true) { if(x<=x_real_door) { x+=dx; xx=0; if(x>=x_real_door) { x-=dx; xx=1; } }else { x-=dx; xx=1; if(x<=x_real_door) { x+=dx; xx=0; } } if(y>y_real_door) { y-=dy; yy=1; } if (x>=x_real_door-10 && y<=y_real_door+10) { y-=15; } } if(x<=xleft_f) { x+=dx; xx=0; y-=dy; //giati door panw boolean stage[] = new boolean[4]; stage[0]=false; stage[1]=false; stage[2]=false; stage[3]=true; long ws_end =System.currentTimeMillis(); stand_wait = ws_end - start_time; while (stand_wait < stand_wait_search) { //ms x+=0.01; x-=0.01; y+=0.01; y-=0.01; ws_end = System.nanoTime(); stand_wait = ws_end - start_time; } stages.set(i, stage); } if(x>=xright_f) { x-=dx; xx=1; y-=dy; yy=1; } if(y>=ybottom_f) { y-=dy; yy=1; x-=dx; xx=1; } if(y<=ytop_f) { if(stages.get(i)[3]==false) { y+=dy; yy=0; } } for(int j=1; j<floorLimits.size(); j++) { int xleft=floorLimits.get(j).get(0)-10; //-10 to vazoyme giati to obj exei size=10 int xright=floorLimits.get(j).get(1); int ybottom=floorLimits.get(j).get(2); int ytop=floorLimits.get(j).get(3)-10; if (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { if (yy==0) { y-=dy; } if (yy==1) { y+=dy; } while (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { if(i%2==0) { if (j%2==0) { y-=dy; }else { y+=dy; } }else { y+=dy; } if (xx==0) { x-=dx; } //0.5*dx; } if (xx==1) { x+=dx; } //0.5*dx; } } break; } } }else { //if (dxp>=x_real_door) int xx=1000; //xx=0 -> x+=dx alliws xx=1 -> x-=dx, ara meta an xx=0 -> x-=dx k an xx=1 -> x+=dx int yy=1000; //edw to proion vriskete pio deksia tis portas, ara me to poy mpainei o pelatis simenei oti to x toy ine mikrotero apo to proion, afoy mpainei apo tin porta!!! if (stages.get(i)[0]==true) { //dld an einai sto stadio poy prospathei na paei pros to proion if(x<dxp) { x+=dx; xx=0; } if(y<dyp) { y+=dy; yy=0; } if(x>=dxp && y>=dyp) { //shmainei oti efase sto prooion boolean stage[] = new boolean[4]; stage[0]=false; //afto to kanoyme false giati den eimaste allo se afto to stadio stage[1]=false; //afto to afinoyme ws exxei giati einai afto poy synexizei tin volta sto katastima stage[2]=false; //afto to allazoyme se true giati imaste se afto to stadio poy theloyme na paei sto tameio stage[3]=true; //to afisnoyme ws exei stages.set(i, stage); long ws_end = System.currentTimeMillis(); stand_wait = ws_end - start_time; while (stand_wait < stand_wait_search) { //ms x+=0.01; x-=0.01; y+=0.01; y-=0.01; ws_end = System.nanoTime(); stand_wait = ws_end - start_time; } } } if (stages.get(i)[3]==true) { //porta if(x<=x_real_door) { x+=dx; xx=0; if(x>=x_real_door) { x-=dx; xx=1; } }else { x-=dx; xx=1; if(x<=x_real_door) { x+=dx; xx=0; } } if(y>y_real_door) { y-=dy; yy=1; } if (x>=x_real_door-10 && y<=y_real_door+10) { y-=15; } } if(x<=xleft_f) { x+=dx; xx=0; y-=dy; //giati door panw boolean stage[] = new boolean[4]; stage[0]=false; stage[1]=false; stage[2]=false; stage[3]=true; long ws_end =System.currentTimeMillis(); stand_wait = ws_end - start_time; while (stand_wait < stand_wait_search) { //ms x+=0.01; x-=0.01; y+=0.01; y-=0.01; ws_end = System.nanoTime(); stand_wait = ws_end - start_time; } stages.set(i, stage); } if(x>=xright_f) { x-=dx; xx=1; y-=dy; yy=1; } if(y>=ybottom_f) { y-=dy; yy=1; x-=dx; xx=1; } if(y<=ytop_f) { if(stages.get(i)[3]==false) { y+=dy; yy=0; } } for(int j=1; j<floorLimits.size(); j++) { int xleft=floorLimits.get(j).get(0)-10; //-10 to vazoyme giati to obj exei size=10 int xright=floorLimits.get(j).get(1); int ybottom=floorLimits.get(j).get(2); int ytop=floorLimits.get(j).get(3)-10; if (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { if (yy==0) { y-=dy; } if (yy==1) { y+=dy; } while (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { if(i%2==0) { if (j%2==0) { y-=dy; }else { y+=dy; } }else { y+=dy; } if (xx==0) { x-=dx; } //0.5*dx; } if (xx==1) { x+=dx; } //0.5*dx; } } break; } } } } public void category4(int i, int xleft_f, int xright_f, int ybottom_f, int ytop_f, double dxp, double dyp) { //epilegei proion->volta katastima (oxi tameio, den fevgei) //ara apo stage[0] -> stage[1] if(dxp < x_real_door) { //1st case //if ya stadia kai analoga na paei pros tin antistoixi katefthinsi //prepei na ta kanei me tin seira ara tha ecxo 3 metavlites tis opoies px otan ftasei sto proion tha kanei true afti poy einai ya na paei sto tameio//meta otan tha ftastei sto tameio tha kanei true afti poy einai ya na fygei//kai ennoeite i proti poy tha mpainei tha nai i true metavliti mexri na ftasei k me to poy ftanei tin kanei false ya na min ksanampei //eite mporoyme na exoume enan array 2d me 3 theseis ya kathe boolean metavliti toy analogoy stadioy//opoy i kathe thesi toy array tha antistoixei se kathe object//giati den ginete na xoyme mia ksexoy metavliti boolean kathos trexei afti i sinartisi ya kathe vima kathe antikimenoy!! int xx=1000; //xx=0 -> x+=dx alliws xx=1 -> x-=dx, ara meta an xx=0 -> x-=dx k an xx=1 -> x+=dx int yy=1000; if (stages.get(i)[0]==true) { //dld an einai sto stadio poy prospathei na paei pros to proion if(x>dxp) { x-=dx; xx=1; } if(y<dyp) { y+=dy; yy=0; } if(x<=dxp && y>=dyp) { //shmainei oti efase sto prooion boolean stage[] = new boolean[4]; stage[0]=false; //afto to kanoyme false giati den eimaste allo se afto to stadio stage[1]=true; //afto to afinoyme ws exxei giati einai afto poy synexizei tin volta sto katastima stage[2]=false; //afto to allazoyme se true giati imaste se afto to stadio poy theloyme na paei sto tameio stage[3]=false; //to afisnoyme ws exei stages.set(i, stage); long ws_end = System.currentTimeMillis(); stand_wait = ws_end - start_time; while (stand_wait < stand_wait_search) { //ms x+=0.01; x-=0.01; y+=0.01; y-=0.01; ws_end = System.nanoTime(); stand_wait = ws_end - start_time; } } } if (stages.get(i)[1]==true) { //dld an einai sto stadio poy prospathei na paei pros to proion random(i, xleft_f, xright_f, ybottom_f, ytop_f); } if(x<=xleft_f) { x+=dx; xx=0; y-=dy; //giati door panw yy=1; random(i, xleft_f, xright_f, ybottom_f, ytop_f); } if(x>=xright_f) { x-=dx; xx=1; y-=dy; yy=1; random(i, xleft_f, xright_f, ybottom_f, ytop_f); } if(y>=ybottom_f) { y-=dy; yy=1; x-=dx; xx=1; random(i, xleft_f, xright_f, ybottom_f, ytop_f); } if(y<=ytop_f) { y+=dy; yy=0; random(i, xleft_f, xright_f, ybottom_f, ytop_f); } for(int j=1; j<floorLimits.size(); j++) { int xleft=floorLimits.get(j).get(0)-10; //-10 to vazoyme giati to obj exei size=10 int xright=floorLimits.get(j).get(1); int ybottom=floorLimits.get(j).get(2); int ytop=floorLimits.get(j).get(3)-10; if (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { if (yy==0) { y-=dy; } if (yy==1) { y+=dy; } while (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { if(i%2==0) { if (j%2==0) { y-=dy; }else { y+=dy; } }else { y+=dy; } if (xx==0) { x-=dx; } //0.5*dx; } if (xx==1) { x+=dx; } //0.5*dx; } } break; } } }else { //if (dxp>=x_real_door) int xx=1000; //xx=0 -> x+=dx alliws xx=1 -> x-=dx, ara meta an xx=0 -> x-=dx k an xx=1 -> x+=dx int yy=1000; //edw to proion vriskete pio deksia tis portas, ara me to poy mpainei o pelatis simenei oti to x toy ine mikrotero apo to proion, afoy mpainei apo tin porta!!! if (stages.get(i)[0]==true) { //dld an einai sto stadio poy prospathei na paei pros to proion if(x<dxp) { x+=dx; xx=0; } if(y<dyp) { y+=dy; yy=0; } if(x>=dxp && y>=dyp) { //shmainei oti efase sto prooion boolean stage[] = new boolean[4]; stage[0]=false; //afto to kanoyme false giati den eimaste allo se afto to stadio stage[1]=true; //afto to afinoyme ws exxei giati einai afto poy synexizei tin volta sto katastima stage[2]=false; //afto to allazoyme se true giati imaste se afto to stadio poy theloyme na paei sto tameio stage[3]=false; //to afisnoyme ws exei stages.set(i, stage); long ws_end = System.currentTimeMillis(); stand_wait = ws_end - start_time; while (stand_wait < stand_wait_search) { //ms x+=0.01; x-=0.01; y+=0.01; y-=0.01; ws_end = System.nanoTime(); stand_wait = ws_end - start_time; } } } if (stages.get(i)[1]==true) { //dld an einai sto stadio poy prospathei na paei pros to proion random(i, xleft_f, xright_f, ybottom_f, ytop_f); } if(x<=xleft_f) { x+=dx; xx=0; y-=dy; //giati door panw yy=1; random(i, xleft_f, xright_f, ybottom_f, ytop_f); } if(x>=xright_f) { x-=dx; xx=1; y-=dy; yy=1; random(i, xleft_f, xright_f, ybottom_f, ytop_f); } if(y>=ybottom_f) { y-=dy; yy=1; x-=dx; xx=1; random(i, xleft_f, xright_f, ybottom_f, ytop_f); } if(y<=ytop_f) { y+=dy; yy=0; random(i, xleft_f, xright_f, ybottom_f, ytop_f); } for(int j=1; j<floorLimits.size(); j++) { int xleft=floorLimits.get(j).get(0)-10; //-10 to vazoyme giati to obj exei size=10 int xright=floorLimits.get(j).get(1); int ybottom=floorLimits.get(j).get(2); int ytop=floorLimits.get(j).get(3)-10; if (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { if (yy==0) { y-=dy; } if (yy==1) { y+=dy; } while (y>=ytop && y<=ybottom && x>=xleft && x<=xright) { if(i%2==0) { if (j%2==0) { y-=dy; }else { y+=dy; } }else { y+=dy; } if (xx==0) { x-=dx; } //0.5*dx; } if (xx==1) { x+=dx; } //0.5*dx; } } break; } } } } public String writeFile(int no) { int num=no; //eksagogi data for costumer behavior String writeline = "Costumer: "+num+" -> "+coordinates_products.get(num); return writeline; } public void draw(Graphics g) { //afto einai gia aftoys toys pelates poy tha mpoune meta!!! //950,20 gia floor plan 1 kai 450,600 if (x_real_door==450 && y_real_door==600) { if(x==485 && y==610) { //einai apla ta x_door kai y_door poy exo hdh yplogismena, apla ya syntomia, sto telos na to allaksw.. g.setColor(java.awt.Color.white); g.fillRect((int) x, (int) y, size, size); }else { g.setColor(generateRandomColor()); g.fillRect((int) x, (int) y, size, size); } }else { if(x==960 && y==10) { //einai apla ta x_door kai y_door poy exo hdh yplogismena, apla ya syntomia, sto telos na to allaksw.. g.setColor(java.awt.Color.white); g.fillRect((int) x, (int) y, size, size); }else { g.setColor(generateRandomColor()); g.fillRect((int) x, (int) y, size, size); } } } private Color generateRandomColor() { int R = (int) (Math.random() * 256); int G = (int) (Math.random() * 256); int B = (int) (Math.random() * 256); if (color_first) { Color c = new Color(R, G, B); color_first=false; col=c; return c; } else { return col; } } }
SotiriaKa/My-Generator
Object.java
41,841
/* * Copyright (c) 2015 The Interedition Development Group. * * This file is part of CollateX. * * CollateX is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CollateX is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CollateX. If not, see <http://www.gnu.org/licenses/>. */ package eu.interedition.collatex.dekker; import eu.interedition.collatex.AbstractTest; import eu.interedition.collatex.CollationAlgorithmFactory; import eu.interedition.collatex.VariantGraph; import eu.interedition.collatex.VariantGraph.Vertex; import eu.interedition.collatex.matching.EqualityTokenComparator; import eu.interedition.collatex.simple.SimpleWitness; import org.junit.Before; import org.junit.Test; import java.util.HashSet; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class TranspositionGraphTest extends AbstractTest { @Before public void setup() { collationAlgorithm = CollationAlgorithmFactory.dekker(new EqualityTokenComparator()); ((InspectableCollationAlgorithm) collationAlgorithm).setMergeTranspositions(true); } @Test public void transpositions() { final SimpleWitness[] w = createWitnesses("the black and white cat", "the white and black cat", "the black and black cat"); final VariantGraph graph = collate(w[0], w[1]); assertEquals(2, graph.transpositions().size()); collate(graph, w[2]); final Set<Set<VariantGraph.Vertex>> transposed = graph.transpositions(); assertEquals(2, transposed.size()); } @Test public void noTransposition() { assertEquals(0, collate("no transposition", "no transposition").transpositions().size()); assertEquals(0, collate("a b", "c a").transpositions().size()); } @Test public void oneTransposition() { assertEquals(1, collate("a b", "b a").transpositions().size()); } @Test public void multipleTranspositions() { assertEquals(1, collate("a b c", "b c a").transpositions().size()); } @Test public void testTranspositionLimiter1() { final SimpleWitness a = new SimpleWitness("A", "X a b"); final SimpleWitness b = new SimpleWitness("B", "a b X"); VariantGraph graph = collate(a, b); assertEquals(1, graph.transpositions().size()); } //test case supplied by Troy @Test public void testGreekTwoWitnesses() { SimpleWitness[] w = createWitnesses( "και αποκριθεισ ειπεν αυτω ου βλεπεισ ταυτασ μεγαλασ οικοδομασ αμην λεγω σοι ο(υ μη α)φεθη ωδε λιθοσ επι λιθω (οσ ου) μη καταλυθη", // "και αποκριθεισ ο ι̅σ̅ ειπεν αυτω βλεπεισ Ταυτασ τασ μεγαλασ οικοδομασ λεγω υμιν ου μη αφεθη λιθοσ επι λιθου οσ ου μη καταλυθη"); VariantGraph graph = collate(w[0], w[1]); Set<Set<Vertex>> transpositions = graph.transpositions(); assertTrue(transpositions.isEmpty()); } //test case supplied by Troy @Test public void testGreekThreeWitnesses() { SimpleWitness[] w = createWitnesses("και αποκριθεισ ειπεν αυτω ου βλεπεισ ταυτασ μεγαλασ οικοδομασ αμην λεγω σοι ο(υ μη α)φεθη ωδε λιθοσ επι λιθω (οσ ου) μη καταλυθη", "και αποκριθεισ ο ι̅σ̅ ειπεν αυτω βλεπεισ Ταυτασ τασ μεγαλασ οικοδομασ λεγω υμιν ου μη αφεθη λιθοσ επι λιθου οσ ου μη καταλυθη", "και ο ι̅σ̅ αποκριθεισ ειπεν αυτω βλεπεισ ταυτασ τασ μεγαλασ οικοδομασ ου μη αφεθη λιθοσ επι λιθον οσ ου μη καταλυθη"); VariantGraph graph = collate(w[0], w[1], w[2]); Set<Set<Vertex>> transpositions = graph.transpositions(); assertEquals(1, transpositions.size()); Set<Vertex> transposition = transpositions.iterator().next(); Set<String> transposedVertices = new HashSet<>(); for (Vertex transposedVertex : transposition) { transposedVertices.add(transposedVertex.toString()); } assertTrue(transposedVertices.contains("[B:2:'ο']")); assertTrue(transposedVertices.contains("[C:2:'ι̅σ̅']")); } }
interedition/collatex
collatex-core/src/test/java/eu/interedition/collatex/dekker/TranspositionGraphTest.java
41,845
package eu.interedition.collatex.dekker; import eu.interedition.collatex.AbstractTest; import eu.interedition.collatex.Token; import eu.interedition.collatex.VariantGraph; import eu.interedition.collatex.Witness; import eu.interedition.collatex.dekker.island.Coordinate; import eu.interedition.collatex.dekker.island.Island; import eu.interedition.collatex.simple.SimpleWitness; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import java.util.*; import static eu.interedition.collatex.dekker.token_index.VariantGraphMatcher.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; public class DekkerAlgorithmTest extends AbstractTest { // helper method // note: x = start coordinate of witness token // note: y = start coordinate of base token //TODO: replace Island by a real Vector class private void assertIslandAsVectorEquals(int x, int y, int length, Collection<Island> islands) { Coordinate startCoordinate = new Coordinate(x, y); Coordinate endCoordinate = new Coordinate(x + length - 1, y + length - 1); Island expected = new Island(startCoordinate, endCoordinate); Assert.assertTrue("Islands are: " + islands, islands.contains(expected)); } @Test public void testExample1() { final SimpleWitness[] w = createWitnesses("This morning the cat observed little birds in the trees.", "The cat was observing birds in the little trees this morning, it observed birds for two hours."); DekkerAlgorithm aligner = new DekkerAlgorithm(); VariantGraph graph = new VariantGraph(); List<SimpleWitness> witnesses = new ArrayList<>(); witnesses.addAll(Arrays.asList(w)); aligner.collate(graph, witnesses); // List<Block> blocks = aligner.tokenIndex.getNonOverlappingBlocks(); // Set<String> blocksAsString = new HashSet<>(); // blocks.stream().map(interval -> interval.getNormalizedForm()).forEach(blocksAsString::add); // Set<String> expected = new HashSet<>(Arrays.asList("birds in the", "the cat", "this morning", ".", "little", "observed", "trees")); // Assert.assertEquals(expected, blocksAsString); // List<Block.Instance> instances = aligner.tokenIndex.getBlockInstancesForWitness(w[0]); // Assert.assertEquals("[this morning, the cat, observed, little, birds in the, trees, .]", instances.toString()); // instances = aligner.tokenIndex.getBlockInstancesForWitness(w[1]); // Assert.assertEquals("[the cat, birds in the, little, trees, this morning, observed, .]", instances.toString()); Set<Island> islands = aligner.getAllPossibleIslands(); assertIslandAsVectorEquals(0, 2, 2, islands); // the cat assertIslandAsVectorEquals(4, 6, 3, islands); // birds in the assertIslandAsVectorEquals(7, 5, 1, islands); // little assertIslandAsVectorEquals(8, 9, 1, islands); // trees assertIslandAsVectorEquals(9, 0, 2, islands); // this morning assertIslandAsVectorEquals(13, 4, 1, islands); // observed assertIslandAsVectorEquals(18, 10, 1, islands); // . assertEquals(16, islands.size()); List<Island> selectedIslands = aligner.getPreferredIslands(); assertIslandAsVectorEquals(0, 2, 2, selectedIslands); // the cat assertIslandAsVectorEquals(4, 6, 3, selectedIslands); // birds in the assertIslandAsVectorEquals(7, 5, 1, selectedIslands); // little assertIslandAsVectorEquals(8, 9, 1, selectedIslands); // trees assertIslandAsVectorEquals(9, 0, 2, selectedIslands); // this morning assertIslandAsVectorEquals(13, 4, 1, selectedIslands); // observed assertIslandAsVectorEquals(18, 10, 1, selectedIslands); // . assertEquals(7, selectedIslands.size()); //Todo: assert transpositions // assertPhraseMatches("this morning", "observed", "little"); // System.out.println(aligner.transpositions); assertThat(graph, graph(w[0]).non_aligned("this", "morning").aligned("the", "cat").non_aligned("observed").non_aligned("little").aligned("birds", "in", "the").aligned("trees", ".")); assertThat(graph, graph(w[1]).aligned("the", "cat").non_aligned("was", "observing").aligned("birds", "in", "the").non_aligned("little").aligned("trees").non_aligned("this", "morning").non_aligned(",", "it").non_aligned("observed", "birds", "for", "two", "hours").aligned(".")); } @Test public void testCaseVariantGraphThreeWitnesses() { final SimpleWitness[] w = createWitnesses("The quick brown fox jumps over the lazy dog", "The fast brown fox jumps over the black dog", "The red fox jumps over the fence"); DekkerAlgorithm aligner = new DekkerAlgorithm(); VariantGraph graph = new VariantGraph(); aligner.collate(graph, w); assertThat(graph, graph(w[0]).aligned("the").non_aligned("quick").aligned("brown", "fox", "jumps", "over", "the").non_aligned("lazy").aligned("dog")); assertThat(graph, graph(w[1]).aligned("the").non_aligned("fast").aligned("brown", "fox", "jumps", "over", "the").non_aligned("black").aligned("dog")); assertThat(graph, graph(w[2]).aligned("the").non_aligned("red").aligned("fox", "jumps", "over", "the").non_aligned("fence")); } @Test public void test3dMatching1() { SimpleWitness[] witnesses = createWitnesses("a", "b", "c", "a b c"); DekkerAlgorithm aligner = new DekkerAlgorithm(); VariantGraph graph = new VariantGraph(); aligner.collate(graph, witnesses); assertThat(graph, graph(witnesses[3]).aligned("a", "b", "c")); } @Test public void testCaseVariantGraphTwoDifferentWitnesses() { final SimpleWitness[] w = createWitnesses("The quick brown fox jumps over the lazy dog", "The fast brown fox jumps over the black dog"); DekkerAlgorithm aligner = new DekkerAlgorithm(); VariantGraph graph = new VariantGraph(); aligner.collate(graph, w); assertThat(graph, graph(w[0]).aligned("the").non_aligned("quick").aligned("brown", "fox", "jumps", "over", "the").non_aligned("lazy").aligned("dog")); assertThat(graph, graph(w[1]).aligned("the").non_aligned("fast").aligned("brown", "fox", "jumps", "over", "the").non_aligned("black").aligned("dog")); } @Test public void testMergeFirstWitness() { final SimpleWitness[] w = createWitnesses("The same stuff"); DekkerAlgorithm aligner = new DekkerAlgorithm(); VariantGraph g = new VariantGraph(); // we collate the first witness --> is a simple add aligner.collate(g, w); VariantGraph.Vertex[] vertices = aligner.vertex_array; assertVertexEquals("the", vertices[0]); assertVertexEquals("same", vertices[1]); assertVertexEquals("stuff", vertices[2]); } @Test public void testTwoEqualWitnesses() { final SimpleWitness[] w = createWitnesses("The same stuff", "The same stuff"); DekkerAlgorithm aligner = new DekkerAlgorithm(); VariantGraph graph = new VariantGraph(); aligner.collate(graph, w); assertThat(graph, graph(w[0]).aligned("the", "same", "stuff")); assertThat(graph, graph(w[1]).aligned("the", "same", "stuff")); } @Test public void testCaseTwoWitnessesReplacement() { final SimpleWitness[] w = createWitnesses("The black cat", "The red cat"); DekkerAlgorithm aligner = new DekkerAlgorithm(); VariantGraph g = new VariantGraph(); aligner.collate(g, w); assertThat(g, graph(w[0]).aligned("the").non_aligned("black").aligned("cat")); assertThat(g, graph(w[1]).aligned("the").non_aligned("red").aligned("cat")); } @Test public void testDifficultCase1TranspositionOrTwoReplacements() { final SimpleWitness[] w = createWitnesses("the cat and the dog", "the dog and the cat"); DekkerAlgorithm aligner = new DekkerAlgorithm(); VariantGraph g = new VariantGraph(); aligner.collate(g, w); assertThat(g, graph(w[0]).aligned("the").non_aligned("cat").aligned("and the").non_aligned("dog")); assertThat(g, graph(w[1]).aligned("the").non_aligned("dog").aligned("and the").non_aligned("cat")); } @Test public void testDifficultCase2HermansOverreachTest() { final SimpleWitness[] w = createWitnesses("a b c d F g h i ! K ! q r s t", "a b c d F g h i ! q r s t", "a b c d E g h i ! q r s t"); DekkerAlgorithm aligner = new DekkerAlgorithm(); VariantGraph graph = new VariantGraph(); aligner.collate(graph, w); assertThat(graph, graph(w[0]).aligned("a b c d f g h i !").non_aligned("k !").aligned("q r s t")); assertThat(graph, graph(w[1]).aligned("a b c d f g h i ! q r s t")); assertThat(graph, graph(w[2]).aligned("a b c d").non_aligned("e").aligned("g h i ! q r s t")); } // Depth should be taken into account during transposition phase @Ignore @Test public void testDifficultCase3DepthShouldMatter() { // 1: a, b, c, d, e // 2: a, e, c, d // 3: a, X, X, d, b final SimpleWitness[] w = createWitnesses("a b c d e", "a e c d", "a d b"); DekkerAlgorithm aligner = new DekkerAlgorithm(); VariantGraph graph = new VariantGraph(); aligner.collate(graph, w); assertThat(graph, graph(w[0]).aligned("a b c d").non_aligned("e")); assertThat(graph, graph(w[1]).aligned("a").non_aligned("e").aligned("c d")); assertThat(graph, graph(w[2]).aligned("a").aligned("d").non_aligned("b")); } // NOTE: transpositions are asserted in another test @Test public void testDifficultCasePartialRightOverlapAndTranspositions() { SimpleWitness[] w = createWitnesses("και αποκριθεισ ειπεν αυτω ου βλεπεισ ταυτασ μεγαλασ οικοδομασ αμην λεγω σοι ο(υ μη α)φεθη ωδε λιθοσ επι λιθω (οσ ου) μη καταλυθη", "και αποκριθεισ ο ι̅σ̅ ειπεν αυτω βλεπεισ Ταυτασ τασ μεγαλασ οικοδομασ λεγω υμιν ου μη αφεθη λιθοσ επι λιθου οσ ου μη καταλυθη", "και ο ι̅σ̅ αποκριθεισ ειπεν αυτω βλεπεισ ταυτασ τασ μεγαλασ οικοδομασ ου μη αφεθη λιθοσ επι λιθον οσ ου μη καταλυθη"); DekkerAlgorithm aligner = new DekkerAlgorithm(); VariantGraph graph = new VariantGraph(); aligner.collate(graph, w); List<SortedMap<Witness, Set<Token>>> t = table(graph); assertEquals("|και| | |αποκριθεισ| | |ειπεν|αυτω|ου|βλεπεισ|ταυτασ| |μεγαλασ|οικοδομασ|αμην|λεγω|σοι|ο(υ|μη|α)φεθη|ωδε|λιθοσ|επι|λιθω|(οσ|ου)|μη|καταλυθη|", toString(t, w[0])); assertEquals("|και| | |αποκριθεισ|ο|ι̅σ̅|ειπεν|αυτω| |βλεπεισ|ταυτασ|τασ|μεγαλασ|οικοδομασ| |λεγω|υμιν|ου|μη|αφεθη| |λιθοσ|επι|λιθου|οσ|ου|μη|καταλυθη|", toString(t, w[1])); assertEquals("|και|ο|ι̅σ̅|αποκριθεισ| | |ειπεν|αυτω| |βλεπεισ|ταυτασ|τασ|μεγαλασ|οικοδομασ| | | |ου|μη|αφεθη| |λιθοσ|επι|λιθον|οσ|ου|μη|καταλυθη|", toString(t, w[2])); } @Test public void testDifficultCasePartialDarwin() { SimpleWitness[] w = createWitnesses("those to which the parent-species have been exposed under nature. There is, also, I think, some probability", "those to which the parent-species have been exposed under nature. There is also, I think, some probability", "those to which the parent-species had been exposed under nature. There is also, I think, some probability", "those to which the parent-species had been exposed under nature. There is, also, some probability"); DekkerAlgorithm aligner = new DekkerAlgorithm(); VariantGraph graph = new VariantGraph(); aligner.collate(graph, w); assertThat(graph, graph(w[0]).aligned("those to which the parent-species have been exposed under nature . there is , also , i think , some probability")); assertThat(graph, graph(w[1]).aligned("those to which the parent-species have been exposed under nature . there is also , i think , some probability")); assertThat(graph, graph(w[2]).aligned("those to which the parent-species had been exposed under nature . there is also , i think , some probability")); assertThat(graph, graph(w[3]).aligned("those to which the parent-species had been exposed under nature . there is , ").aligned(4, "also").aligned(", some probability")); } }
interedition/collatex
collatex-core/src/test/java/eu/interedition/collatex/dekker/DekkerAlgorithmTest.java
41,847
/* * Copyright (c) 2015 The Interedition Development Group. * * This file is part of CollateX. * * CollateX is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CollateX is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CollateX. If not, see <http://www.gnu.org/licenses/>. */ package eu.interedition.collatex.dekker; import eu.interedition.collatex.AbstractTest; import eu.interedition.collatex.VariantGraph; import eu.interedition.collatex.VariantGraph.Vertex; import eu.interedition.collatex.matching.EqualityTokenComparator; import eu.interedition.collatex.simple.SimpleWitness; import org.junit.Before; import org.junit.Test; import java.util.HashSet; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class TranspositionGraphTest extends AbstractTest { @Before public void setup() { collationAlgorithm = new DekkerAlgorithm(new EqualityTokenComparator()); ((DekkerAlgorithm) collationAlgorithm).setMergeTranspositions(true); } @Test public void transpositions() { final SimpleWitness[] w = createWitnesses("the black and white cat", "the white and black cat", "the black and black cat"); final VariantGraph graph = collate(w[0], w[1]); assertEquals(2, graph.transpositions().size()); collate(graph, w[2]); final Set<Set<VariantGraph.Vertex>> transposed = graph.transpositions(); assertEquals(2, transposed.size()); } @Test public void noTransposition() { assertEquals(0, collate("no transposition", "no transposition").transpositions().size()); assertEquals(0, collate("a b", "c a").transpositions().size()); } @Test public void oneTransposition() { assertEquals(1, collate("a b", "b a").transpositions().size()); } @Test public void multipleTranspositions() { assertEquals(1, collate("a b c", "b c a").transpositions().size()); } @Test public void testTranspositionLimiter1() { final SimpleWitness a = new SimpleWitness("A", "X a b"); final SimpleWitness b = new SimpleWitness("B", "a b X"); VariantGraph graph = collate(a, b); assertEquals(1, graph.transpositions().size()); } //test case supplied by Troy @Test public void testGreekTwoWitnesses() { SimpleWitness[] w = createWitnesses( "και αποκριθεισ ειπεν αυτω ου βλεπεισ ταυτασ μεγαλασ οικοδομασ αμην λεγω σοι ο(υ μη α)φεθη ωδε λιθοσ επι λιθω (οσ ου) μη καταλυθη", // "και αποκριθεισ ο ι̅σ̅ ειπεν αυτω βλεπεισ Ταυτασ τασ μεγαλασ οικοδομασ λεγω υμιν ου μη αφεθη λιθοσ επι λιθου οσ ου μη καταλυθη"); VariantGraph graph = collate(w[0], w[1]); Set<Set<Vertex>> transpositions = graph.transpositions(); assertTrue(transpositions.isEmpty()); } //test case supplied by Troy @Test public void testGreekThreeWitnesses() { SimpleWitness[] w = createWitnesses("και αποκριθεισ ειπεν αυτω ου βλεπεισ ταυτασ μεγαλασ οικοδομασ αμην λεγω σοι ο(υ μη α)φεθη ωδε λιθοσ επι λιθω (οσ ου) μη καταλυθη", "και αποκριθεισ ο ι̅σ̅ ειπεν αυτω βλεπεισ Ταυτασ τασ μεγαλασ οικοδομασ λεγω υμιν ου μη αφεθη λιθοσ επι λιθου οσ ου μη καταλυθη", "και ο ι̅σ̅ αποκριθεισ ειπεν αυτω βλεπεισ ταυτασ τασ μεγαλασ οικοδομασ ου μη αφεθη λιθοσ επι λιθον οσ ου μη καταλυθη"); VariantGraph graph = collate(w[0], w[1], w[2]); Set<Set<Vertex>> transpositions = graph.transpositions(); assertEquals(1, transpositions.size()); Set<Vertex> transposition = transpositions.iterator().next(); Set<String> transposedVertices = new HashSet<>(); for (Vertex transposedVertex : transposition) { transposedVertices.add(transposedVertex.toString()); } assertTrue(transposedVertices.contains("[B:2:'ο']")); assertTrue(transposedVertices.contains("[C:2:'ι̅σ̅']")); } }
rhdekker/collatex
collatex-core/src/test/java/eu/interedition/collatex/dekker/TranspositionGraphTest.java
41,848
/* * Copyright (c) 2015 The Interedition Development Group. * * This file is part of CollateX. * * CollateX is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CollateX is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CollateX. If not, see <http://www.gnu.org/licenses/>. */ package eu.interedition.collatex.dekker; import eu.interedition.collatex.AbstractTest; import eu.interedition.collatex.CollationAlgorithmFactory; import eu.interedition.collatex.VariantGraph; import eu.interedition.collatex.VariantGraph.Vertex; import eu.interedition.collatex.matching.EqualityTokenComparator; import eu.interedition.collatex.simple.SimpleWitness; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.util.HashSet; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @Ignore public class TranspositionGraphTest extends AbstractTest { @Before public void setup() { collationAlgorithm = CollationAlgorithmFactory.dekker(new EqualityTokenComparator()); ((InspectableCollationAlgorithm) collationAlgorithm).setMergeTranspositions(true); } @Test public void transpositions() { final SimpleWitness[] w = createWitnesses("the black and white cat", "the white and black cat", "the black and black cat"); final VariantGraph graph = collate(w[0], w[1]); assertEquals(2, graph.transpositions().size()); collate(graph, w[2]); final Set<Set<VariantGraph.Vertex>> transposed = graph.transpositions(); assertEquals(2, transposed.size()); } @Test public void noTransposition() { assertEquals(0, collate("no transposition", "no transposition").transpositions().size()); assertEquals(0, collate("a b", "c a").transpositions().size()); } @Test public void oneTransposition() { assertEquals(1, collate("a b", "b a").transpositions().size()); } @Test public void multipleTranspositions() { assertEquals(1, collate("a b c", "b c a").transpositions().size()); } @Test public void testTranspositionLimiter1() { final SimpleWitness a = new SimpleWitness("A", "X a b"); final SimpleWitness b = new SimpleWitness("B", "a b X"); VariantGraph graph = collate(a, b); assertEquals(1, graph.transpositions().size()); } //test case supplied by Troy @Test public void testGreekTwoWitnesses() { SimpleWitness[] w = createWitnesses( "και αποκριθεισ ειπεν αυτω ου βλεπεισ ταυτασ μεγαλασ οικοδομασ αμην λεγω σοι ο(υ μη α)φεθη ωδε λιθοσ επι λιθω (οσ ου) μη καταλυθη", // "και αποκριθεισ ο ι̅σ̅ ειπεν αυτω βλεπεισ Ταυτασ τασ μεγαλασ οικοδομασ λεγω υμιν ου μη αφεθη λιθοσ επι λιθου οσ ου μη καταλυθη"); VariantGraph graph = collate(w[0], w[1]); Set<Set<Vertex>> transpositions = graph.transpositions(); assertTrue(transpositions.isEmpty()); } //test case supplied by Troy @Test public void testGreekThreeWitnesses() { SimpleWitness[] w = createWitnesses("και αποκριθεισ ειπεν αυτω ου βλεπεισ ταυτασ μεγαλασ οικοδομασ αμην λεγω σοι ο(υ μη α)φεθη ωδε λιθοσ επι λιθω (οσ ου) μη καταλυθη", "και αποκριθεισ ο ι̅σ̅ ειπεν αυτω βλεπεισ Ταυτασ τασ μεγαλασ οικοδομασ λεγω υμιν ου μη αφεθη λιθοσ επι λιθου οσ ου μη καταλυθη", "και ο ι̅σ̅ αποκριθεισ ειπεν αυτω βλεπεισ ταυτασ τασ μεγαλασ οικοδομασ ου μη αφεθη λιθοσ επι λιθον οσ ου μη καταλυθη"); VariantGraph graph = collate(w[0], w[1], w[2]); Set<Set<Vertex>> transpositions = graph.transpositions(); assertEquals(1, transpositions.size()); Set<Vertex> transposition = transpositions.iterator().next(); Set<String> transposedVertices = new HashSet<>(); for (Vertex transposedVertex : transposition) { transposedVertices.add(transposedVertex.toString()); } assertTrue(transposedVertices.contains("[B:2:'ο']")); assertTrue(transposedVertices.contains("[C:2:'ι̅σ̅']")); } }
DHUniWien/collatex
collatex-core/src/test/java/eu/interedition/collatex/dekker/TranspositionGraphTest.java
41,849
package eu.interedition.collatex.dekker; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Set; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import com.google.common.collect.Sets; import eu.interedition.collatex.AbstractTest; import eu.interedition.collatex.VariantGraph; import eu.interedition.collatex.VariantGraph.Transposition; import eu.interedition.collatex.VariantGraph.Vertex; import eu.interedition.collatex.matching.EqualityTokenComparator; import eu.interedition.collatex.simple.SimpleWitness; public class TranspositionGraphTest extends AbstractTest { @Before public void setup() { collationAlgorithm = new DekkerAlgorithm(new EqualityTokenComparator()); ((DekkerAlgorithm)collationAlgorithm).setMergeTranspositions(true); } @Test public void transpositions() { final SimpleWitness[] w = createWitnesses("the black and white cat", "the white and black cat", "the black and black cat"); final VariantGraph graph = collate(w[0], w[1]); assertEquals(2, graph.transpositions().size()); collate(graph, w[2]); final Set<VariantGraph.Transposition> transposed = graph.transpositions(); assertEquals(2, transposed.size()); } @Test public void noTransposition() { assertEquals(0, collate("no transposition", "no transposition").transpositions().size()); assertEquals(0, collate("a b", "c a").transpositions().size()); } @Test public void oneTransposition() { assertEquals(1, collate("a b", "b a").transpositions().size()); } @Test public void multipleTranspositions() { assertEquals(1, collate("a b c", "b c a").transpositions().size()); } @Test public void testTranspositionLimiter1() { final SimpleWitness a = new SimpleWitness("A","X a b"); final SimpleWitness b = new SimpleWitness("B","a b X"); VariantGraph graph = collate(a,b); assertEquals(1, graph.transpositions().size()); } //test case supplied by Troy @Test public void testGreekTwoWitnesses() { SimpleWitness[] w = createWitnesses( "και αποκριθεισ ειπεν αυτω ου βλεπεισ ταυτασ μεγαλασ οικοδομασ αμην λεγω σοι ο(υ μη α)φεθη ωδε λιθοσ επι λιθω (οσ ου) μη καταλυθη", // "και αποκριθεισ ο ι̅σ̅ ειπεν αυτω βλεπεισ Ταυτασ τασ μεγαλασ οικοδομασ λεγω υμιν ου μη αφεθη λιθοσ επι λιθου οσ ου μη καταλυθη"); VariantGraph graph = collate(w[0], w[1]); Set<Transposition> transpositions = graph.transpositions(); assertTrue(transpositions.isEmpty()); } //test case supplied by Troy @Test public void testGreekThreeWitnesses() { SimpleWitness[] w = createWitnesses("και αποκριθεισ ειπεν αυτω ου βλεπεισ ταυτασ μεγαλασ οικοδομασ αμην λεγω σοι ο(υ μη α)φεθη ωδε λιθοσ επι λιθω (οσ ου) μη καταλυθη", "και αποκριθεισ ο ι̅σ̅ ειπεν αυτω βλεπεισ Ταυτασ τασ μεγαλασ οικοδομασ λεγω υμιν ου μη αφεθη λιθοσ επι λιθου οσ ου μη καταλυθη", "και ο ι̅σ̅ αποκριθεισ ειπεν αυτω βλεπεισ ταυτασ τασ μεγαλασ οικοδομασ ου μη αφεθη λιθοσ επι λιθον οσ ου μη καταλυθη"); VariantGraph graph = collate(w[0], w[1], w[2]); Set<Transposition> transpositions = graph.transpositions(); assertEquals(1, transpositions.size()); Transposition transposition = transpositions.iterator().next(); Set<String> transposedVertices = Sets.newHashSet(); for (Vertex transposedVertex : transposition) { transposedVertices.add(transposedVertex.toString()); } assertTrue(transposedVertices.contains("[B:2:'ο']")); assertTrue(transposedVertices.contains("[C:2:'ι̅σ̅']")); } }
plutext/collatex
collatex-core/src/test/java/eu/interedition/collatex/dekker/TranspositionGraphTest.java
41,953
/* * Copyright © 2020 Mark Raynsford <[email protected]> https://www.io7m.com * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package com.io7m.jade.tests; import com.io7m.jade.api.ApplicationNames; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; import java.util.stream.Stream; public final class ApplicationNamesTest { @TestFactory public Stream<DynamicTest> testValidNames() { return Stream.of( "Window.23_", "παράθυρο.23_", "窗口.23_", "окно.23_", "_23.شباك", "ອ.23_" ).map(name -> { return DynamicTest.dynamicTest( "testValid" + name, () -> { ApplicationNames.checkValid(name); }); }); } @TestFactory public Stream<DynamicTest> testInvalidNames() { return Stream.of( "-", "", "," ).map(name -> { return DynamicTest.dynamicTest( "testInvalid" + name, () -> { Assertions.assertThrows(IllegalArgumentException.class, () -> { ApplicationNames.checkValid(name); }); }); }); } }
io7m-com/jade
com.io7m.jade.tests/src/main/java/com/io7m/jade/tests/ApplicationNamesTest.java
41,958
package wiktionary.to.xml.full; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Locale; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; /** * @author Joel Korhonen * * Parses languages from pre-downloaded Greek Wiktionary language page and stores into language file * to be used by ReadStripped.java * * Downloaded this page: https://el.wikipedia.org/wiki/Κατάλογος_κωδικών_ISO_639 * -> langs/el/el-language_codes.html */ public class ParseLangsEl { private final static Logger LOGGER = Logger.getLogger(ParseLangsEl.class .getName()); private static FileHandler fileHandler; private static SimpleFormatter formatterTxt; //private final static String LF = System.getProperty("line.separator"); static { try { fileHandler = new FileHandler(ParseLangsEl.class.getName() + ".log"); } catch (Exception e) { System.err.println("" + "LOGGING ERROR, CANNOT INITIALIZE FILEHANDLER"); e.printStackTrace(); System.exit(255); } //LOGGER.setLevel(Level.ALL); LOGGER.setLevel(Level.INFO); // Create txt Formatter formatterTxt = new SimpleFormatter(); fileHandler.setFormatter(formatterTxt); LOGGER.addHandler(fileHandler); } public static void main(String[] args) { String inFileName = null; String outFileName = null; try { if (args.length != 2) { LOGGER.log(Level.SEVERE, "Wrong number of arguments, expected 2, got " + args.length); LOGGER.log(Level.SEVERE, " ParseLangsEl Input_filename Output_filename"); LOGGER.log(Level.SEVERE, "Arg[max] = '" + args[args.length-1] + "'"); System.exit(255); } inFileName = args[0]; outFileName = args[1]; LOGGER.info("Input: " + inFileName); LOGGER.info("Output: " + outFileName); ParseLangsEl parseLangs = new ParseLangsEl(); FileOutputStream fos = null; fos = new FileOutputStream(outFileName); PrintWriter out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(fos, "UTF-8"))); out.println("name;abr"); parseLangs.process(out, inFileName); out.close(); System.exit(0); } catch (Exception e) { String msg = e.getMessage(); LOGGER.severe(msg); e.printStackTrace(); System.exit(255); } } /* * Process the input file and produce output * @throws Exception */ private void process (PrintWriter out, String inFileName) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader( new FileInputStream(inFileName), "UTF-8")); String s = in.readLine(); String abr = null; String name = null; boolean trOn = false; int tdLine = -1; int lineNbr = 0; while (s != null) { lineNbr++; if (s.indexOf("<tr>") > -1) { trOn = true; tdLine = 0; } else if (trOn && s.indexOf("<td>") > -1) { tdLine++; /* <tr> <td>abhaasi</td> <td>{{ab}}</td> <td>abhaasi</td> <td><a href="//fi.wikipedia.org/wiki/fi:Abhaasin_kieli" class="extiw" title="w:fi:Abhaasin kieli">abhaasi</a> Wikipediassa, vapaassa tietosanakirjassa</td> </tr> */ switch(tdLine) { case 1: int nameStart = s.indexOf("<td>"); if (nameStart > -1) { int nameEnd = s.substring(nameStart+4).indexOf("</td>"); name = s.substring(nameStart+4, nameStart+4+nameEnd); if (name != null && name.length() > 0) name = name.trim(); // Make 1st letter uppercase if (name.length() > 1) name = name.substring(0,1).toUpperCase(new Locale("el","EL")) + name.substring(1); else if (name.trim().length() == 1) name = name.substring(0,1).toUpperCase(new Locale("el","EL")); LOGGER.fine(" name: '" + name + "'"); } ; break; case 2: int abrStart = s.indexOf("<td>{{"); if (abrStart > -1) { int abrEnd = s.substring(abrStart+6).indexOf("}}</td>"); abr = s.substring(abrStart+6, abrStart+6+abrEnd); LOGGER.fine("abr: '" + abr + "'"); } break; case 3: ; // This is just name again break; case 4: ; // This is additional info, such as an URL break; default: LOGGER.warning("Error in parse, s='" + s + "'"); //throw new Exception("Error in parse"); } } else if (s.indexOf("</tr>") > -1) { trOn = false; tdLine = 0; if (abr != null && name != null) { LOGGER.info(abr + ": " + name); out.println(name + ";" + abr); abr = null; name = null; } } s = in.readLine(); } LOGGER.info("Processed " + lineNbr + " lines"); in.close(); } }
korhoj/wiktionary-convert
wikt2xmlfull/src/wiktionary/to/xml/full/ParseLangsEl.java
41,959
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.hughes.android.dictionary.engine; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import com.hughes.android.dictionary.parser.DictFileParser; import com.hughes.android.dictionary.parser.wiktionary.WiktionaryLangs; import com.ibm.icu.text.Transliterator; import junit.framework.TestCase; public class LanguageTest extends TestCase { public void testGermanSort() { final Transliterator normalizer = Transliterator.createFromRules("", Language.de.getDefaultNormalizerRules(), Transliterator.FORWARD); assertEquals("aüääss", normalizer.transform("aueAeAEß")); final List<String> words = Arrays.asList( "er-ben", "erben", "Erben", "Erbse", "Erbsen", "essen", "Essen", "Grosformat", "Grosformats", "Grossformat", "Großformat", "Grossformats", "Großformats", "Großpoo", "Großpoos", "Hörvermögen", "Hörweite", "hos", "Höschen", "Hostel", "hulle", "Hulle", "huelle", "Huelle", "hülle", "Hülle", "Huellen", "Hüllen", "Hum" ); final NormalizeComparator comparator = new NormalizeComparator(normalizer, Language.de.getCollator(), 7); assertEquals(1, comparator.compare("hülle", "huelle")); assertEquals(-1, comparator.compare("huelle", "hülle")); assertEquals(-1, comparator.compare("hülle", "Hülle")); assertEquals("hülle", normalizer.transform("Hülle")); assertEquals("hulle", normalizer.transform("Hulle")); final List<String> sorted = new ArrayList<>(words); // Collections.shuffle(shuffled, new Random(0)); sorted.sort(comparator); System.out.println(sorted); for (int i = 0; i < words.size(); ++i) { System.out.println(words.get(i) + "\t" + sorted.get(i)); assertEquals(words.get(i), sorted.get(i)); } } public void testEnglishSort() { final Transliterator normalizer = Transliterator.createFromRules("", Language.en.getDefaultNormalizerRules(), Transliterator.FORWARD); final List<String> words = Arrays.asList( "pre-print", "preppie", "preppy", "preprocess"); final List<String> sorted = new ArrayList<>(words); final NormalizeComparator comparator = new NormalizeComparator(normalizer, Language.en.getCollator(), 7); sorted.sort(comparator); for (int i = 0; i < words.size(); ++i) { if (i > 0) { assertTrue(comparator.compare(words.get(i-1), words.get(i)) < 0); } System.out.println(words.get(i) + "\t" + sorted.get(i)); assertEquals(words.get(i), sorted.get(i)); } assertTrue(comparator.compare("pre-print", "preppy") < 0); } public void testLanguage() { assertEquals(Language.de, Language.lookup("de")); assertEquals(Language.en, Language.lookup("en")); assertEquals("es", Language.lookup("es").getIsoCode()); } public void testTextNorm() { //final Transliterator transliterator = Transliterator.getInstance("Any-Latin; Upper; Lower; 'oe' > 'o'; NFD; [:Nonspacing Mark:] Remove; NFC", Transliterator.FORWARD); final Transliterator transliterator = Transliterator.createFromRules("", ":: Any-Latin; :: Upper; :: Lower; 'oe' > 'o'; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC ;", Transliterator.FORWARD); assertEquals("hoschen", transliterator.transliterate("Höschen")); assertEquals("hoschen", transliterator.transliterate("Hoeschen")); assertEquals("grosspoo", transliterator.transliterate("Großpoo")); assertEquals("kyanpasu", transliterator.transliterate("キャンパス")); assertEquals("alphabetikos katalogos", transliterator.transliterate("Αλφαβητικός Κατάλογος")); assertEquals("biologiceskom", transliterator.transliterate("биологическом")); } public void testHalfTextNorm() { final Transliterator transliterator = Transliterator.createFromRules("", ":: Any-Latin; ' ' > ; :: Lower; ", Transliterator.FORWARD); assertEquals("kyanpasu", transliterator.transliterate("キャンパス")); assertEquals("alphabētikóskatálogos", transliterator.transliterate("Αλφαβητικός Κατάλογος")); assertEquals("biologičeskom", transliterator.transliterate("биологическом")); assertEquals("xièxiè", transliterator.transliterate("謝謝")); assertEquals("xièxiè", transliterator.transliterate("谢谢")); assertEquals("diànnǎo", transliterator.transliterate("電腦")); assertEquals("diànnǎo", transliterator.transliterate("电脑")); assertEquals("jìsuànjī", transliterator.transliterate("計算機")); assertEquals("jìsuànjī", transliterator.transliterate("计算机")); } public void testChinese() { final Language cmn = Language.lookup("cmn"); final Transliterator transliterator = Transliterator.createFromRules("", cmn.getDefaultNormalizerRules(), Transliterator.FORWARD); assertEquals("xiexie", transliterator.transliterate("謝謝")); assertEquals("xiexie", transliterator.transliterate("谢谢")); assertEquals("diannao", transliterator.transliterate("電腦")); assertEquals("diannao", transliterator.transliterate("电脑")); assertEquals("jisuanji", transliterator.transliterate("計算機")); assertEquals("jisuanji", transliterator.transliterate("计算机")); assertEquals("chengjiu", transliterator.transliterate("成就")); } public void testArabic() { final Language ar = Language.lookup("ar"); final Transliterator transliterator = Transliterator.createFromRules("", ar.getDefaultNormalizerRules(), Transliterator.FORWARD); // These don't seem quite right.... assertEquals("haswb", transliterator.transliterate("حاسوب")); assertEquals("kmbywtr", transliterator.transliterate("كمبيوتر")); assertEquals("{\u200e كمبيوتر \u200e}", Language.fixBidiText("{كمبيوتر}")); assertEquals("{a=\u200e كمبيوتر \u200e}", Language.fixBidiText("{a=كمبيوتر}")); assertEquals("(\u200e كمبيوتر \u200e)", Language.fixBidiText("(كمبيوتر)")); assertEquals("أنثى أنْثَى (’únθā) {f}, إناث (’ināθ) {p}, اناثى (’anāθā) {p}", Language.fixBidiText("أنثى أنْثَى (’únθā) {f}, إناث (’ināθ) {p}, اناثى (’anāθā) {p}")); } public void testThai() { final Language th = Language.lookup("TH"); final Transliterator transliterator = Transliterator.createFromRules("", th.getDefaultNormalizerRules(), Transliterator.FORWARD); // Not sure these are right, just to know... assertEquals("d", transliterator.transliterate("ด")); assertEquals("di", transliterator.transliterate("ด ี")); assertEquals("dii", transliterator.transliterate("ดีี")); assertEquals(Collections.singleton("ดีี"), DictFileParser.tokenize("ดีี", DictFileParser.NON_CHAR)); } public void testEnWiktionaryNames() { final Set<String> enLangs = new LinkedHashSet<>(WiktionaryLangs.isoCodeToEnWikiName.keySet()); final List<String> names = new ArrayList<>(); for (final String code : WiktionaryLangs.isoCodeToEnWikiName.keySet()) { names.add(WiktionaryLangs.isoCodeToEnWikiName.get(code)); enLangs.add(code.toLowerCase()); } Collections.sort(names); System.out.println(names); //assertEquals(enLangs, Language.isoCodeToResources.keySet()); } }
rdoeffinger/DictionaryPC
src/com/hughes/android/dictionary/engine/LanguageTest.java
41,964
package org.apache.lucene.analysis.icu; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.io.Reader; import java.io.StringReader; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.BaseTokenStreamTestCase; import org.apache.lucene.analysis.MockTokenizer; import org.apache.lucene.analysis.Tokenizer; import org.apache.lucene.analysis.core.KeywordTokenizer; import org.apache.lucene.analysis.TokenStream; import com.ibm.icu.text.Transliterator; import com.ibm.icu.text.UnicodeSet; /** * Test the ICUTransformFilter with some basic examples. */ public class TestICUTransformFilter extends BaseTokenStreamTestCase { public void testBasicFunctionality() throws Exception { checkToken(Transliterator.getInstance("Traditional-Simplified"), "簡化字", "简化字"); checkToken(Transliterator.getInstance("Katakana-Hiragana"), "ヒラガナ", "ひらがな"); checkToken(Transliterator.getInstance("Fullwidth-Halfwidth"), "アルアノリウ", "アルアノリウ"); checkToken(Transliterator.getInstance("Any-Latin"), "Αλφαβητικός Κατάλογος", "Alphabētikós Katálogos"); checkToken(Transliterator.getInstance("NFD; [:Nonspacing Mark:] Remove"), "Alphabētikós Katálogos", "Alphabetikos Katalogos"); checkToken(Transliterator.getInstance("Han-Latin"), "中国", "zhōng guó"); } public void testCustomFunctionality() throws Exception { String rules = "a > b; b > c;"; // convert a's to b's and b's to c's checkToken(Transliterator.createFromRules("test", rules, Transliterator.FORWARD), "abacadaba", "bcbcbdbcb"); } public void testCustomFunctionality2() throws Exception { String rules = "c { a > b; a > d;"; // convert a's to b's and b's to c's checkToken(Transliterator.createFromRules("test", rules, Transliterator.FORWARD), "caa", "cbd"); } public void testOptimizer() throws Exception { String rules = "a > b; b > c;"; // convert a's to b's and b's to c's Transliterator custom = Transliterator.createFromRules("test", rules, Transliterator.FORWARD); assertTrue(custom.getFilter() == null); new ICUTransformFilter(new KeywordTokenizer(new StringReader("")), custom); assertTrue(custom.getFilter().equals(new UnicodeSet("[ab]"))); } public void testOptimizer2() throws Exception { checkToken(Transliterator.getInstance("Traditional-Simplified; CaseFold"), "ABCDE", "abcde"); } public void testOptimizerSurrogate() throws Exception { String rules = "\\U00020087 > x;"; // convert CJK UNIFIED IDEOGRAPH-20087 to an x Transliterator custom = Transliterator.createFromRules("test", rules, Transliterator.FORWARD); assertTrue(custom.getFilter() == null); new ICUTransformFilter(new KeywordTokenizer(new StringReader("")), custom); assertTrue(custom.getFilter().equals(new UnicodeSet("[\\U00020087]"))); } private void checkToken(Transliterator transform, String input, String expected) throws IOException { TokenStream ts = new ICUTransformFilter(new KeywordTokenizer((new StringReader(input))), transform); assertTokenStreamContents(ts, new String[] { expected }); } /** blast some random strings through the analyzer */ public void testRandomStrings() throws Exception { final Transliterator transform = Transliterator.getInstance("Any-Latin"); Analyzer a = new Analyzer() { @Override protected TokenStreamComponents createComponents(String fieldName, Reader reader) { Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); return new TokenStreamComponents(tokenizer, new ICUTransformFilter(tokenizer, transform)); } }; checkRandomData(random(), a, 1000*RANDOM_MULTIPLIER); } public void testEmptyTerm() throws IOException { Analyzer a = new Analyzer() { @Override protected TokenStreamComponents createComponents(String fieldName, Reader reader) { Tokenizer tokenizer = new KeywordTokenizer(reader); return new TokenStreamComponents(tokenizer, new ICUTransformFilter(tokenizer, Transliterator.getInstance("Any-Latin"))); } }; checkOneTerm(a, "", ""); } }
yuchien302/Lucene
.svn/pristine/0f/0fbde9a384e830b3607948e694c54989590db8b2.svn-base
41,969
package org.apache.lucene.analysis.icu; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.io.StringReader; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.BaseTokenStreamTestCase; import org.apache.lucene.analysis.MockTokenizer; import org.apache.lucene.analysis.Tokenizer; import org.apache.lucene.analysis.core.KeywordTokenizer; import org.apache.lucene.analysis.TokenStream; import com.ibm.icu.text.Transliterator; import com.ibm.icu.text.UnicodeSet; /** * Test the ICUTransformFilter with some basic examples. */ public class TestICUTransformFilter extends BaseTokenStreamTestCase { public void testBasicFunctionality() throws Exception { checkToken(Transliterator.getInstance("Traditional-Simplified"), "簡化字", "简化字"); checkToken(Transliterator.getInstance("Katakana-Hiragana"), "ヒラガナ", "ひらがな"); checkToken(Transliterator.getInstance("Fullwidth-Halfwidth"), "アルアノリウ", "アルアノリウ"); checkToken(Transliterator.getInstance("Any-Latin"), "Αλφαβητικός Κατάλογος", "Alphabētikós Katálogos"); checkToken(Transliterator.getInstance("NFD; [:Nonspacing Mark:] Remove"), "Alphabētikós Katálogos", "Alphabetikos Katalogos"); checkToken(Transliterator.getInstance("Han-Latin"), "中国", "zhōng guó"); } public void testCustomFunctionality() throws Exception { String rules = "a > b; b > c;"; // convert a's to b's and b's to c's checkToken(Transliterator.createFromRules("test", rules, Transliterator.FORWARD), "abacadaba", "bcbcbdbcb"); } public void testCustomFunctionality2() throws Exception { String rules = "c { a > b; a > d;"; // convert a's to b's and b's to c's checkToken(Transliterator.createFromRules("test", rules, Transliterator.FORWARD), "caa", "cbd"); } public void testOptimizer() throws Exception { String rules = "a > b; b > c;"; // convert a's to b's and b's to c's Transliterator custom = Transliterator.createFromRules("test", rules, Transliterator.FORWARD); assertTrue(custom.getFilter() == null); final KeywordTokenizer input = new KeywordTokenizer(); input.setReader(new StringReader("")); new ICUTransformFilter(input, custom); assertTrue(custom.getFilter().equals(new UnicodeSet("[ab]"))); } public void testOptimizer2() throws Exception { checkToken(Transliterator.getInstance("Traditional-Simplified; CaseFold"), "ABCDE", "abcde"); } public void testOptimizerSurrogate() throws Exception { String rules = "\\U00020087 > x;"; // convert CJK UNIFIED IDEOGRAPH-20087 to an x Transliterator custom = Transliterator.createFromRules("test", rules, Transliterator.FORWARD); assertTrue(custom.getFilter() == null); final KeywordTokenizer input = new KeywordTokenizer(); input.setReader(new StringReader("")); new ICUTransformFilter(input, custom); assertTrue(custom.getFilter().equals(new UnicodeSet("[\\U00020087]"))); } private void checkToken(Transliterator transform, String input, String expected) throws IOException { final KeywordTokenizer input1 = new KeywordTokenizer(); input1.setReader(new StringReader(input)); TokenStream ts = new ICUTransformFilter(input1, transform); assertTokenStreamContents(ts, new String[] { expected }); } /** blast some random strings through the analyzer */ public void testRandomStrings() throws Exception { final Transliterator transform = Transliterator.getInstance("Any-Latin"); Analyzer a = new Analyzer() { @Override protected TokenStreamComponents createComponents(String fieldName) { Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false); return new TokenStreamComponents(tokenizer, new ICUTransformFilter(tokenizer, transform)); } }; checkRandomData(random(), a, 1000*RANDOM_MULTIPLIER); a.close(); } public void testEmptyTerm() throws IOException { Analyzer a = new Analyzer() { @Override protected TokenStreamComponents createComponents(String fieldName) { Tokenizer tokenizer = new KeywordTokenizer(); return new TokenStreamComponents(tokenizer, new ICUTransformFilter(tokenizer, Transliterator.getInstance("Any-Latin"))); } }; checkOneTerm(a, "", ""); a.close(); } }
knewter/solr-redis-xjoin-example
lucene_solr_5_3/.svn/pristine/9e/9eafcdb5f8a19898b8ae6a82d6bc87987740ae54.svn-base
41,970
package android.gr.katastima; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Resources; import android.location.Location; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.Log; import android.view.InflateException; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.google.android.gms.common.Scopes; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.Scope; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.api.services.people.v1.PeopleScopes; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks { private SectionsPagerAdapter mSectionsPagerAdapter; private ViewPager mViewPager; public static Context context; public static Activity activity; public static GoogleSignInAccount account; public static GoogleApiClient mGoogleApiClient; public static int CUR_POINTS; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); context = getApplicationContext(); activity = this; //Permission to read external storage if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, 20); } else { ServerCommunication.init(); } Functions.LOCATION_FINDER = new LocationFinder(context, this); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Create the adapter that will return a fragment for each of the three // primary sections of the activity. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.container); mViewPager.setAdapter(mSectionsPagerAdapter); TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(mViewPager); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestServerAuthCode(getString(R.string.server_client_id)) .requestIdToken(getString(R.string.server_client_id)) .requestEmail() .requestScopes(new Scope(Scopes.PROFILE)) .requestScopes(new Scope(PeopleScopes.USER_BIRTHDAY_READ)) .build(); mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, this) .addOnConnectionFailedListener(this) .addConnectionCallbacks(this) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if(requestCode == 20) { if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { ServerCommunication.init(); } } } @Override public void onStart() { super.onStart(); mGoogleApiClient.connect(); // Check if already signed in account = GoogleSignIn.getLastSignedInAccount(context); if(account != null) { ServerCommunication.PointGetter task = new ServerCommunication.PointGetter(false); task.execute(account.getEmail(), getString(R.string.appId), getString(R.string.userId)); } } @Override public void onStop() { super.onStop(); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { GoogleApiAvailability gaa = GoogleApiAvailability.getInstance(); Dialog dialog = gaa.getErrorDialog(this, connectionResult.getErrorCode(), 101); dialog.show(); } @Override public void onConnected(@Nullable Bundle bundle) {} @Override public void onConnectionSuspended(int i) {} public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class below). return PlaceholderFragment.newInstance(position + 1); } @Override public int getCount() { // Show 4 total pages. return 4; } public Fragment setItem(int position) { return PlaceholderFragment.newInstance(position + 1); } @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return "Home"; case 1: return "Catalog"; case 2: return "Offers"; case 3: return "Map"; } return null; } } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { private static final String ARG_SECTION_NUMBER = "section_number"; public static PlaceholderFragment newInstance(int sectionNumber) { PlaceholderFragment fragment = new PlaceholderFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = null; int section = getArguments().getInt(ARG_SECTION_NUMBER); if (section == 1) { // Home try { rootView = inflater.inflate(R.layout.fragment_main, container, false); Resources res = context.getResources(); ImageView img = (ImageView) rootView.findViewById(R.id.shopImage); DisplayMetrics dm = Resources.getSystem().getDisplayMetrics(); int reqW = dm.widthPixels; int reqH = Functions.convertDpToPx(200); img.setImageBitmap(Functions.getScaledBitmap(res, res.getIdentifier(context.getString(R.string.shop_image), "drawable", context.getPackageName()), reqW, reqH)); } catch(InflateException e) {} } else if (section == 2) { // Τιμοκατάλογος rootView = inflater.inflate(R.layout.fragment_timokatalogos, container, false); ListView listView = (ListView) rootView.findViewById(R.id.list_of_products); ProductListAdapter listAdapter = new ProductListAdapter(getActivity(), Functions.calcProductlist(getActivity())); listView.setAdapter(listAdapter); } else if (section == 3) { // Προσφορές if(MainActivity.account != null) { // If user has logged in rootView = inflater.inflate(R.layout.fragment_gifts, container, false); final TextView textView = (TextView) rootView.findViewById(R.id.pointsTxt); ListView listView = (ListView) rootView.findViewById(R.id.list_of_gifts); final ArrayList<Gift> gifts = Functions.calcGiftlist(getActivity()); GiftListAdapter listAdapter = new GiftListAdapter(getActivity(), gifts); listView.setAdapter(listAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(MainActivity.CUR_POINTS >= Integer.parseInt(gifts.get(position).points)) { ServerCommunication.CodeCreation task = new ServerCommunication.CodeCreation(); task.execute( account.getEmail(), getString(R.string.appId), getString(R.string.userId), gifts.get(position).points); } else { Toast.makeText(context,"Not enough points..", Toast.LENGTH_SHORT).show(); } } }); final Button b = (Button) rootView.findViewById(R.id.checkInBtn); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean gpsOn = Functions.LOCATION_FINDER.checkIfGpsIsEnabled(); if(gpsOn) { Location l = Functions.LOCATION_FINDER.getLocation(); if(l != null) { String[] details = Functions.getMapDetails(context); float distance = Functions.getDistance(Double.parseDouble(details[1]), Double.parseDouble(details[2]), l.getLatitude(), l.getLongitude()); if(distance <= Integer.parseInt(getString(R.string.distance_from_shop))) { ServerCommunication.PointSetter task = new ServerCommunication.PointSetter(); task.execute(MainActivity.account.getEmail(),getString(R.string.appId), getString(R.string.userId), "5"); } else Toast.makeText(context, "Too far. Distance: " + distance, Toast.LENGTH_SHORT).show(); } else Toast.makeText(context, "Try again..", Toast.LENGTH_SHORT).show(); } } }); String points = "POINTS(" + MainActivity.CUR_POINTS + ")"; textView.setText(points); } else { // Show sign in button rootView = inflater.inflate(R.layout.fragment_google_signin, container, false); SignInButton signInButton = (SignInButton) rootView.findViewById(R.id.sign_in_button); signInButton.setSize(SignInButton.SIZE_WIDE); signInButton.setColorScheme(SignInButton.COLOR_DARK); signInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { signIn(); } }); } } else if(section == 4) { // Map rootView = inflater.inflate(R.layout.fragment_maps, container, false); FragmentManager fm = getChildFragmentManager(); SupportMapFragment mapFragment = SupportMapFragment.newInstance(); mapFragment.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(GoogleMap googleMap) { String[] details = Functions.getMapDetails(context); LatLng place = new LatLng(Float.parseFloat(details[1]), Float.parseFloat(details[2])); googleMap.addMarker(new MarkerOptions().position(place).title(details[0])); googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(place, 16f)); } }); fm.beginTransaction().replace(R.id.rl_map, mapFragment).commit(); } return rootView; } private void signIn() { Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); MainActivity.activity.startActivityForResult(signInIntent, 100); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == 100) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); if(result.isSuccess()) { account = result.getSignInAccount(); ServerCommunication.PeopleTask task = new ServerCommunication.PeopleTask(this, account.getIdToken(), account.getEmail()); task.execute(account.getServerAuthCode()); } } } public void updateUi(String response) { if(response != null) { if(response.equals("Illegal")) { account = null; } else if(response.equals("legal")) { ServerCommunication.PointGetter task = new ServerCommunication.PointGetter(true); task.execute(account.getEmail(), getString(R.string.appId), getString(R.string.userId)); // Update ui mSectionsPagerAdapter.setItem(2); mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.setCurrentItem(2); } } else account = null; } public static void updatePointTxtView() { try { TextView textView = (TextView) activity.findViewById(R.id.pointsTxt); Log.e("POINTS", MainActivity.CUR_POINTS + ""); textView.setText("POINTS(" +MainActivity.CUR_POINTS + ")"); } catch (Exception e) { e.printStackTrace(); } } }
ETS-Android5/nodejsandroidproduction
Android Studio Project/app/src/main/java/android/gr/katastima/MainActivity.java
41,974
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.hughes.android.dictionary.engine; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import junit.framework.TestCase; import com.hughes.android.dictionary.parser.DictFileParser; import com.hughes.android.dictionary.parser.wiktionary.WiktionaryLangs; import com.ibm.icu.text.Transliterator; public class LanguageTest extends TestCase { public void testGermanSort() { final Transliterator normalizer = Transliterator.createFromRules("", Language.de.getDefaultNormalizerRules(), Transliterator.FORWARD); assertEquals("aüääss", normalizer.transform("aueAeAEß")); final List<String> words = Arrays.asList( "er-ben", "erben", "Erben", "Erbse", "Erbsen", "essen", "Essen", "Grosformat", "Grosformats", "Grossformat", "Großformat", "Grossformats", "Großformats", "Großpoo", "Großpoos", "Hörvermögen", "Hörweite", "hos", "Höschen", "Hostel", "hulle", "Hulle", "huelle", "Huelle", "hülle", "Hülle", "Huellen", "Hüllen", "Hum" ); final NormalizeComparator comparator = new NormalizeComparator(normalizer, Language.de.getCollator(), 7); assertEquals(1, comparator.compare("hülle", "huelle")); assertEquals(-1, comparator.compare("huelle", "hülle")); assertEquals(-1, comparator.compare("hülle", "Hülle")); assertEquals("hülle", normalizer.transform("Hülle")); assertEquals("hulle", normalizer.transform("Hulle")); final List<String> sorted = new ArrayList<String>(words); // Collections.shuffle(shuffled, new Random(0)); Collections.sort(sorted, comparator); System.out.println(sorted.toString()); for (int i = 0; i < words.size(); ++i) { System.out.println(words.get(i) + "\t" + sorted.get(i)); assertEquals(words.get(i), sorted.get(i)); } } public void testEnglishSort() { final Transliterator normalizer = Transliterator.createFromRules("", Language.en.getDefaultNormalizerRules(), Transliterator.FORWARD); final List<String> words = Arrays.asList( "pre-print", "preppie", "preppy", "preprocess"); final List<String> sorted = new ArrayList<String>(words); final NormalizeComparator comparator = new NormalizeComparator(normalizer, Language.en.getCollator(), 7); Collections.sort(sorted, comparator); for (int i = 0; i < words.size(); ++i) { if (i > 0) { assertTrue(comparator.compare(words.get(i-1), words.get(i)) < 0); } System.out.println(words.get(i) + "\t" + sorted.get(i)); assertEquals(words.get(i), sorted.get(i)); } assertTrue(comparator.compare("pre-print", "preppy") < 0); } public void testLanguage() { assertEquals(Language.de, Language.lookup("de")); assertEquals(Language.en, Language.lookup("en")); assertEquals("es", Language.lookup("es").getIsoCode()); } public void testTextNorm() { //final Transliterator transliterator = Transliterator.getInstance("Any-Latin; Upper; Lower; 'oe' > 'o'; NFD; [:Nonspacing Mark:] Remove; NFC", Transliterator.FORWARD); final Transliterator transliterator = Transliterator.createFromRules("", ":: Any-Latin; :: Upper; :: Lower; 'oe' > 'o'; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC ;", Transliterator.FORWARD); assertEquals("hoschen", transliterator.transliterate("Höschen")); assertEquals("hoschen", transliterator.transliterate("Hoeschen")); assertEquals("grosspoo", transliterator.transliterate("Großpoo")); assertEquals("kyanpasu", transliterator.transliterate("キャンパス")); assertEquals("alphabetikos katalogos", transliterator.transliterate("Αλφαβητικός Κατάλογος")); assertEquals("biologiceskom", transliterator.transliterate("биологическом")); } public void testHalfTextNorm() { final Transliterator transliterator = Transliterator.createFromRules("", ":: Any-Latin; ' ' > ; :: Lower; ", Transliterator.FORWARD); assertEquals("kyanpasu", transliterator.transliterate("キャンパス")); assertEquals("alphabētikóskatálogos", transliterator.transliterate("Αλφαβητικός Κατάλογος")); assertEquals("biologičeskom", transliterator.transliterate("биологическом")); assertEquals("xièxiè", transliterator.transliterate("謝謝")); assertEquals("xièxiè", transliterator.transliterate("谢谢")); assertEquals("diànnǎo", transliterator.transliterate("電腦")); assertEquals("diànnǎo", transliterator.transliterate("电脑")); assertEquals("jìsuànjī", transliterator.transliterate("計算機")); assertEquals("jìsuànjī", transliterator.transliterate("计算机")); } public void testChinese() { final Language cmn = Language.lookup("cmn"); final Transliterator transliterator = Transliterator.createFromRules("", cmn.getDefaultNormalizerRules(), Transliterator.FORWARD); assertEquals("xiexie", transliterator.transliterate("謝謝")); assertEquals("xiexie", transliterator.transliterate("谢谢")); assertEquals("diannao", transliterator.transliterate("電腦")); assertEquals("diannao", transliterator.transliterate("电脑")); assertEquals("jisuanji", transliterator.transliterate("計算機")); assertEquals("jisuanji", transliterator.transliterate("计算机")); assertEquals("chengjiu", transliterator.transliterate("成就")); } public void testArabic() { final Language ar = Language.lookup("ar"); final Transliterator transliterator = Transliterator.createFromRules("", ar.getDefaultNormalizerRules(), Transliterator.FORWARD); // These don't seem quite right.... assertEquals("haswb", transliterator.transliterate("حاسوب")); assertEquals("kmbywtr", transliterator.transliterate("كمبيوتر")); assertEquals("{\u200e كمبيوتر \u200e}", Language.fixBidiText("{كمبيوتر}")); assertEquals("{a=\u200e كمبيوتر \u200e}", Language.fixBidiText("{a=كمبيوتر}")); assertEquals("(\u200e كمبيوتر \u200e)", Language.fixBidiText("(كمبيوتر)")); assertEquals("أنثى أنْثَى (’únθā) {f}, إناث (’ināθ) {p}, اناثى (’anāθā) {p}", Language.fixBidiText("أنثى أنْثَى (’únθā) {f}, إناث (’ināθ) {p}, اناثى (’anāθā) {p}")); } public void testThai() { final Language th = Language.lookup("TH"); final Transliterator transliterator = Transliterator.createFromRules("", th.getDefaultNormalizerRules(), Transliterator.FORWARD); // Not sure these are right, just to know... assertEquals("d", transliterator.transliterate("ด")); assertEquals("di", transliterator.transliterate("ด ี")); assertEquals("dii", transliterator.transliterate("ดีี")); assertEquals(Collections.singleton("ดีี"), DictFileParser.tokenize("ดีี", DictFileParser.NON_CHAR)); } public void testEnWiktionaryNames() { final Set<String> enLangs = new LinkedHashSet<String>(WiktionaryLangs.isoCodeToEnWikiName.keySet()); final List<String> names = new ArrayList<String>(); for (final String code : WiktionaryLangs.isoCodeToEnWikiName.keySet()) { names.add(WiktionaryLangs.isoCodeToEnWikiName.get(code)); enLangs.add(code.toLowerCase()); } Collections.sort(names); System.out.println(names); //assertEquals(enLangs, Language.isoCodeToResources.keySet()); } }
zorun/DictionaryPC
src/com/hughes/android/dictionary/engine/LanguageTest.java
41,980
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.lucene.analysis.icu; import com.ibm.icu.text.Transliterator; import com.ibm.icu.text.UnicodeSet; import java.io.IOException; import java.io.StringReader; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.Tokenizer; import org.apache.lucene.analysis.core.KeywordTokenizer; import org.apache.lucene.tests.analysis.BaseTokenStreamTestCase; import org.apache.lucene.tests.analysis.MockTokenizer; /** Test the ICUTransformFilter with some basic examples. */ public class TestICUTransformFilter extends BaseTokenStreamTestCase { public void testBasicFunctionality() throws Exception { checkToken(Transliterator.getInstance("Traditional-Simplified"), "簡化字", "简化字"); checkToken(Transliterator.getInstance("Katakana-Hiragana"), "ヒラガナ", "ひらがな"); checkToken(Transliterator.getInstance("Fullwidth-Halfwidth"), "アルアノリウ", "アルアノリウ"); checkToken( Transliterator.getInstance("Any-Latin"), "Αλφαβητικός Κατάλογος", "Alphabētikós Katálogos"); checkToken( Transliterator.getInstance("NFD; [:Nonspacing Mark:] Remove"), "Alphabētikós Katálogos", "Alphabetikos Katalogos"); checkToken(Transliterator.getInstance("Han-Latin"), "中国", "zhōng guó"); } public void testCustomFunctionality() throws Exception { String rules = "a > b; b > c;"; // convert a's to b's and b's to c's checkToken( Transliterator.createFromRules("test", rules, Transliterator.FORWARD), "abacadaba", "bcbcbdbcb"); } public void testCustomFunctionality2() throws Exception { String rules = "c { a > b; a > d;"; // convert a's to b's and b's to c's checkToken(Transliterator.createFromRules("test", rules, Transliterator.FORWARD), "caa", "cbd"); } public void testOptimizer() throws Exception { String rules = "a > b; b > c;"; // convert a's to b's and b's to c's Transliterator custom = Transliterator.createFromRules("test", rules, Transliterator.FORWARD); assertTrue(custom.getFilter() == null); final KeywordTokenizer input = new KeywordTokenizer(); input.setReader(new StringReader("")); new ICUTransformFilter(input, custom); assertTrue(custom.getFilter().equals(new UnicodeSet("[ab]"))); } public void testOptimizer2() throws Exception { checkToken(Transliterator.getInstance("Traditional-Simplified; CaseFold"), "ABCDE", "abcde"); } public void testOptimizerSurrogate() throws Exception { String rules = "\\U00020087 > x;"; // convert CJK UNIFIED IDEOGRAPH-20087 to an x Transliterator custom = Transliterator.createFromRules("test", rules, Transliterator.FORWARD); assertTrue(custom.getFilter() == null); final KeywordTokenizer input = new KeywordTokenizer(); input.setReader(new StringReader("")); new ICUTransformFilter(input, custom); assertTrue(custom.getFilter().equals(new UnicodeSet("[\\U00020087]"))); } private void checkToken(Transliterator transform, String input, String expected) throws IOException { final KeywordTokenizer input1 = new KeywordTokenizer(); input1.setReader(new StringReader(input)); TokenStream ts = new ICUTransformFilter(input1, transform); assertTokenStreamContents(ts, new String[] {expected}); } /** blast some random strings through the analyzer */ public void testRandomStrings() throws Exception { final Transliterator transform = Transliterator.getInstance("Any-Latin"); Analyzer a = new Analyzer() { @Override protected TokenStreamComponents createComponents(String fieldName) { Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false); return new TokenStreamComponents( tokenizer, new ICUTransformFilter(tokenizer, transform)); } }; checkRandomData(random(), a, 200 * RANDOM_MULTIPLIER); a.close(); } public void testEmptyTerm() throws IOException { Analyzer a = new Analyzer() { @Override protected TokenStreamComponents createComponents(String fieldName) { Tokenizer tokenizer = new KeywordTokenizer(); return new TokenStreamComponents( tokenizer, new ICUTransformFilter(tokenizer, Transliterator.getInstance("Any-Latin"))); } }; checkOneTerm(a, "", ""); a.close(); } }
apache/lucene
lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/TestICUTransformFilter.java
41,981
package com.onthegomap.planetiler.util; import static com.onthegomap.planetiler.util.LanguageUtils.containsOnlyLatinCharacters; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Map; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; class LanguageUtilsTest { @ParameterizedTest @CsvSource({ "abc, true", "5!, true", "5~, true", "é, true", "éś, true", "ɏə, true", "ɐ, true", "ᵿἀ, false", "Ḁỿ, true", "\u02ff\u0370, false", "\u0030\u036f, true", "日本, false", "abc本123, false", }) void testIsLatin(String in, boolean isLatin) { if (!isLatin) { assertFalse(containsOnlyLatinCharacters(in)); } else { assertEquals(in, LanguageUtils.getLatinName(Map.of( "name", in ), true)); } } @ParameterizedTest @CsvSource(value = { "null,null", "abcaāíìś+, +", "abcaāíìś, null", "日本, 日本", "abca日āíìś+, 日+", "(abc), null", "日本 (Japan), 日本", "日本 [Japan - Nippon], 日本", " Japan - Nippon (Japan) - Japan - 日本 - Japan - Nippon (Japan), 日本", "Japan - 日本~+ , 日本~+", "Japan / 日本 / Japan , 日本", }, nullValues = "null") void testRemoveNonLatin(String in, String out) { assertEquals(out, LanguageUtils.removeLatinCharacters(in)); } @ParameterizedTest @ValueSource(strings = { // OSM tags that SHOULD be eligible for name:latin feature in the output "name:en", "name:en-US", "name:en-010", "int_name", "name:fr", "name:es", "name:pt", "name:de", "name:ar", "name:it", "name:ko-Latn", "name:be-tarask", // https://wiki.openstreetmap.org/wiki/Multilingual_names#Japan "name:ja", "name:ja-Latn", "name:ja_rm", "name:ja_kana", // https://wiki.openstreetmap.org/wiki/Multilingual_names#China "name:zh-CN", "name:zh-hant-CN", "name:zh_pinyin", "name:zh_zhuyin", "name:zh-Latn-tongyong", "name:zh-Latn-pinyin", "name:zh-Latn-wadegiles", "name:yue-Latn-jyutping", // https://wiki.openstreetmap.org/wiki/Multilingual_names#France "name:fr", "name:fr-x-gallo", "name:br", "name:oc", "name:vls", "name:frp", "name:gcf", "name:gsw", }) void testLatinFallbacks(String key) { if (key.startsWith("name:")) { assertTrue(LanguageUtils.isValidOsmNameTag(key)); } assertEquals("a", LanguageUtils.getLatinName(Map.of( key, "a" ), true)); assertNull(LanguageUtils.getLatinName(Map.of( key, "ア" ), true)); assertNull(LanguageUtils.getLatinName(Map.of( key, "غ" ), true)); } @ParameterizedTest @ValueSource(strings = { // OSM tags that should NOT be eligible for name:latin feature in the output "name:signed", "name:prefix", "name:abbreviation", "name:source", "name:full", "name:adjective", "name:proposed", "name:pronunciation", "name:etymology", "name:etymology:wikidata", "name:etymology:wikipedia", "name:etymology:right", "name:etymology:left", "name:genitive", }) void testNoLatinFallback(String key) { assertFalse(LanguageUtils.isValidOsmNameTag(key)); assertEquals("Branch Hill–Loveland Road", LanguageUtils.getLatinName(Map.of( "name", "Branch Hill–Loveland Road", key, "Q22133584;Q843993" ), true)); assertEquals("rì", LanguageUtils.getLatinName(Map.of( "name", "日", key, "other" ), true)); } @ParameterizedTest @CsvSource({ "キャンパス, kyanpasu", "Αλφαβητικός Κατάλογος, Alphabētikós Katálogos", "биологическом, biologičeskom", }) void testTransliterate(String in, String out) { assertEquals(out, LanguageUtils.getLatinName(Map.of( "name", in ), true)); assertNull(LanguageUtils.getLatinName(Map.of( "name", in ), false)); } }
onthegomap/planetiler
planetiler-core/src/test/java/com/onthegomap/planetiler/util/LanguageUtilsTest.java
41,982
package life.catalogue.dao; import org.junit.Test; import static org.junit.Assert.assertEquals; public class CatCopyTest { @Test public void latinName() throws Exception { assertEquals("Abies", CopyUtil.latinName("Abies")); assertEquals("Bao wen dong fang tun", CopyUtil.latinName("Bào wén dōng fāng tún")); assertEquals("bao wen duo ji tun", CopyUtil.latinName("豹紋多紀魨")); assertEquals("Alphabetikos Katalogos", CopyUtil.latinName("Αλφαβητικός Κατάλογος")); assertEquals("Doering Spass", CopyUtil.latinName("Döring Spaß")); } }
CatalogueOfLife/backend
dao/src/test/java/life/catalogue/dao/CatCopyTest.java
41,983
package org.openmaptiles.util; import static com.onthegomap.planetiler.TestUtils.assertSubmap; import static com.onthegomap.planetiler.util.LanguageUtils.containsOnlyLatinCharacters; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import com.onthegomap.planetiler.util.Translations; import com.onthegomap.planetiler.util.Wikidata; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; class OmtLanguageUtilsTest { private final Wikidata.WikidataTranslations wikidataTranslations = new Wikidata.WikidataTranslations(); private final Translations translations = Translations.defaultProvider(List.of("en", "es", "de")) .addFallbackTranslationProvider(wikidataTranslations); @Test void testSimpleExample() { assertSubmap(Map.of( "name", "name", "name_en", "english name", "name_de", "german name" ), OmtLanguageUtils.getNames(Map.of( "name", "name", "name:en", "english name", "name:de", "german name" ), translations)); assertSubmap(Map.of( "name", "name", "name_en", "name", "name_de", "german name" ), OmtLanguageUtils.getNames(Map.of( "name", "name", "name:de", "german name" ), translations)); assertSubmap(Map.of( "name", "name", "name_en", "english name", "name_de", "name" ), OmtLanguageUtils.getNames(Map.of( "name", "name", "name:en", "english name" ), translations)); } @ParameterizedTest @CsvSource({ "abc, true", "5!, true", "5~, true", "é, true", "éś, true", "ɏə, true", "ɐ, true", "ᵿἀ, false", "Ḁỿ, true", "\u02ff\u0370, false", "\u0030\u036f, true", "日本, false", "abc本123, false", }) void testIsLatin(String in, boolean isLatin) { if (!isLatin) { assertFalse(containsOnlyLatinCharacters(in)); } else { assertEquals(in, OmtLanguageUtils.getNames(Map.of( "name", in ), translations).get("name:latin")); } } @ParameterizedTest @CsvSource(value = { "abcaāíìś+, null", "abca日āíìś+, 日+", "(abc), null", "日本 (Japan), 日本", "日本 [Japan - Nippon], 日本", " Japan - Nippon (Japan) - Japan - 日本 - Japan - Nippon (Japan), 日本", "Japan - 日本~+ , 日本~+", "Japan / 日本 / Japan , 日本", }, nullValues = "null") void testRemoveNonLatin(String in, String out) { assertEquals(out, OmtLanguageUtils.getNames(Map.of( "name", in ), translations).get("name:nonlatin")); } @ParameterizedTest @ValueSource(strings = { // OSM tags that SHOULD be eligible for name:latin feature in the output "name:en", "name:en-US", "name:en-010", "int_name", "name:fr", "name:es", "name:pt", "name:de", "name:ar", "name:it", "name:ko-Latn", "name:be-tarask", // https://wiki.openstreetmap.org/wiki/Multilingual_names#Japan "name:ja", "name:ja-Latn", "name:ja_rm", "name:ja_kana", // https://wiki.openstreetmap.org/wiki/Multilingual_names#China "name:zh-CN", "name:zh-hant-CN", "name:zh_pinyin", "name:zh_zhuyin", "name:zh-Latn-tongyong", "name:zh-Latn-pinyin", "name:zh-Latn-wadegiles", "name:yue-Latn-jyutping", // https://wiki.openstreetmap.org/wiki/Multilingual_names#France "name:fr", "name:fr-x-gallo", "name:br", "name:oc", "name:vls", "name:frp", "name:gcf", "name:gsw", }) void testLatinFallbacks(String key) { assertEquals("a", OmtLanguageUtils.getNames(Map.of( key, "a" ), translations).get("name:latin")); assertNull(OmtLanguageUtils.getNames(Map.of( key, "ア" ), translations).get("name:latin")); assertNull(OmtLanguageUtils.getNames(Map.of( key, "غ" ), translations).get("name:latin")); } @ParameterizedTest @ValueSource(strings = { // OSM tags that should NOT be eligible for name:latin feature in the output "name:signed", "name:prefix", "name:abbreviation", "name:source", "name:full", "name:adjective", "name:proposed", "name:pronunciation", "name:etymology", "name:etymology:wikidata", "name:etymology:wikipedia", "name:etymology:right", "name:etymology:left", "name:genitive", }) void testNoLatinFallback(String key) { assertSubmap(Map.of( "name", "Branch Hill–Loveland Road", "name_en", "Branch Hill–Loveland Road", "name_de", "Branch Hill–Loveland Road", "name:latin", "Branch Hill–Loveland Road", "name_int", "Branch Hill–Loveland Road" ), OmtLanguageUtils.getNames(Map.of( "name", "Branch Hill–Loveland Road", key, "Q22133584;Q843993" ), translations)); assertSubmap(Map.of( "name", "日", "name_en", "日", "name_de", "日", "name:latin", "rì", "name_int", "rì" ), OmtLanguageUtils.getNames(Map.of( "name", "日", key, "other" // don't use this latin string with invalid name keys ), translations)); } @ParameterizedTest @CsvSource({ "キャンパス, kyanpasu", "Αλφαβητικός Κατάλογος, Alphabētikós Katálogos", "биологическом, biologičeskom", }) void testTransliterate(String in, String out) { assertEquals(out, OmtLanguageUtils.getNames(Map.of( "name", in ), translations).get("name:latin")); translations.setShouldTransliterate(false); assertNull(OmtLanguageUtils.getNames(Map.of( "name", in ), translations).get("name:latin")); } @Test void testUseWikidata() { wikidataTranslations.put(123, "es", "es name"); assertSubmap(Map.of( "name:es", "es name" ), OmtLanguageUtils.getNames(Map.of( "name", "name", "wikidata", "Q123" ), translations)); } @Test void testUseOsm() { assertSubmap(Map.of( "name:es", "es name osm" ), OmtLanguageUtils.getNames(Map.of( "name", "name", "wikidata", "Q123", "name:es", "es name osm" ), translations)); } @Test void testPreferOsm() { wikidataTranslations.put(123, "es", "wd es name"); wikidataTranslations.put(123, "de", "wd de name"); assertSubmap(Map.of( "name:es", "wd es name", "name:de", "de name osm" ), OmtLanguageUtils.getNames(Map.of( "name", "name", "wikidata", "Q123", "name:de", "de name osm" ), translations)); } @Test void testDontUseTranslationsWhenNotSpecified() { var result = OmtLanguageUtils.getNamesWithoutTranslations(Map.of( "name", "name", "wikidata", "Q123", "name:es", "es name osm", "name:de", "de name osm" )); assertNull(result.get("name:es")); assertNull(result.get("name:de")); assertEquals("name", result.get("name")); } @Test void testIgnoreLanguages() { wikidataTranslations.put(123, "ja", "ja name wd"); var result = OmtLanguageUtils.getNamesWithoutTranslations(Map.of( "name", "name", "wikidata", "Q123", "name:ja", "ja name osm" )); assertNull(result.get("name:ja")); } }
openmaptiles/planetiler-openmaptiles
src/test/java/org/openmaptiles/util/OmtLanguageUtilsTest.java
41,984
package life.catalogue.dao; import org.junit.Test; import static org.junit.Assert.assertEquals; public class CatCopyTest { @Test public void latinName() throws Exception { assertEquals("Abies", CatCopy.latinName("Abies")); assertEquals("Bao wen dong fang tun", CatCopy.latinName("Bào wén dōng fāng tún")); assertEquals("bao wen duo ji tun", CatCopy.latinName("豹紋多紀魨")); assertEquals("Alphabetikos Katalogos", CatCopy.latinName("Αλφαβητικός Κατάλογος")); assertEquals("Doering Spass", CatCopy.latinName("Döring Spaß")); } }
bellmit/backend-6
dao/src/test/java/life/catalogue/dao/CatCopyTest.java
41,985
package org.xbib.elasticsearch.plugin.bundle.test.index.analysis.icu; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.Tokenizer; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.Index; import org.elasticsearch.index.analysis.TokenFilterFactory; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.ESTokenStreamTestCase; import org.xbib.elasticsearch.plugin.bundle.BundlePlugin; import java.io.StringReader; /** * ICU transform filter tests. */ public class IcuTransformFilterTests extends ESTokenStreamTestCase { public void testTransformTraditionalSimplified() throws Exception { String source = "簡化字"; String[] expected = new String[] { "简化", "字" }; String resource = "icu_transform.json"; Settings settings = Settings.builder() .loadFromStream(resource, getClass().getResourceAsStream(resource), true) .build(); ESTestCase.TestAnalysis analysis = ESTestCase.createTestAnalysis(new Index("test", "_na_"), settings, new BundlePlugin(Settings.EMPTY)); Tokenizer tokenizer = analysis.tokenizer.get("my_icu_tokenizer_ch").create(); tokenizer.setReader(new StringReader(source)); TokenFilterFactory tokenFilter = analysis.tokenFilter.get("my_icu_transformer_ch"); TokenStream tokenStream = tokenFilter.create(tokenizer); assertTokenStreamContents(tokenStream, expected); } public void testTransformHanLatin() throws Exception { String source = "中国"; String[] expected = new String[] { "zhōng guó" }; String resource = "icu_transform.json"; Settings settings = Settings.builder() .loadFromStream(resource, getClass().getResourceAsStream(resource), true) .build(); ESTestCase.TestAnalysis analysis = ESTestCase.createTestAnalysis(new Index("test", "_na_"), settings, new BundlePlugin(Settings.EMPTY)); Tokenizer tokenizer = analysis.tokenizer.get("my_icu_tokenizer_han").create(); tokenizer.setReader(new StringReader(source)); TokenFilterFactory tokenFilter = analysis.tokenFilter.get("my_icu_transformer_han"); TokenStream tokenStream = tokenFilter.create(tokenizer); assertTokenStreamContents(tokenStream, expected); } public void testTransformKatakanaHiragana() throws Exception { String source = "ヒラガナ"; String[] expected = new String[] { "ひらがな" }; String resource = "icu_transform.json"; Settings settings = Settings.builder() .loadFromStream(resource, getClass().getResourceAsStream(resource), true) .build(); ESTestCase.TestAnalysis analysis = ESTestCase.createTestAnalysis(new Index("test", "_na_"), settings, new BundlePlugin(Settings.EMPTY)); Tokenizer tokenizer = analysis.tokenizer.get("my_icu_tokenizer_katakana").create(); tokenizer.setReader(new StringReader(source)); TokenFilterFactory tokenFilter = analysis.tokenFilter.get("my_icu_transformer_katakana"); TokenStream tokenStream = tokenFilter.create(tokenizer); assertTokenStreamContents(tokenStream, expected); } public void testTransformCyrillicLatin() throws Exception { String source = "Российская Федерация"; String[] expected = new String[] { "Rossijskaâ", "Federaciâ" }; String resource = "icu_transform.json"; Settings settings = Settings.builder() .loadFromStream(resource, getClass().getResourceAsStream(resource), true) .build(); ESTestCase.TestAnalysis analysis = ESTestCase.createTestAnalysis(new Index("test", "_na_"), settings, new BundlePlugin(Settings.EMPTY)); Tokenizer tokenizer = analysis.tokenizer.get("my_icu_tokenizer_cyr").create(); tokenizer.setReader(new StringReader(source)); TokenFilterFactory tokenFilter = analysis.tokenFilter.get("my_icu_transformer_cyr"); TokenStream tokenStream = tokenFilter.create(tokenizer); assertTokenStreamContents(tokenStream, expected); } public void testTransformCyrillicLatinReverse() throws Exception { String source = "Rossijskaâ Federaciâ"; String[] expected = new String[] { "Российская", "Федерация"}; String resource = "icu_transform.json"; Settings settings = Settings.builder() .loadFromStream(resource, getClass().getResourceAsStream(resource), true) .build(); ESTestCase.TestAnalysis analysis = ESTestCase.createTestAnalysis(new Index("test", "_na_"), settings, new BundlePlugin(Settings.EMPTY)); Tokenizer tokenizer = analysis.tokenizer.get("my_icu_tokenizer_cyr").create(); tokenizer.setReader(new StringReader(source)); TokenFilterFactory tokenFilter = analysis.tokenFilter.get("my_icu_transformer_cyr_reverse"); TokenStream tokenStream = tokenFilter.create(tokenizer); assertTokenStreamContents(tokenStream, expected); } public void testTransformAnyLatin() throws Exception { String source = "Αλφαβητικός Κατάλογος"; String[] expected = new String[] { "Alphabētikós", "Katálogos" }; String resource = "icu_transform.json"; Settings settings = Settings.builder() .loadFromStream(resource, getClass().getResourceAsStream(resource), true) .build(); ESTestCase.TestAnalysis analysis = ESTestCase.createTestAnalysis(new Index("test", "_na_"), settings, new BundlePlugin(Settings.EMPTY)); Tokenizer tokenizer = analysis.tokenizer.get("my_icu_tokenizer_any_latin").create(); tokenizer.setReader(new StringReader(source)); TokenFilterFactory tokenFilter = analysis.tokenFilter.get("my_icu_transformer_any_latin"); TokenStream tokenStream = tokenFilter.create(tokenizer); assertTokenStreamContents(tokenStream, expected); } public void testTransformNFD() throws Exception { String source = "Alphabētikós Katálogos"; String[] expected = new String[] { "Alphabetikos", "Katalogos" }; String resource = "icu_transform.json"; Settings settings = Settings.builder() .loadFromStream(resource, getClass().getResourceAsStream(resource), true) .build(); ESTestCase.TestAnalysis analysis = ESTestCase.createTestAnalysis(new Index("test", "_na_"), settings, new BundlePlugin(Settings.EMPTY)); Tokenizer tokenizer = analysis.tokenizer.get("my_icu_tokenizer_nfd").create(); tokenizer.setReader(new StringReader(source)); TokenFilterFactory tokenFilter = analysis.tokenFilter.get("my_icu_transformer_nfd"); TokenStream tokenStream = tokenFilter.create(tokenizer); assertTokenStreamContents(tokenStream, expected); } public void testTransformRules() throws Exception { String source = "abacadaba"; String[] expected = new String[] { "bcbcbdbcb" }; String resource = "icu_transform.json"; Settings settings = Settings.builder() .loadFromStream(resource, getClass().getResourceAsStream(resource), true) .build(); ESTestCase.TestAnalysis analysis = ESTestCase.createTestAnalysis(new Index("test", "_na_"), settings, new BundlePlugin(Settings.EMPTY)); Tokenizer tokenizer = analysis.tokenizer.get("my_icu_tokenizer_rules").create(); tokenizer.setReader(new StringReader(source)); TokenFilterFactory tokenFilter = analysis.tokenFilter.get("my_icu_transformer_rules"); TokenStream tokenStream = tokenFilter.create(tokenizer); assertTokenStreamContents(tokenStream, expected); } }
jprante/elasticsearch-plugin-bundle
src/test/java/org/xbib/elasticsearch/plugin/bundle/test/index/analysis/icu/IcuTransformFilterTests.java
41,986
package org.apache.lucene.analysis.icu; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.io.StringReader; import org.apache.lucene.analysis.BaseTokenStreamTestCase; import org.apache.lucene.analysis.core.KeywordTokenizer; import org.apache.lucene.analysis.TokenStream; import com.ibm.icu.text.Transliterator; import com.ibm.icu.text.UnicodeSet; /** * Test the ICUTransformFilter with some basic examples. */ public class TestICUTransformFilter extends BaseTokenStreamTestCase { public void testBasicFunctionality() throws Exception { checkToken(Transliterator.getInstance("Traditional-Simplified"), "簡化字", "简化字"); checkToken(Transliterator.getInstance("Katakana-Hiragana"), "ヒラガナ", "ひらがな"); checkToken(Transliterator.getInstance("Fullwidth-Halfwidth"), "アルアノリウ", "アルアノリウ"); checkToken(Transliterator.getInstance("Any-Latin"), "Αλφαβητικός Κατάλογος", "Alphabētikós Katálogos"); checkToken(Transliterator.getInstance("NFD; [:Nonspacing Mark:] Remove"), "Alphabētikós Katálogos", "Alphabetikos Katalogos"); checkToken(Transliterator.getInstance("Han-Latin"), "中国", "zhōng guó"); } public void testCustomFunctionality() throws Exception { String rules = "a > b; b > c;"; // convert a's to b's and b's to c's checkToken(Transliterator.createFromRules("test", rules, Transliterator.FORWARD), "abacadaba", "bcbcbdbcb"); } public void testCustomFunctionality2() throws Exception { String rules = "c { a > b; a > d;"; // convert a's to b's and b's to c's checkToken(Transliterator.createFromRules("test", rules, Transliterator.FORWARD), "caa", "cbd"); } public void testOptimizer() throws Exception { String rules = "a > b; b > c;"; // convert a's to b's and b's to c's Transliterator custom = Transliterator.createFromRules("test", rules, Transliterator.FORWARD); assertTrue(custom.getFilter() == null); new ICUTransformFilter(new KeywordTokenizer(new StringReader("")), custom); assertTrue(custom.getFilter().equals(new UnicodeSet("[ab]"))); } public void testOptimizer2() throws Exception { checkToken(Transliterator.getInstance("Traditional-Simplified; CaseFold"), "ABCDE", "abcde"); } public void testOptimizerSurrogate() throws Exception { String rules = "\\U00020087 > x;"; // convert CJK UNIFIED IDEOGRAPH-20087 to an x Transliterator custom = Transliterator.createFromRules("test", rules, Transliterator.FORWARD); assertTrue(custom.getFilter() == null); new ICUTransformFilter(new KeywordTokenizer(new StringReader("")), custom); assertTrue(custom.getFilter().equals(new UnicodeSet("[\\U00020087]"))); } private void checkToken(Transliterator transform, String input, String expected) throws IOException { TokenStream ts = new ICUTransformFilter(new KeywordTokenizer((new StringReader(input))), transform); assertTokenStreamContents(ts, new String[] { expected }); } }
chrismattmann/solrcene
modules/analysis/icu/src/test/org/apache/lucene/analysis/icu/TestICUTransformFilter.java
41,987
package org.apache.lucene.analysis.icu; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.io.Reader; import java.io.StringReader; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.BaseTokenStreamTestCase; import org.apache.lucene.analysis.Tokenizer; import org.apache.lucene.analysis.core.KeywordTokenizer; import org.apache.lucene.analysis.core.WhitespaceTokenizer; import org.apache.lucene.analysis.util.ReusableAnalyzerBase; import org.apache.lucene.analysis.TokenStream; import com.ibm.icu.text.Transliterator; import com.ibm.icu.text.UnicodeSet; /** * Test the ICUTransformFilter with some basic examples. */ public class TestICUTransformFilter extends BaseTokenStreamTestCase { public void testBasicFunctionality() throws Exception { checkToken(Transliterator.getInstance("Traditional-Simplified"), "簡化字", "简化字"); checkToken(Transliterator.getInstance("Katakana-Hiragana"), "ヒラガナ", "ひらがな"); checkToken(Transliterator.getInstance("Fullwidth-Halfwidth"), "アルアノリウ", "アルアノリウ"); checkToken(Transliterator.getInstance("Any-Latin"), "Αλφαβητικός Κατάλογος", "Alphabētikós Katálogos"); checkToken(Transliterator.getInstance("NFD; [:Nonspacing Mark:] Remove"), "Alphabētikós Katálogos", "Alphabetikos Katalogos"); checkToken(Transliterator.getInstance("Han-Latin"), "中国", "zhōng guó"); } public void testCustomFunctionality() throws Exception { String rules = "a > b; b > c;"; // convert a's to b's and b's to c's checkToken(Transliterator.createFromRules("test", rules, Transliterator.FORWARD), "abacadaba", "bcbcbdbcb"); } public void testCustomFunctionality2() throws Exception { String rules = "c { a > b; a > d;"; // convert a's to b's and b's to c's checkToken(Transliterator.createFromRules("test", rules, Transliterator.FORWARD), "caa", "cbd"); } public void testOptimizer() throws Exception { String rules = "a > b; b > c;"; // convert a's to b's and b's to c's Transliterator custom = Transliterator.createFromRules("test", rules, Transliterator.FORWARD); assertTrue(custom.getFilter() == null); new ICUTransformFilter(new KeywordTokenizer(new StringReader("")), custom); assertTrue(custom.getFilter().equals(new UnicodeSet("[ab]"))); } public void testOptimizer2() throws Exception { checkToken(Transliterator.getInstance("Traditional-Simplified; CaseFold"), "ABCDE", "abcde"); } public void testOptimizerSurrogate() throws Exception { String rules = "\\U00020087 > x;"; // convert CJK UNIFIED IDEOGRAPH-20087 to an x Transliterator custom = Transliterator.createFromRules("test", rules, Transliterator.FORWARD); assertTrue(custom.getFilter() == null); new ICUTransformFilter(new KeywordTokenizer(new StringReader("")), custom); assertTrue(custom.getFilter().equals(new UnicodeSet("[\\U00020087]"))); } private void checkToken(Transliterator transform, String input, String expected) throws IOException { TokenStream ts = new ICUTransformFilter(new KeywordTokenizer((new StringReader(input))), transform); assertTokenStreamContents(ts, new String[] { expected }); } /** blast some random strings through the analyzer */ public void testRandomStrings() throws Exception { final Transliterator transform = Transliterator.getInstance("Any-Latin"); Analyzer a = new ReusableAnalyzerBase() { @Override protected TokenStreamComponents createComponents(String fieldName, Reader reader) { Tokenizer tokenizer = new WhitespaceTokenizer(TEST_VERSION_CURRENT, reader); return new TokenStreamComponents(tokenizer, new ICUTransformFilter(tokenizer, transform)); } }; checkRandomData(random, a, 1000*RANDOM_MULTIPLIER); } }
wayfair-archive/lucene-solr
modules/analysis/icu/src/test/org/apache/lucene/analysis/icu/TestICUTransformFilter.java